1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // The Google C++ Testing and Mocking Framework (Google Test)
33 #include "gtest/gtest.h"
34 #include "gtest/internal/custom/gtest.h"
35 #include "gtest/gtest-spi.h"
51 #include <ostream> // NOLINT
57 # define GTEST_HAS_GETTIMEOFDAY_ 1
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
70 # define GTEST_HAS_GETTIMEOFDAY_ 1
71 # include <sys/time.h> // NOLINT
73 // On z/OS we additionally need strings.h for strcasecmp.
74 # include <strings.h> // NOLINT
76 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
78 # include <windows.h> // NOLINT
81 #elif GTEST_OS_WINDOWS // We are on Windows proper.
83 # include <windows.h> // NOLINT
86 # include <crtdbg.h> // NOLINT
87 # include <debugapi.h> // NOLINT
88 # include <io.h> // NOLINT
89 # include <sys/timeb.h> // NOLINT
90 # include <sys/types.h> // NOLINT
91 # include <sys/stat.h> // NOLINT
93 # if GTEST_OS_WINDOWS_MINGW
94 // MinGW has gettimeofday() but not _ftime64().
95 # define GTEST_HAS_GETTIMEOFDAY_ 1
96 # include <sys/time.h> // NOLINT
97 # endif // GTEST_OS_WINDOWS_MINGW
101 // Assume other platforms have gettimeofday().
102 # define GTEST_HAS_GETTIMEOFDAY_ 1
104 // cpplint thinks that the header is already included, so we want to
106 # include <sys/time.h> // NOLINT
107 # include <unistd.h> // NOLINT
109 #endif // GTEST_OS_LINUX
111 #if GTEST_HAS_EXCEPTIONS
112 # include <stdexcept>
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
122 #include "src/gtest-internal-inl.h"
125 # define vsnprintf _vsnprintf
126 #endif // GTEST_OS_WINDOWS
130 #include <crt_externs.h>
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
143 using internal::CountIf
;
144 using internal::ForEach
;
145 using internal::GetElementOr
;
146 using internal::Shuffle
;
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_*";
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/*";
159 // A test filter that matches everything.
160 static const char kUniversalFilter
[] = "*";
162 // The default output format.
163 static const char kDefaultOutputFormat
[] = "xml";
164 // The default output file.
165 static const char kDefaultOutputFile
[] = "test_detail";
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";
176 // The text used in failure messages to indicate the start of the
178 const char kStackTraceMarker
[] = "\nStack trace:\n";
180 // g_help_flag is true if and only if the --help flag or an equivalent form
181 // is specified on the command line.
182 bool g_help_flag
= false;
184 // Utilty function to Open File for Writing
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());
190 if (output_dir
.CreateDirectoriesRecursively()) {
191 fileout
= posix::FOpen(output_file
.c_str(), "w");
193 if (fileout
== nullptr) {
194 GTEST_LOG_(FATAL
) << "Unable to open file \"" << output_file
<< "\"";
199 } // namespace internal
201 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
202 // environment variable.
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
;
209 return kUniversalFilter
;
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.");
218 break_on_failure
, internal::BoolFromGTestEnv("break_on_failure", false),
219 "True if and only if a failed assertion should be a debugger "
222 GTEST_DEFINE_bool_(catch_exceptions
,
223 internal::BoolFromGTestEnv("catch_exceptions", true),
224 "True if and only if " GTEST_NAME_
225 " should catch exceptions and treat them as test failures.");
227 GTEST_DEFINE_string_(
229 internal::StringFromGTestEnv("color", "auto"),
230 "Whether to use colors in the output. Valid values: yes, no, "
231 "and auto. 'auto' means to use colors if the output is "
232 "being sent to a terminal and the TERM environment variable "
233 "is set to a terminal type that supports colors.");
235 GTEST_DEFINE_string_(
237 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
238 "A colon-separated list of glob (not regex) patterns "
239 "for filtering the tests to run, optionally followed by a "
240 "'-' and a : separated list of negative patterns (tests to "
241 "exclude). A test is run if it matches one of the positive "
242 "patterns and does not match any of the negative patterns.");
245 install_failure_signal_handler
,
246 internal::BoolFromGTestEnv("install_failure_signal_handler", false),
247 "If true and supported on the current platform, " GTEST_NAME_
" should "
248 "install a signal handler that dumps debugging information when fatal "
249 "signals are raised.");
251 GTEST_DEFINE_bool_(list_tests
, false,
252 "List all tests without running them.");
254 // The net priority order after flag processing is thus:
255 // --gtest_output command line flag
256 // GTEST_OUTPUT environment variable
257 // XML_OUTPUT_FILE environment variable
259 GTEST_DEFINE_string_(
261 internal::StringFromGTestEnv("output",
262 internal::OutputFlagAlsoCheckEnvVar().c_str()),
263 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
264 "optionally followed by a colon and an output file name or directory. "
265 "A directory is indicated by a trailing pathname separator. "
266 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
267 "If a directory is specified, output files will be created "
268 "within that directory, with file-names based on the test "
269 "executable's name and, if necessary, made unique by adding "
272 GTEST_DEFINE_bool_(print_time
, internal::BoolFromGTestEnv("print_time", true),
273 "True if and only if " GTEST_NAME_
274 " should display elapsed time in text output.");
276 GTEST_DEFINE_bool_(print_utf8
, internal::BoolFromGTestEnv("print_utf8", true),
277 "True if and only if " GTEST_NAME_
278 " prints UTF8 characters as text.");
282 internal::Int32FromGTestEnv("random_seed", 0),
283 "Random number seed to use when shuffling test orders. Must be in range "
284 "[1, 99999], or 0 to use a seed based on the current time.");
288 internal::Int32FromGTestEnv("repeat", 1),
289 "How many times to repeat each test. Specify a negative number "
290 "for repeating forever. Useful for shaking out flaky tests.");
292 GTEST_DEFINE_bool_(show_internal_stack_frames
, false,
293 "True if and only if " GTEST_NAME_
294 " should include internal stack frames when "
295 "printing test failure stack traces.");
297 GTEST_DEFINE_bool_(shuffle
, internal::BoolFromGTestEnv("shuffle", false),
298 "True if and only if " GTEST_NAME_
299 " should randomize tests' order on every run.");
303 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth
),
304 "The maximum number of stack frames to print when an "
305 "assertion fails. The valid range is 0 through 100, inclusive.");
307 GTEST_DEFINE_string_(
309 internal::StringFromGTestEnv("stream_result_to", ""),
310 "This flag specifies the host name and the port number on which to stream "
311 "test results. Example: \"localhost:555\". The flag is effective only on "
316 internal::BoolFromGTestEnv("throw_on_failure", false),
317 "When this flag is specified, a failed assertion will throw an exception "
318 "if exceptions are enabled or exit the program with a non-zero code "
319 "otherwise. For use with an external test framework.");
321 #if GTEST_USE_OWN_FLAGFILE_FLAG_
322 GTEST_DEFINE_string_(
324 internal::StringFromGTestEnv("flagfile", ""),
325 "This flag specifies the flagfile to read command-line flags from.");
326 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
330 // Generates a random number from [0, range), using a Linear
331 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
333 UInt32
Random::Generate(UInt32 range
) {
334 // These constants are the same as are used in glibc's rand(3).
335 // Use wider types than necessary to prevent unsigned overflow diagnostics.
336 state_
= static_cast<UInt32
>(1103515245ULL*state_
+ 12345U) % kMaxRange
;
338 GTEST_CHECK_(range
> 0)
339 << "Cannot generate a number in the range [0, 0).";
340 GTEST_CHECK_(range
<= kMaxRange
)
341 << "Generation of a number in [0, " << range
<< ") was requested, "
342 << "but this can only generate numbers in [0, " << kMaxRange
<< ").";
344 // Converting via modulus introduces a bit of downward bias, but
345 // it's simple, and a linear congruential generator isn't too good
347 return state_
% range
;
350 // GTestIsInitialized() returns true if and only if the user has initialized
351 // Google Test. Useful for catching the user mistake of not initializing
352 // Google Test before calling RUN_ALL_TESTS().
353 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
355 // Iterates over a vector of TestSuites, keeping a running sum of the
356 // results of calling a given int-returning method on each.
358 static int SumOverTestSuiteList(const std::vector
<TestSuite
*>& case_list
,
359 int (TestSuite::*method
)() const) {
361 for (size_t i
= 0; i
< case_list
.size(); i
++) {
362 sum
+= (case_list
[i
]->*method
)();
367 // Returns true if and only if the test suite passed.
368 static bool TestSuitePassed(const TestSuite
* test_suite
) {
369 return test_suite
->should_run() && test_suite
->Passed();
372 // Returns true if and only if the test suite failed.
373 static bool TestSuiteFailed(const TestSuite
* test_suite
) {
374 return test_suite
->should_run() && test_suite
->Failed();
377 // Returns true if and only if test_suite contains at least one test that
379 static bool ShouldRunTestSuite(const TestSuite
* test_suite
) {
380 return test_suite
->should_run();
383 // AssertHelper constructor.
384 AssertHelper::AssertHelper(TestPartResult::Type type
,
388 : data_(new AssertHelperData(type
, file
, line
, message
)) {
391 AssertHelper::~AssertHelper() {
395 // Message assignment, for assertion streaming support.
396 void AssertHelper::operator=(const Message
& message
) const {
397 UnitTest::GetInstance()->
398 AddTestPartResult(data_
->type
, data_
->file
, data_
->line
,
399 AppendUserMessage(data_
->message
, message
),
400 UnitTest::GetInstance()->impl()
401 ->CurrentOsStackTraceExceptTop(1)
402 // Skips the stack frame for this function itself.
406 // A copy of all command line arguments. Set by InitGoogleTest().
407 static ::std::vector
<std::string
> g_argvs
;
409 ::std::vector
<std::string
> GetArgvs() {
410 #if defined(GTEST_CUSTOM_GET_ARGVS_)
411 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
412 // ::string. This code converts it to the appropriate type.
413 const auto& custom
= GTEST_CUSTOM_GET_ARGVS_();
414 return ::std::vector
<std::string
>(custom
.begin(), custom
.end());
415 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
417 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
420 // Returns the current application's name, removing directory path if that
422 FilePath
GetCurrentExecutableName() {
425 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
426 result
.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
428 result
.Set(FilePath(GetArgvs()[0]));
429 #endif // GTEST_OS_WINDOWS
431 return result
.RemoveDirectoryName();
434 // Functions for processing the gtest_output flag.
436 // Returns the output format, or "" for normal printed output.
437 std::string
UnitTestOptions::GetOutputFormat() {
438 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
439 const char* const colon
= strchr(gtest_output_flag
, ':');
440 return (colon
== nullptr)
441 ? std::string(gtest_output_flag
)
442 : std::string(gtest_output_flag
,
443 static_cast<size_t>(colon
- gtest_output_flag
));
446 // Returns the name of the requested output file, or the default if none
447 // was explicitly specified.
448 std::string
UnitTestOptions::GetAbsolutePathToOutputFile() {
449 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
451 std::string format
= GetOutputFormat();
453 format
= std::string(kDefaultOutputFormat
);
455 const char* const colon
= strchr(gtest_output_flag
, ':');
456 if (colon
== nullptr)
457 return internal::FilePath::MakeFileName(
459 UnitTest::GetInstance()->original_working_dir()),
460 internal::FilePath(kDefaultOutputFile
), 0,
461 format
.c_str()).string();
463 internal::FilePath
output_name(colon
+ 1);
464 if (!output_name
.IsAbsolutePath())
465 output_name
= internal::FilePath::ConcatPaths(
466 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
467 internal::FilePath(colon
+ 1));
469 if (!output_name
.IsDirectory())
470 return output_name
.string();
472 internal::FilePath
result(internal::FilePath::GenerateUniqueFileName(
473 output_name
, internal::GetCurrentExecutableName(),
474 GetOutputFormat().c_str()));
475 return result
.string();
478 // Returns true if and only if the wildcard pattern matches the string.
479 // The first ':' or '\0' character in pattern marks the end of it.
481 // This recursive algorithm isn't very efficient, but is clear and
482 // works well enough for matching test names, which are short.
483 bool UnitTestOptions::PatternMatchesString(const char *pattern
,
487 case ':': // Either ':' or '\0' marks the end of the pattern.
489 case '?': // Matches any single character.
490 return *str
!= '\0' && PatternMatchesString(pattern
+ 1, str
+ 1);
491 case '*': // Matches any string (possibly empty) of characters.
492 return (*str
!= '\0' && PatternMatchesString(pattern
, str
+ 1)) ||
493 PatternMatchesString(pattern
+ 1, str
);
494 default: // Non-special character. Matches itself.
495 return *pattern
== *str
&&
496 PatternMatchesString(pattern
+ 1, str
+ 1);
500 bool UnitTestOptions::MatchesFilter(
501 const std::string
& name
, const char* filter
) {
502 const char *cur_pattern
= filter
;
504 if (PatternMatchesString(cur_pattern
, name
.c_str())) {
508 // Finds the next pattern in the filter.
509 cur_pattern
= strchr(cur_pattern
, ':');
511 // Returns if no more pattern can be found.
512 if (cur_pattern
== nullptr) {
516 // Skips the pattern separater (the ':' character).
521 // Returns true if and only if the user-specified filter matches the test
522 // suite name and the test name.
523 bool UnitTestOptions::FilterMatchesTest(const std::string
& test_suite_name
,
524 const std::string
& test_name
) {
525 const std::string
& full_name
= test_suite_name
+ "." + test_name
.c_str();
527 // Split --gtest_filter at '-', if there is one, to separate into
528 // positive filter and negative filter portions
529 const char* const p
= GTEST_FLAG(filter
).c_str();
530 const char* const dash
= strchr(p
, '-');
531 std::string positive
;
532 std::string negative
;
533 if (dash
== nullptr) {
534 positive
= GTEST_FLAG(filter
).c_str(); // Whole string is a positive filter
537 positive
= std::string(p
, dash
); // Everything up to the dash
538 negative
= std::string(dash
+ 1); // Everything after the dash
539 if (positive
.empty()) {
540 // Treat '-test1' as the same as '*-test1'
541 positive
= kUniversalFilter
;
545 // A filter is a colon-separated list of patterns. It matches a
546 // test if any pattern in it matches the test.
547 return (MatchesFilter(full_name
, positive
.c_str()) &&
548 !MatchesFilter(full_name
, negative
.c_str()));
552 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
553 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
554 // This function is useful as an __except condition.
555 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code
) {
556 // Google Test should handle a SEH exception if:
557 // 1. the user wants it to, AND
558 // 2. this is not a breakpoint exception, AND
559 // 3. this is not a C++ exception (VC++ implements them via SEH,
562 // SEH exception code for C++ exceptions.
563 // (see http://support.microsoft.com/kb/185294 for more information).
564 const DWORD kCxxExceptionCode
= 0xe06d7363;
566 bool should_handle
= true;
568 if (!GTEST_FLAG(catch_exceptions
))
569 should_handle
= false;
570 else if (exception_code
== EXCEPTION_BREAKPOINT
)
571 should_handle
= false;
572 else if (exception_code
== kCxxExceptionCode
)
573 should_handle
= false;
575 return should_handle
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
;
577 #endif // GTEST_HAS_SEH
579 } // namespace internal
581 // The c'tor sets this object as the test part result reporter used by
582 // Google Test. The 'result' parameter specifies where to report the
583 // results. Intercepts only failures from the current thread.
584 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
585 TestPartResultArray
* result
)
586 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD
),
591 // The c'tor sets this object as the test part result reporter used by
592 // Google Test. The 'result' parameter specifies where to report the
594 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
595 InterceptMode intercept_mode
, TestPartResultArray
* result
)
596 : intercept_mode_(intercept_mode
),
601 void ScopedFakeTestPartResultReporter::Init() {
602 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
603 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
604 old_reporter_
= impl
->GetGlobalTestPartResultReporter();
605 impl
->SetGlobalTestPartResultReporter(this);
607 old_reporter_
= impl
->GetTestPartResultReporterForCurrentThread();
608 impl
->SetTestPartResultReporterForCurrentThread(this);
612 // The d'tor restores the test part result reporter used by Google Test
614 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
615 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
616 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
617 impl
->SetGlobalTestPartResultReporter(old_reporter_
);
619 impl
->SetTestPartResultReporterForCurrentThread(old_reporter_
);
623 // Increments the test part result count and remembers the result.
624 // This method is from the TestPartResultReporterInterface interface.
625 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
626 const TestPartResult
& result
) {
627 result_
->Append(result
);
632 // Returns the type ID of ::testing::Test. We should always call this
633 // instead of GetTypeId< ::testing::Test>() to get the type ID of
634 // testing::Test. This is to work around a suspected linker bug when
635 // using Google Test as a framework on Mac OS X. The bug causes
636 // GetTypeId< ::testing::Test>() to return different values depending
637 // on whether the call is from the Google Test framework itself or
638 // from user test code. GetTestTypeId() is guaranteed to always
639 // return the same value, as it always calls GetTypeId<>() from the
640 // gtest.cc, which is within the Google Test framework.
641 TypeId
GetTestTypeId() {
642 return GetTypeId
<Test
>();
645 // The value of GetTestTypeId() as seen from within the Google Test
646 // library. This is solely for testing GetTestTypeId().
647 extern const TypeId kTestTypeIdInGoogleTest
= GetTestTypeId();
649 // This predicate-formatter checks that 'results' contains a test part
650 // failure of the given type and that the failure message contains the
652 static AssertionResult
HasOneFailure(const char* /* results_expr */,
653 const char* /* type_expr */,
654 const char* /* substr_expr */,
655 const TestPartResultArray
& results
,
656 TestPartResult::Type type
,
657 const std::string
& substr
) {
658 const std::string
expected(type
== TestPartResult::kFatalFailure
?
660 "1 non-fatal failure");
662 if (results
.size() != 1) {
663 msg
<< "Expected: " << expected
<< "\n"
664 << " Actual: " << results
.size() << " failures";
665 for (int i
= 0; i
< results
.size(); i
++) {
666 msg
<< "\n" << results
.GetTestPartResult(i
);
668 return AssertionFailure() << msg
;
671 const TestPartResult
& r
= results
.GetTestPartResult(0);
672 if (r
.type() != type
) {
673 return AssertionFailure() << "Expected: " << expected
<< "\n"
678 if (strstr(r
.message(), substr
.c_str()) == nullptr) {
679 return AssertionFailure() << "Expected: " << expected
<< " containing \""
685 return AssertionSuccess();
688 // The constructor of SingleFailureChecker remembers where to look up
689 // test part results, what type of failure we expect, and what
690 // substring the failure message should contain.
691 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray
* results
,
692 TestPartResult::Type type
,
693 const std::string
& substr
)
694 : results_(results
), type_(type
), substr_(substr
) {}
696 // The destructor of SingleFailureChecker verifies that the given
697 // TestPartResultArray contains exactly one failure that has the given
698 // type and contains the given substring. If that's not the case, a
699 // non-fatal failure will be generated.
700 SingleFailureChecker::~SingleFailureChecker() {
701 EXPECT_PRED_FORMAT3(HasOneFailure
, *results_
, type_
, substr_
);
704 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
705 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
707 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
708 const TestPartResult
& result
) {
709 unit_test_
->current_test_result()->AddTestPartResult(result
);
710 unit_test_
->listeners()->repeater()->OnTestPartResult(result
);
713 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
714 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
716 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
717 const TestPartResult
& result
) {
718 unit_test_
->GetGlobalTestPartResultReporter()->ReportTestPartResult(result
);
721 // Returns the global test part result reporter.
722 TestPartResultReporterInterface
*
723 UnitTestImpl::GetGlobalTestPartResultReporter() {
724 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
725 return global_test_part_result_repoter_
;
728 // Sets the global test part result reporter.
729 void UnitTestImpl::SetGlobalTestPartResultReporter(
730 TestPartResultReporterInterface
* reporter
) {
731 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
732 global_test_part_result_repoter_
= reporter
;
735 // Returns the test part result reporter for the current thread.
736 TestPartResultReporterInterface
*
737 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
738 return per_thread_test_part_result_reporter_
.get();
741 // Sets the test part result reporter for the current thread.
742 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
743 TestPartResultReporterInterface
* reporter
) {
744 per_thread_test_part_result_reporter_
.set(reporter
);
747 // Gets the number of successful test suites.
748 int UnitTestImpl::successful_test_suite_count() const {
749 return CountIf(test_suites_
, TestSuitePassed
);
752 // Gets the number of failed test suites.
753 int UnitTestImpl::failed_test_suite_count() const {
754 return CountIf(test_suites_
, TestSuiteFailed
);
757 // Gets the number of all test suites.
758 int UnitTestImpl::total_test_suite_count() const {
759 return static_cast<int>(test_suites_
.size());
762 // Gets the number of all test suites that contain at least one test
764 int UnitTestImpl::test_suite_to_run_count() const {
765 return CountIf(test_suites_
, ShouldRunTestSuite
);
768 // Gets the number of successful tests.
769 int UnitTestImpl::successful_test_count() const {
770 return SumOverTestSuiteList(test_suites_
, &TestSuite::successful_test_count
);
773 // Gets the number of skipped tests.
774 int UnitTestImpl::skipped_test_count() const {
775 return SumOverTestSuiteList(test_suites_
, &TestSuite::skipped_test_count
);
778 // Gets the number of failed tests.
779 int UnitTestImpl::failed_test_count() const {
780 return SumOverTestSuiteList(test_suites_
, &TestSuite::failed_test_count
);
783 // Gets the number of disabled tests that will be reported in the XML report.
784 int UnitTestImpl::reportable_disabled_test_count() const {
785 return SumOverTestSuiteList(test_suites_
,
786 &TestSuite::reportable_disabled_test_count
);
789 // Gets the number of disabled tests.
790 int UnitTestImpl::disabled_test_count() const {
791 return SumOverTestSuiteList(test_suites_
, &TestSuite::disabled_test_count
);
794 // Gets the number of tests to be printed in the XML report.
795 int UnitTestImpl::reportable_test_count() const {
796 return SumOverTestSuiteList(test_suites_
, &TestSuite::reportable_test_count
);
799 // Gets the number of all tests.
800 int UnitTestImpl::total_test_count() const {
801 return SumOverTestSuiteList(test_suites_
, &TestSuite::total_test_count
);
804 // Gets the number of tests that should run.
805 int UnitTestImpl::test_to_run_count() const {
806 return SumOverTestSuiteList(test_suites_
, &TestSuite::test_to_run_count
);
809 // Returns the current OS stack trace as an std::string.
811 // The maximum number of stack frames to be included is specified by
812 // the gtest_stack_trace_depth flag. The skip_count parameter
813 // specifies the number of top frames to be skipped, which doesn't
814 // count against the number of frames to be included.
816 // For example, if Foo() calls Bar(), which in turn calls
817 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
818 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
819 std::string
UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count
) {
820 return os_stack_trace_getter()->CurrentStackTrace(
821 static_cast<int>(GTEST_FLAG(stack_trace_depth
)),
823 // Skips the user-specified number of frames plus this function
828 // Returns the current time in milliseconds.
829 TimeInMillis
GetTimeInMillis() {
830 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
831 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
832 // http://analogous.blogspot.com/2005/04/epoch.html
833 const TimeInMillis kJavaEpochToWinFileTimeDelta
=
834 static_cast<TimeInMillis
>(116444736UL) * 100000UL;
835 const DWORD kTenthMicrosInMilliSecond
= 10000;
837 SYSTEMTIME now_systime
;
838 FILETIME now_filetime
;
839 ULARGE_INTEGER now_int64
;
840 GetSystemTime(&now_systime
);
841 if (SystemTimeToFileTime(&now_systime
, &now_filetime
)) {
842 now_int64
.LowPart
= now_filetime
.dwLowDateTime
;
843 now_int64
.HighPart
= now_filetime
.dwHighDateTime
;
844 now_int64
.QuadPart
= (now_int64
.QuadPart
/ kTenthMicrosInMilliSecond
) -
845 kJavaEpochToWinFileTimeDelta
;
846 return now_int64
.QuadPart
;
849 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
852 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
853 // (deprecated function) there.
854 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
856 GTEST_DISABLE_MSC_DEPRECATED_POP_()
858 return static_cast<TimeInMillis
>(now
.time
) * 1000 + now
.millitm
;
859 #elif GTEST_HAS_GETTIMEOFDAY_
861 gettimeofday(&now
, nullptr);
862 return static_cast<TimeInMillis
>(now
.tv_sec
) * 1000 + now
.tv_usec
/ 1000;
864 # error "Don't know how to get the current time on your system."
872 #if GTEST_OS_WINDOWS_MOBILE
873 // Creates a UTF-16 wide string from the given ANSI string, allocating
874 // memory using new. The caller is responsible for deleting the return
875 // value using delete[]. Returns the wide string, or NULL if the
877 LPCWSTR
String::AnsiToUtf16(const char* ansi
) {
878 if (!ansi
) return nullptr;
879 const int length
= strlen(ansi
);
880 const int unicode_length
=
881 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
, nullptr, 0);
882 WCHAR
* unicode
= new WCHAR
[unicode_length
+ 1];
883 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
,
884 unicode
, unicode_length
);
885 unicode
[unicode_length
] = 0;
889 // Creates an ANSI string from the given wide string, allocating
890 // memory using new. The caller is responsible for deleting the return
891 // value using delete[]. Returns the ANSI string, or NULL if the
893 const char* String::Utf16ToAnsi(LPCWSTR utf16_str
) {
894 if (!utf16_str
) return nullptr;
895 const int ansi_length
= WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, nullptr,
896 0, nullptr, nullptr);
897 char* ansi
= new char[ansi_length
+ 1];
898 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, ansi
, ansi_length
, nullptr,
900 ansi
[ansi_length
] = 0;
904 #endif // GTEST_OS_WINDOWS_MOBILE
906 // Compares two C strings. Returns true if and only if they have the same
909 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
910 // C string is considered different to any non-NULL C string,
911 // including the empty string.
912 bool String::CStringEquals(const char * lhs
, const char * rhs
) {
913 if (lhs
== nullptr) return rhs
== nullptr;
915 if (rhs
== nullptr) return false;
917 return strcmp(lhs
, rhs
) == 0;
920 #if GTEST_HAS_STD_WSTRING
922 // Converts an array of wide chars to a narrow string using the UTF-8
923 // encoding, and streams the result to the given Message object.
924 static void StreamWideCharsToMessage(const wchar_t* wstr
, size_t length
,
926 for (size_t i
= 0; i
!= length
; ) { // NOLINT
927 if (wstr
[i
] != L
'\0') {
928 *msg
<< WideStringToUtf8(wstr
+ i
, static_cast<int>(length
- i
));
929 while (i
!= length
&& wstr
[i
] != L
'\0')
938 #endif // GTEST_HAS_STD_WSTRING
940 void SplitString(const ::std::string
& str
, char delimiter
,
941 ::std::vector
< ::std::string
>* dest
) {
942 ::std::vector
< ::std::string
> parsed
;
943 ::std::string::size_type pos
= 0;
944 while (::testing::internal::AlwaysTrue()) {
945 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
946 if (colon
== ::std::string::npos
) {
947 parsed
.push_back(str
.substr(pos
));
950 parsed
.push_back(str
.substr(pos
, colon
- pos
));
957 } // namespace internal
959 // Constructs an empty Message.
960 // We allocate the stringstream separately because otherwise each use of
961 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
962 // stack frame leading to huge stack frames in some cases; gcc does not reuse
964 Message::Message() : ss_(new ::std::stringstream
) {
965 // By default, we want there to be enough precision when printing
966 // a double to a Message.
967 *ss_
<< std::setprecision(std::numeric_limits
<double>::digits10
+ 2);
970 // These two overloads allow streaming a wide C string to a Message
971 // using the UTF-8 encoding.
972 Message
& Message::operator <<(const wchar_t* wide_c_str
) {
973 return *this << internal::String::ShowWideCString(wide_c_str
);
975 Message
& Message::operator <<(wchar_t* wide_c_str
) {
976 return *this << internal::String::ShowWideCString(wide_c_str
);
979 #if GTEST_HAS_STD_WSTRING
980 // Converts the given wide string to a narrow string using the UTF-8
981 // encoding, and streams the result to this Message object.
982 Message
& Message::operator <<(const ::std::wstring
& wstr
) {
983 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
986 #endif // GTEST_HAS_STD_WSTRING
988 // Gets the text streamed to this object so far as an std::string.
989 // Each '\0' character in the buffer is replaced with "\\0".
990 std::string
Message::GetString() const {
991 return internal::StringStreamToString(ss_
.get());
994 // AssertionResult constructors.
995 // Used in EXPECT_TRUE/FALSE(assertion_result).
996 AssertionResult::AssertionResult(const AssertionResult
& other
)
997 : success_(other
.success_
),
998 message_(other
.message_
.get() != nullptr
999 ? new ::std::string(*other
.message_
)
1000 : static_cast< ::std::string
*>(nullptr)) {}
1002 // Swaps two AssertionResults.
1003 void AssertionResult::swap(AssertionResult
& other
) {
1005 swap(success_
, other
.success_
);
1006 swap(message_
, other
.message_
);
1009 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1010 AssertionResult
AssertionResult::operator!() const {
1011 AssertionResult
negation(!success_
);
1012 if (message_
.get() != nullptr) negation
<< *message_
;
1016 // Makes a successful assertion result.
1017 AssertionResult
AssertionSuccess() {
1018 return AssertionResult(true);
1021 // Makes a failed assertion result.
1022 AssertionResult
AssertionFailure() {
1023 return AssertionResult(false);
1026 // Makes a failed assertion result with the given failure message.
1027 // Deprecated; use AssertionFailure() << message.
1028 AssertionResult
AssertionFailure(const Message
& message
) {
1029 return AssertionFailure() << message
;
1032 namespace internal
{
1034 namespace edit_distance
{
1035 std::vector
<EditType
> CalculateOptimalEdits(const std::vector
<size_t>& left
,
1036 const std::vector
<size_t>& right
) {
1037 std::vector
<std::vector
<double> > costs(
1038 left
.size() + 1, std::vector
<double>(right
.size() + 1));
1039 std::vector
<std::vector
<EditType
> > best_move(
1040 left
.size() + 1, std::vector
<EditType
>(right
.size() + 1));
1042 // Populate for empty right.
1043 for (size_t l_i
= 0; l_i
< costs
.size(); ++l_i
) {
1044 costs
[l_i
][0] = static_cast<double>(l_i
);
1045 best_move
[l_i
][0] = kRemove
;
1047 // Populate for empty left.
1048 for (size_t r_i
= 1; r_i
< costs
[0].size(); ++r_i
) {
1049 costs
[0][r_i
] = static_cast<double>(r_i
);
1050 best_move
[0][r_i
] = kAdd
;
1053 for (size_t l_i
= 0; l_i
< left
.size(); ++l_i
) {
1054 for (size_t r_i
= 0; r_i
< right
.size(); ++r_i
) {
1055 if (left
[l_i
] == right
[r_i
]) {
1056 // Found a match. Consume it.
1057 costs
[l_i
+ 1][r_i
+ 1] = costs
[l_i
][r_i
];
1058 best_move
[l_i
+ 1][r_i
+ 1] = kMatch
;
1062 const double add
= costs
[l_i
+ 1][r_i
];
1063 const double remove
= costs
[l_i
][r_i
+ 1];
1064 const double replace
= costs
[l_i
][r_i
];
1065 if (add
< remove
&& add
< replace
) {
1066 costs
[l_i
+ 1][r_i
+ 1] = add
+ 1;
1067 best_move
[l_i
+ 1][r_i
+ 1] = kAdd
;
1068 } else if (remove
< add
&& remove
< replace
) {
1069 costs
[l_i
+ 1][r_i
+ 1] = remove
+ 1;
1070 best_move
[l_i
+ 1][r_i
+ 1] = kRemove
;
1072 // We make replace a little more expensive than add/remove to lower
1074 costs
[l_i
+ 1][r_i
+ 1] = replace
+ 1.00001;
1075 best_move
[l_i
+ 1][r_i
+ 1] = kReplace
;
1080 // Reconstruct the best path. We do it in reverse order.
1081 std::vector
<EditType
> best_path
;
1082 for (size_t l_i
= left
.size(), r_i
= right
.size(); l_i
> 0 || r_i
> 0;) {
1083 EditType move
= best_move
[l_i
][r_i
];
1084 best_path
.push_back(move
);
1085 l_i
-= move
!= kAdd
;
1086 r_i
-= move
!= kRemove
;
1088 std::reverse(best_path
.begin(), best_path
.end());
1094 // Helper class to convert string into ids with deduplication.
1095 class InternalStrings
{
1097 size_t GetId(const std::string
& str
) {
1098 IdMap::iterator it
= ids_
.find(str
);
1099 if (it
!= ids_
.end()) return it
->second
;
1100 size_t id
= ids_
.size();
1101 return ids_
[str
] = id
;
1105 typedef std::map
<std::string
, size_t> IdMap
;
1111 std::vector
<EditType
> CalculateOptimalEdits(
1112 const std::vector
<std::string
>& left
,
1113 const std::vector
<std::string
>& right
) {
1114 std::vector
<size_t> left_ids
, right_ids
;
1116 InternalStrings intern_table
;
1117 for (size_t i
= 0; i
< left
.size(); ++i
) {
1118 left_ids
.push_back(intern_table
.GetId(left
[i
]));
1120 for (size_t i
= 0; i
< right
.size(); ++i
) {
1121 right_ids
.push_back(intern_table
.GetId(right
[i
]));
1124 return CalculateOptimalEdits(left_ids
, right_ids
);
1129 // Helper class that holds the state for one hunk and prints it out to the
1131 // It reorders adds/removes when possible to group all removes before all
1132 // adds. It also adds the hunk header before printint into the stream.
1135 Hunk(size_t left_start
, size_t right_start
)
1136 : left_start_(left_start
),
1137 right_start_(right_start
),
1142 void PushLine(char edit
, const char* line
) {
1147 hunk_
.push_back(std::make_pair(' ', line
));
1151 hunk_removes_
.push_back(std::make_pair('-', line
));
1155 hunk_adds_
.push_back(std::make_pair('+', line
));
1160 void PrintTo(std::ostream
* os
) {
1163 for (std::list
<std::pair
<char, const char*> >::const_iterator it
=
1165 it
!= hunk_
.end(); ++it
) {
1166 *os
<< it
->first
<< it
->second
<< "\n";
1170 bool has_edits() const { return adds_
|| removes_
; }
1174 hunk_
.splice(hunk_
.end(), hunk_removes_
);
1175 hunk_
.splice(hunk_
.end(), hunk_adds_
);
1178 // Print a unified diff header for one hunk.
1180 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1181 // where the left/right parts are omitted if unnecessary.
1182 void PrintHeader(std::ostream
* ss
) const {
1185 *ss
<< "-" << left_start_
<< "," << (removes_
+ common_
);
1187 if (removes_
&& adds_
) {
1191 *ss
<< "+" << right_start_
<< "," << (adds_
+ common_
);
1196 size_t left_start_
, right_start_
;
1197 size_t adds_
, removes_
, common_
;
1198 std::list
<std::pair
<char, const char*> > hunk_
, hunk_adds_
, hunk_removes_
;
1203 // Create a list of diff hunks in Unified diff format.
1204 // Each hunk has a header generated by PrintHeader above plus a body with
1205 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
1207 // 'context' represents the desired unchanged prefix/suffix around the diff.
1208 // If two hunks are close enough that their contexts overlap, then they are
1209 // joined into one hunk.
1210 std::string
CreateUnifiedDiff(const std::vector
<std::string
>& left
,
1211 const std::vector
<std::string
>& right
,
1213 const std::vector
<EditType
> edits
= CalculateOptimalEdits(left
, right
);
1215 size_t l_i
= 0, r_i
= 0, edit_i
= 0;
1216 std::stringstream ss
;
1217 while (edit_i
< edits
.size()) {
1219 while (edit_i
< edits
.size() && edits
[edit_i
] == kMatch
) {
1225 // Find the first line to include in the hunk.
1226 const size_t prefix_context
= std::min(l_i
, context
);
1227 Hunk
hunk(l_i
- prefix_context
+ 1, r_i
- prefix_context
+ 1);
1228 for (size_t i
= prefix_context
; i
> 0; --i
) {
1229 hunk
.PushLine(' ', left
[l_i
- i
].c_str());
1232 // Iterate the edits until we found enough suffix for the hunk or the input
1234 size_t n_suffix
= 0;
1235 for (; edit_i
< edits
.size(); ++edit_i
) {
1236 if (n_suffix
>= context
) {
1237 // Continue only if the next hunk is very close.
1238 auto it
= edits
.begin() + static_cast<int>(edit_i
);
1239 while (it
!= edits
.end() && *it
== kMatch
) ++it
;
1240 if (it
== edits
.end() ||
1241 static_cast<size_t>(it
- edits
.begin()) - edit_i
>= context
) {
1242 // There is no next edit or it is too far away.
1247 EditType edit
= edits
[edit_i
];
1248 // Reset count when a non match is found.
1249 n_suffix
= edit
== kMatch
? n_suffix
+ 1 : 0;
1251 if (edit
== kMatch
|| edit
== kRemove
|| edit
== kReplace
) {
1252 hunk
.PushLine(edit
== kMatch
? ' ' : '-', left
[l_i
].c_str());
1254 if (edit
== kAdd
|| edit
== kReplace
) {
1255 hunk
.PushLine('+', right
[r_i
].c_str());
1258 // Advance indices, depending on edit type.
1259 l_i
+= edit
!= kAdd
;
1260 r_i
+= edit
!= kRemove
;
1263 if (!hunk
.has_edits()) {
1264 // We are done. We don't want this hunk.
1273 } // namespace edit_distance
1277 // The string representation of the values received in EqFailure() are already
1278 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1279 // characters the same.
1280 std::vector
<std::string
> SplitEscapedString(const std::string
& str
) {
1281 std::vector
<std::string
> lines
;
1282 size_t start
= 0, end
= str
.size();
1283 if (end
> 2 && str
[0] == '"' && str
[end
- 1] == '"') {
1287 bool escaped
= false;
1288 for (size_t i
= start
; i
+ 1 < end
; ++i
) {
1291 if (str
[i
] == 'n') {
1292 lines
.push_back(str
.substr(start
, i
- start
- 1));
1296 escaped
= str
[i
] == '\\';
1299 lines
.push_back(str
.substr(start
, end
- start
));
1305 // Constructs and returns the message for an equality assertion
1306 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1308 // The first four parameters are the expressions used in the assertion
1309 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1310 // where foo is 5 and bar is 6, we have:
1312 // lhs_expression: "foo"
1313 // rhs_expression: "bar"
1317 // The ignoring_case parameter is true if and only if the assertion is a
1318 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
1319 // be inserted into the message.
1320 AssertionResult
EqFailure(const char* lhs_expression
,
1321 const char* rhs_expression
,
1322 const std::string
& lhs_value
,
1323 const std::string
& rhs_value
,
1324 bool ignoring_case
) {
1326 msg
<< "Expected equality of these values:";
1327 msg
<< "\n " << lhs_expression
;
1328 if (lhs_value
!= lhs_expression
) {
1329 msg
<< "\n Which is: " << lhs_value
;
1331 msg
<< "\n " << rhs_expression
;
1332 if (rhs_value
!= rhs_expression
) {
1333 msg
<< "\n Which is: " << rhs_value
;
1336 if (ignoring_case
) {
1337 msg
<< "\nIgnoring case";
1340 if (!lhs_value
.empty() && !rhs_value
.empty()) {
1341 const std::vector
<std::string
> lhs_lines
=
1342 SplitEscapedString(lhs_value
);
1343 const std::vector
<std::string
> rhs_lines
=
1344 SplitEscapedString(rhs_value
);
1345 if (lhs_lines
.size() > 1 || rhs_lines
.size() > 1) {
1346 msg
<< "\nWith diff:\n"
1347 << edit_distance::CreateUnifiedDiff(lhs_lines
, rhs_lines
);
1351 return AssertionFailure() << msg
;
1354 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1355 std::string
GetBoolAssertionFailureMessage(
1356 const AssertionResult
& assertion_result
,
1357 const char* expression_text
,
1358 const char* actual_predicate_value
,
1359 const char* expected_predicate_value
) {
1360 const char* actual_message
= assertion_result
.message();
1362 msg
<< "Value of: " << expression_text
1363 << "\n Actual: " << actual_predicate_value
;
1364 if (actual_message
[0] != '\0')
1365 msg
<< " (" << actual_message
<< ")";
1366 msg
<< "\nExpected: " << expected_predicate_value
;
1367 return msg
.GetString();
1370 // Helper function for implementing ASSERT_NEAR.
1371 AssertionResult
DoubleNearPredFormat(const char* expr1
,
1373 const char* abs_error_expr
,
1377 const double diff
= fabs(val1
- val2
);
1378 if (diff
<= abs_error
) return AssertionSuccess();
1380 return AssertionFailure()
1381 << "The difference between " << expr1
<< " and " << expr2
1382 << " is " << diff
<< ", which exceeds " << abs_error_expr
<< ", where\n"
1383 << expr1
<< " evaluates to " << val1
<< ",\n"
1384 << expr2
<< " evaluates to " << val2
<< ", and\n"
1385 << abs_error_expr
<< " evaluates to " << abs_error
<< ".";
1389 // Helper template for implementing FloatLE() and DoubleLE().
1390 template <typename RawType
>
1391 AssertionResult
FloatingPointLE(const char* expr1
,
1395 // Returns success if val1 is less than val2,
1397 return AssertionSuccess();
1400 // or if val1 is almost equal to val2.
1401 const FloatingPoint
<RawType
> lhs(val1
), rhs(val2
);
1402 if (lhs
.AlmostEquals(rhs
)) {
1403 return AssertionSuccess();
1406 // Note that the above two checks will both fail if either val1 or
1407 // val2 is NaN, as the IEEE floating-point standard requires that
1408 // any predicate involving a NaN must return false.
1410 ::std::stringstream val1_ss
;
1411 val1_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
1414 ::std::stringstream val2_ss
;
1415 val2_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
1418 return AssertionFailure()
1419 << "Expected: (" << expr1
<< ") <= (" << expr2
<< ")\n"
1420 << " Actual: " << StringStreamToString(&val1_ss
) << " vs "
1421 << StringStreamToString(&val2_ss
);
1424 } // namespace internal
1426 // Asserts that val1 is less than, or almost equal to, val2. Fails
1427 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1428 AssertionResult
FloatLE(const char* expr1
, const char* expr2
,
1429 float val1
, float val2
) {
1430 return internal::FloatingPointLE
<float>(expr1
, expr2
, val1
, val2
);
1433 // Asserts that val1 is less than, or almost equal to, val2. Fails
1434 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1435 AssertionResult
DoubleLE(const char* expr1
, const char* expr2
,
1436 double val1
, double val2
) {
1437 return internal::FloatingPointLE
<double>(expr1
, expr2
, val1
, val2
);
1440 namespace internal
{
1442 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
1444 AssertionResult
CmpHelperEQ(const char* lhs_expression
,
1445 const char* rhs_expression
,
1449 return AssertionSuccess();
1452 return EqFailure(lhs_expression
,
1454 FormatForComparisonFailureMessage(lhs
, rhs
),
1455 FormatForComparisonFailureMessage(rhs
, lhs
),
1459 // A macro for implementing the helper functions needed to implement
1460 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1461 // just to avoid copy-and-paste of similar code.
1462 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1463 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1464 BiggestInt val1, BiggestInt val2) {\
1465 if (val1 op val2) {\
1466 return AssertionSuccess();\
1468 return AssertionFailure() \
1469 << "Expected: (" << expr1 << ") " #op " (" << expr2\
1470 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1471 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1475 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
1477 GTEST_IMPL_CMP_HELPER_(NE
, !=)
1478 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
1480 GTEST_IMPL_CMP_HELPER_(LE
, <=)
1481 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
1483 GTEST_IMPL_CMP_HELPER_(LT
, < )
1484 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
1486 GTEST_IMPL_CMP_HELPER_(GE
, >=)
1487 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
1489 GTEST_IMPL_CMP_HELPER_(GT
, > )
1491 #undef GTEST_IMPL_CMP_HELPER_
1493 // The helper function for {ASSERT|EXPECT}_STREQ.
1494 AssertionResult
CmpHelperSTREQ(const char* lhs_expression
,
1495 const char* rhs_expression
,
1498 if (String::CStringEquals(lhs
, rhs
)) {
1499 return AssertionSuccess();
1502 return EqFailure(lhs_expression
,
1509 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1510 AssertionResult
CmpHelperSTRCASEEQ(const char* lhs_expression
,
1511 const char* rhs_expression
,
1514 if (String::CaseInsensitiveCStringEquals(lhs
, rhs
)) {
1515 return AssertionSuccess();
1518 return EqFailure(lhs_expression
,
1525 // The helper function for {ASSERT|EXPECT}_STRNE.
1526 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
1527 const char* s2_expression
,
1530 if (!String::CStringEquals(s1
, s2
)) {
1531 return AssertionSuccess();
1533 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
1534 << s2_expression
<< "), actual: \""
1535 << s1
<< "\" vs \"" << s2
<< "\"";
1539 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1540 AssertionResult
CmpHelperSTRCASENE(const char* s1_expression
,
1541 const char* s2_expression
,
1544 if (!String::CaseInsensitiveCStringEquals(s1
, s2
)) {
1545 return AssertionSuccess();
1547 return AssertionFailure()
1548 << "Expected: (" << s1_expression
<< ") != ("
1549 << s2_expression
<< ") (ignoring case), actual: \""
1550 << s1
<< "\" vs \"" << s2
<< "\"";
1554 } // namespace internal
1558 // Helper functions for implementing IsSubString() and IsNotSubstring().
1560 // This group of overloaded functions return true if and only if needle
1561 // is a substring of haystack. NULL is considered a substring of
1564 bool IsSubstringPred(const char* needle
, const char* haystack
) {
1565 if (needle
== nullptr || haystack
== nullptr) return needle
== haystack
;
1567 return strstr(haystack
, needle
) != nullptr;
1570 bool IsSubstringPred(const wchar_t* needle
, const wchar_t* haystack
) {
1571 if (needle
== nullptr || haystack
== nullptr) return needle
== haystack
;
1573 return wcsstr(haystack
, needle
) != nullptr;
1576 // StringType here can be either ::std::string or ::std::wstring.
1577 template <typename StringType
>
1578 bool IsSubstringPred(const StringType
& needle
,
1579 const StringType
& haystack
) {
1580 return haystack
.find(needle
) != StringType::npos
;
1583 // This function implements either IsSubstring() or IsNotSubstring(),
1584 // depending on the value of the expected_to_be_substring parameter.
1585 // StringType here can be const char*, const wchar_t*, ::std::string,
1586 // or ::std::wstring.
1587 template <typename StringType
>
1588 AssertionResult
IsSubstringImpl(
1589 bool expected_to_be_substring
,
1590 const char* needle_expr
, const char* haystack_expr
,
1591 const StringType
& needle
, const StringType
& haystack
) {
1592 if (IsSubstringPred(needle
, haystack
) == expected_to_be_substring
)
1593 return AssertionSuccess();
1595 const bool is_wide_string
= sizeof(needle
[0]) > 1;
1596 const char* const begin_string_quote
= is_wide_string
? "L\"" : "\"";
1597 return AssertionFailure()
1598 << "Value of: " << needle_expr
<< "\n"
1599 << " Actual: " << begin_string_quote
<< needle
<< "\"\n"
1600 << "Expected: " << (expected_to_be_substring
? "" : "not ")
1601 << "a substring of " << haystack_expr
<< "\n"
1602 << "Which is: " << begin_string_quote
<< haystack
<< "\"";
1607 // IsSubstring() and IsNotSubstring() check whether needle is a
1608 // substring of haystack (NULL is considered a substring of itself
1609 // only), and return an appropriate error message when they fail.
1611 AssertionResult
IsSubstring(
1612 const char* needle_expr
, const char* haystack_expr
,
1613 const char* needle
, const char* haystack
) {
1614 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1617 AssertionResult
IsSubstring(
1618 const char* needle_expr
, const char* haystack_expr
,
1619 const wchar_t* needle
, const wchar_t* haystack
) {
1620 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1623 AssertionResult
IsNotSubstring(
1624 const char* needle_expr
, const char* haystack_expr
,
1625 const char* needle
, const char* haystack
) {
1626 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1629 AssertionResult
IsNotSubstring(
1630 const char* needle_expr
, const char* haystack_expr
,
1631 const wchar_t* needle
, const wchar_t* haystack
) {
1632 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1635 AssertionResult
IsSubstring(
1636 const char* needle_expr
, const char* haystack_expr
,
1637 const ::std::string
& needle
, const ::std::string
& haystack
) {
1638 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1641 AssertionResult
IsNotSubstring(
1642 const char* needle_expr
, const char* haystack_expr
,
1643 const ::std::string
& needle
, const ::std::string
& haystack
) {
1644 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1647 #if GTEST_HAS_STD_WSTRING
1648 AssertionResult
IsSubstring(
1649 const char* needle_expr
, const char* haystack_expr
,
1650 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
1651 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1654 AssertionResult
IsNotSubstring(
1655 const char* needle_expr
, const char* haystack_expr
,
1656 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
1657 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1659 #endif // GTEST_HAS_STD_WSTRING
1661 namespace internal
{
1663 #if GTEST_OS_WINDOWS
1667 // Helper function for IsHRESULT{SuccessFailure} predicates
1668 AssertionResult
HRESULTFailureHelper(const char* expr
,
1669 const char* expected
,
1670 long hr
) { // NOLINT
1671 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1673 // Windows CE doesn't support FormatMessage.
1674 const char error_text
[] = "";
1678 // Looks up the human-readable system message for the HRESULT code
1679 // and since we're not passing any params to FormatMessage, we don't
1680 // want inserts expanded.
1681 const DWORD kFlags
= FORMAT_MESSAGE_FROM_SYSTEM
|
1682 FORMAT_MESSAGE_IGNORE_INSERTS
;
1683 const DWORD kBufSize
= 4096;
1684 // Gets the system's human readable message string for this HRESULT.
1685 char error_text
[kBufSize
] = { '\0' };
1686 DWORD message_length
= ::FormatMessageA(kFlags
,
1687 0, // no source, we're asking system
1688 static_cast<DWORD
>(hr
), // the error
1689 0, // no line width restrictions
1690 error_text
, // output buffer
1691 kBufSize
, // buf size
1692 nullptr); // no arguments for inserts
1693 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1694 for (; message_length
&& IsSpace(error_text
[message_length
- 1]);
1696 error_text
[message_length
- 1] = '\0';
1699 # endif // GTEST_OS_WINDOWS_MOBILE
1701 const std::string
error_hex("0x" + String::FormatHexInt(hr
));
1702 return ::testing::AssertionFailure()
1703 << "Expected: " << expr
<< " " << expected
<< ".\n"
1704 << " Actual: " << error_hex
<< " " << error_text
<< "\n";
1709 AssertionResult
IsHRESULTSuccess(const char* expr
, long hr
) { // NOLINT
1710 if (SUCCEEDED(hr
)) {
1711 return AssertionSuccess();
1713 return HRESULTFailureHelper(expr
, "succeeds", hr
);
1716 AssertionResult
IsHRESULTFailure(const char* expr
, long hr
) { // NOLINT
1718 return AssertionSuccess();
1720 return HRESULTFailureHelper(expr
, "fails", hr
);
1723 #endif // GTEST_OS_WINDOWS
1725 // Utility functions for encoding Unicode text (wide strings) in
1728 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1731 // Code-point length Encoding
1732 // 0 - 7 bits 0xxxxxxx
1733 // 8 - 11 bits 110xxxxx 10xxxxxx
1734 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1735 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1737 // The maximum code-point a one-byte UTF-8 sequence can represent.
1738 const UInt32 kMaxCodePoint1
= (static_cast<UInt32
>(1) << 7) - 1;
1740 // The maximum code-point a two-byte UTF-8 sequence can represent.
1741 const UInt32 kMaxCodePoint2
= (static_cast<UInt32
>(1) << (5 + 6)) - 1;
1743 // The maximum code-point a three-byte UTF-8 sequence can represent.
1744 const UInt32 kMaxCodePoint3
= (static_cast<UInt32
>(1) << (4 + 2*6)) - 1;
1746 // The maximum code-point a four-byte UTF-8 sequence can represent.
1747 const UInt32 kMaxCodePoint4
= (static_cast<UInt32
>(1) << (3 + 3*6)) - 1;
1749 // Chops off the n lowest bits from a bit pattern. Returns the n
1750 // lowest bits. As a side effect, the original bit pattern will be
1751 // shifted to the right by n bits.
1752 inline UInt32
ChopLowBits(UInt32
* bits
, int n
) {
1753 const UInt32 low_bits
= *bits
& ((static_cast<UInt32
>(1) << n
) - 1);
1758 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
1759 // code_point parameter is of type UInt32 because wchar_t may not be
1760 // wide enough to contain a code point.
1761 // If the code_point is not a valid Unicode code point
1762 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1763 // to "(Invalid Unicode 0xXXXXXXXX)".
1764 std::string
CodePointToUtf8(UInt32 code_point
) {
1765 if (code_point
> kMaxCodePoint4
) {
1766 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point
) + ")";
1769 char str
[5]; // Big enough for the largest valid code point.
1770 if (code_point
<= kMaxCodePoint1
) {
1772 str
[0] = static_cast<char>(code_point
); // 0xxxxxxx
1773 } else if (code_point
<= kMaxCodePoint2
) {
1775 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1776 str
[0] = static_cast<char>(0xC0 | code_point
); // 110xxxxx
1777 } else if (code_point
<= kMaxCodePoint3
) {
1779 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1780 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1781 str
[0] = static_cast<char>(0xE0 | code_point
); // 1110xxxx
1782 } else { // code_point <= kMaxCodePoint4
1784 str
[3] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1785 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1786 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1787 str
[0] = static_cast<char>(0xF0 | code_point
); // 11110xxx
1792 // The following two functions only make sense if the system
1793 // uses UTF-16 for wide string encoding. All supported systems
1794 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
1796 // Determines if the arguments constitute UTF-16 surrogate pair
1797 // and thus should be combined into a single Unicode code point
1798 // using CreateCodePointFromUtf16SurrogatePair.
1799 inline bool IsUtf16SurrogatePair(wchar_t first
, wchar_t second
) {
1800 return sizeof(wchar_t) == 2 &&
1801 (first
& 0xFC00) == 0xD800 && (second
& 0xFC00) == 0xDC00;
1804 // Creates a Unicode code point from UTF16 surrogate pair.
1805 inline UInt32
CreateCodePointFromUtf16SurrogatePair(wchar_t first
,
1807 const auto first_u
= static_cast<UInt32
>(first
);
1808 const auto second_u
= static_cast<UInt32
>(second
);
1809 const UInt32 mask
= (1 << 10) - 1;
1810 return (sizeof(wchar_t) == 2)
1811 ? (((first_u
& mask
) << 10) | (second_u
& mask
)) + 0x10000
1813 // This function should not be called when the condition is
1814 // false, but we provide a sensible default in case it is.
1818 // Converts a wide string to a narrow string in UTF-8 encoding.
1819 // The wide string is assumed to have the following encoding:
1820 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
1821 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1822 // Parameter str points to a null-terminated wide string.
1823 // Parameter num_chars may additionally limit the number
1824 // of wchar_t characters processed. -1 is used when the entire string
1825 // should be processed.
1826 // If the string contains code points that are not valid Unicode code points
1827 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1828 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1829 // and contains invalid UTF-16 surrogate pairs, values in those pairs
1830 // will be encoded as individual Unicode characters from Basic Normal Plane.
1831 std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
) {
1832 if (num_chars
== -1)
1833 num_chars
= static_cast<int>(wcslen(str
));
1835 ::std::stringstream stream
;
1836 for (int i
= 0; i
< num_chars
; ++i
) {
1837 UInt32 unicode_code_point
;
1839 if (str
[i
] == L
'\0') {
1841 } else if (i
+ 1 < num_chars
&& IsUtf16SurrogatePair(str
[i
], str
[i
+ 1])) {
1842 unicode_code_point
= CreateCodePointFromUtf16SurrogatePair(str
[i
],
1846 unicode_code_point
= static_cast<UInt32
>(str
[i
]);
1849 stream
<< CodePointToUtf8(unicode_code_point
);
1851 return StringStreamToString(&stream
);
1854 // Converts a wide C string to an std::string using the UTF-8 encoding.
1855 // NULL will be converted to "(null)".
1856 std::string
String::ShowWideCString(const wchar_t * wide_c_str
) {
1857 if (wide_c_str
== nullptr) return "(null)";
1859 return internal::WideStringToUtf8(wide_c_str
, -1);
1862 // Compares two wide C strings. Returns true if and only if they have the
1865 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1866 // C string is considered different to any non-NULL C string,
1867 // including the empty string.
1868 bool String::WideCStringEquals(const wchar_t * lhs
, const wchar_t * rhs
) {
1869 if (lhs
== nullptr) return rhs
== nullptr;
1871 if (rhs
== nullptr) return false;
1873 return wcscmp(lhs
, rhs
) == 0;
1876 // Helper function for *_STREQ on wide strings.
1877 AssertionResult
CmpHelperSTREQ(const char* lhs_expression
,
1878 const char* rhs_expression
,
1880 const wchar_t* rhs
) {
1881 if (String::WideCStringEquals(lhs
, rhs
)) {
1882 return AssertionSuccess();
1885 return EqFailure(lhs_expression
,
1892 // Helper function for *_STRNE on wide strings.
1893 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
1894 const char* s2_expression
,
1896 const wchar_t* s2
) {
1897 if (!String::WideCStringEquals(s1
, s2
)) {
1898 return AssertionSuccess();
1901 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
1902 << s2_expression
<< "), actual: "
1903 << PrintToString(s1
)
1904 << " vs " << PrintToString(s2
);
1907 // Compares two C strings, ignoring case. Returns true if and only if they have
1908 // the same content.
1910 // Unlike strcasecmp(), this function can handle NULL argument(s). A
1911 // NULL C string is considered different to any non-NULL C string,
1912 // including the empty string.
1913 bool String::CaseInsensitiveCStringEquals(const char * lhs
, const char * rhs
) {
1914 if (lhs
== nullptr) return rhs
== nullptr;
1915 if (rhs
== nullptr) return false;
1916 return posix::StrCaseCmp(lhs
, rhs
) == 0;
1919 // Compares two wide C strings, ignoring case. Returns true if and only if they
1920 // have the same content.
1922 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1923 // A NULL C string is considered different to any non-NULL wide C string,
1924 // including the empty string.
1925 // NB: The implementations on different platforms slightly differ.
1926 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1927 // environment variable. On GNU platform this method uses wcscasecmp
1928 // which compares according to LC_CTYPE category of the current locale.
1929 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1931 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs
,
1932 const wchar_t* rhs
) {
1933 if (lhs
== nullptr) return rhs
== nullptr;
1935 if (rhs
== nullptr) return false;
1937 #if GTEST_OS_WINDOWS
1938 return _wcsicmp(lhs
, rhs
) == 0;
1939 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1940 return wcscasecmp(lhs
, rhs
) == 0;
1942 // Android, Mac OS X and Cygwin don't define wcscasecmp.
1943 // Other unknown OSes may not define it either.
1946 left
= towlower(static_cast<wint_t>(*lhs
++));
1947 right
= towlower(static_cast<wint_t>(*rhs
++));
1948 } while (left
&& left
== right
);
1949 return left
== right
;
1950 #endif // OS selector
1953 // Returns true if and only if str ends with the given suffix, ignoring case.
1954 // Any string is considered to end with an empty suffix.
1955 bool String::EndsWithCaseInsensitive(
1956 const std::string
& str
, const std::string
& suffix
) {
1957 const size_t str_len
= str
.length();
1958 const size_t suffix_len
= suffix
.length();
1959 return (str_len
>= suffix_len
) &&
1960 CaseInsensitiveCStringEquals(str
.c_str() + str_len
- suffix_len
,
1964 // Formats an int value as "%02d".
1965 std::string
String::FormatIntWidth2(int value
) {
1966 std::stringstream ss
;
1967 ss
<< std::setfill('0') << std::setw(2) << value
;
1971 // Formats an int value as "%X".
1972 std::string
String::FormatHexUInt32(UInt32 value
) {
1973 std::stringstream ss
;
1974 ss
<< std::hex
<< std::uppercase
<< value
;
1978 // Formats an int value as "%X".
1979 std::string
String::FormatHexInt(int value
) {
1980 return FormatHexUInt32(static_cast<UInt32
>(value
));
1983 // Formats a byte as "%02X".
1984 std::string
String::FormatByte(unsigned char value
) {
1985 std::stringstream ss
;
1986 ss
<< std::setfill('0') << std::setw(2) << std::hex
<< std::uppercase
1987 << static_cast<unsigned int>(value
);
1991 // Converts the buffer in a stringstream to an std::string, converting NUL
1992 // bytes to "\\0" along the way.
1993 std::string
StringStreamToString(::std::stringstream
* ss
) {
1994 const ::std::string
& str
= ss
->str();
1995 const char* const start
= str
.c_str();
1996 const char* const end
= start
+ str
.length();
1999 result
.reserve(static_cast<size_t>(2 * (end
- start
)));
2000 for (const char* ch
= start
; ch
!= end
; ++ch
) {
2002 result
+= "\\0"; // Replaces NUL with "\\0";
2011 // Appends the user-supplied message to the Google-Test-generated message.
2012 std::string
AppendUserMessage(const std::string
& gtest_msg
,
2013 const Message
& user_msg
) {
2014 // Appends the user message if it's non-empty.
2015 const std::string user_msg_string
= user_msg
.GetString();
2016 if (user_msg_string
.empty()) {
2020 return gtest_msg
+ "\n" + user_msg_string
;
2023 } // namespace internal
2027 // Creates an empty TestResult.
2028 TestResult::TestResult()
2029 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2032 TestResult::~TestResult() {
2035 // Returns the i-th test part result among all the results. i can
2036 // range from 0 to total_part_count() - 1. If i is not in that range,
2037 // aborts the program.
2038 const TestPartResult
& TestResult::GetTestPartResult(int i
) const {
2039 if (i
< 0 || i
>= total_part_count())
2040 internal::posix::Abort();
2041 return test_part_results_
.at(static_cast<size_t>(i
));
2044 // Returns the i-th test property. i can range from 0 to
2045 // test_property_count() - 1. If i is not in that range, aborts the
2047 const TestProperty
& TestResult::GetTestProperty(int i
) const {
2048 if (i
< 0 || i
>= test_property_count())
2049 internal::posix::Abort();
2050 return test_properties_
.at(static_cast<size_t>(i
));
2053 // Clears the test part results.
2054 void TestResult::ClearTestPartResults() {
2055 test_part_results_
.clear();
2058 // Adds a test part result to the list.
2059 void TestResult::AddTestPartResult(const TestPartResult
& test_part_result
) {
2060 test_part_results_
.push_back(test_part_result
);
2063 // Adds a test property to the list. If a property with the same key as the
2064 // supplied property is already represented, the value of this test_property
2065 // replaces the old value for that key.
2066 void TestResult::RecordProperty(const std::string
& xml_element
,
2067 const TestProperty
& test_property
) {
2068 if (!ValidateTestProperty(xml_element
, test_property
)) {
2071 internal::MutexLock
lock(&test_properites_mutex_
);
2072 const std::vector
<TestProperty
>::iterator property_with_matching_key
=
2073 std::find_if(test_properties_
.begin(), test_properties_
.end(),
2074 internal::TestPropertyKeyIs(test_property
.key()));
2075 if (property_with_matching_key
== test_properties_
.end()) {
2076 test_properties_
.push_back(test_property
);
2079 property_with_matching_key
->SetValue(test_property
.value());
2082 // The list of reserved attributes used in the <testsuites> element of XML
2084 static const char* const kReservedTestSuitesAttributes
[] = {
2095 // The list of reserved attributes used in the <testsuite> element of XML
2097 static const char* const kReservedTestSuiteAttributes
[] = {
2098 "disabled", "errors", "failures", "name", "tests", "time", "timestamp"};
2100 // The list of reserved attributes used in the <testcase> element of XML output.
2101 static const char* const kReservedTestCaseAttributes
[] = {
2102 "classname", "name", "status", "time", "type_param",
2103 "value_param", "file", "line"};
2105 // Use a slightly different set for allowed output to ensure existing tests can
2106 // still RecordProperty("result") or "RecordProperty(timestamp")
2107 static const char* const kReservedOutputTestCaseAttributes
[] = {
2108 "classname", "name", "status", "time", "type_param",
2109 "value_param", "file", "line", "result", "timestamp"};
2111 template <int kSize
>
2112 std::vector
<std::string
> ArrayAsVector(const char* const (&array
)[kSize
]) {
2113 return std::vector
<std::string
>(array
, array
+ kSize
);
2116 static std::vector
<std::string
> GetReservedAttributesForElement(
2117 const std::string
& xml_element
) {
2118 if (xml_element
== "testsuites") {
2119 return ArrayAsVector(kReservedTestSuitesAttributes
);
2120 } else if (xml_element
== "testsuite") {
2121 return ArrayAsVector(kReservedTestSuiteAttributes
);
2122 } else if (xml_element
== "testcase") {
2123 return ArrayAsVector(kReservedTestCaseAttributes
);
2125 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
2127 // This code is unreachable but some compilers may not realizes that.
2128 return std::vector
<std::string
>();
2131 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
2132 static std::vector
<std::string
> GetReservedOutputAttributesForElement(
2133 const std::string
& xml_element
) {
2134 if (xml_element
== "testsuites") {
2135 return ArrayAsVector(kReservedTestSuitesAttributes
);
2136 } else if (xml_element
== "testsuite") {
2137 return ArrayAsVector(kReservedTestSuiteAttributes
);
2138 } else if (xml_element
== "testcase") {
2139 return ArrayAsVector(kReservedOutputTestCaseAttributes
);
2141 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
2143 // This code is unreachable but some compilers may not realizes that.
2144 return std::vector
<std::string
>();
2147 static std::string
FormatWordList(const std::vector
<std::string
>& words
) {
2149 for (size_t i
= 0; i
< words
.size(); ++i
) {
2150 if (i
> 0 && words
.size() > 2) {
2153 if (i
== words
.size() - 1) {
2154 word_list
<< "and ";
2156 word_list
<< "'" << words
[i
] << "'";
2158 return word_list
.GetString();
2161 static bool ValidateTestPropertyName(
2162 const std::string
& property_name
,
2163 const std::vector
<std::string
>& reserved_names
) {
2164 if (std::find(reserved_names
.begin(), reserved_names
.end(), property_name
) !=
2165 reserved_names
.end()) {
2166 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2167 << " (" << FormatWordList(reserved_names
)
2168 << " are reserved by " << GTEST_NAME_
<< ")";
2174 // Adds a failure if the key is a reserved attribute of the element named
2175 // xml_element. Returns true if the property is valid.
2176 bool TestResult::ValidateTestProperty(const std::string
& xml_element
,
2177 const TestProperty
& test_property
) {
2178 return ValidateTestPropertyName(test_property
.key(),
2179 GetReservedAttributesForElement(xml_element
));
2182 // Clears the object.
2183 void TestResult::Clear() {
2184 test_part_results_
.clear();
2185 test_properties_
.clear();
2186 death_test_count_
= 0;
2190 // Returns true off the test part was skipped.
2191 static bool TestPartSkipped(const TestPartResult
& result
) {
2192 return result
.skipped();
2195 // Returns true if and only if the test was skipped.
2196 bool TestResult::Skipped() const {
2197 return !Failed() && CountIf(test_part_results_
, TestPartSkipped
) > 0;
2200 // Returns true if and only if the test failed.
2201 bool TestResult::Failed() const {
2202 for (int i
= 0; i
< total_part_count(); ++i
) {
2203 if (GetTestPartResult(i
).failed())
2209 // Returns true if and only if the test part fatally failed.
2210 static bool TestPartFatallyFailed(const TestPartResult
& result
) {
2211 return result
.fatally_failed();
2214 // Returns true if and only if the test fatally failed.
2215 bool TestResult::HasFatalFailure() const {
2216 return CountIf(test_part_results_
, TestPartFatallyFailed
) > 0;
2219 // Returns true if and only if the test part non-fatally failed.
2220 static bool TestPartNonfatallyFailed(const TestPartResult
& result
) {
2221 return result
.nonfatally_failed();
2224 // Returns true if and only if the test has a non-fatal failure.
2225 bool TestResult::HasNonfatalFailure() const {
2226 return CountIf(test_part_results_
, TestPartNonfatallyFailed
) > 0;
2229 // Gets the number of all test parts. This is the sum of the number
2230 // of successful test parts and the number of failed test parts.
2231 int TestResult::total_part_count() const {
2232 return static_cast<int>(test_part_results_
.size());
2235 // Returns the number of the test properties.
2236 int TestResult::test_property_count() const {
2237 return static_cast<int>(test_properties_
.size());
2242 // Creates a Test object.
2244 // The c'tor saves the states of all flags.
2246 : gtest_flag_saver_(new GTEST_FLAG_SAVER_
) {
2249 // The d'tor restores the states of all flags. The actual work is
2250 // done by the d'tor of the gtest_flag_saver_ field, and thus not
2255 // Sets up the test fixture.
2257 // A sub-class may override this.
2258 void Test::SetUp() {
2261 // Tears down the test fixture.
2263 // A sub-class may override this.
2264 void Test::TearDown() {
2267 // Allows user supplied key value pairs to be recorded for later output.
2268 void Test::RecordProperty(const std::string
& key
, const std::string
& value
) {
2269 UnitTest::GetInstance()->RecordProperty(key
, value
);
2272 // Allows user supplied key value pairs to be recorded for later output.
2273 void Test::RecordProperty(const std::string
& key
, int value
) {
2274 Message value_message
;
2275 value_message
<< value
;
2276 RecordProperty(key
, value_message
.GetString().c_str());
2279 namespace internal
{
2281 void ReportFailureInUnknownLocation(TestPartResult::Type result_type
,
2282 const std::string
& message
) {
2283 // This function is a friend of UnitTest and as such has access to
2284 // AddTestPartResult.
2285 UnitTest::GetInstance()->AddTestPartResult(
2287 nullptr, // No info about the source file where the exception occurred.
2288 -1, // We have no info on which line caused the exception.
2290 ""); // No stack trace, either.
2293 } // namespace internal
2295 // Google Test requires all tests in the same test suite to use the same test
2296 // fixture class. This function checks if the current test has the
2297 // same fixture class as the first test in the current test suite. If
2298 // yes, it returns true; otherwise it generates a Google Test failure and
2300 bool Test::HasSameFixtureClass() {
2301 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2302 const TestSuite
* const test_suite
= impl
->current_test_suite();
2304 // Info about the first test in the current test suite.
2305 const TestInfo
* const first_test_info
= test_suite
->test_info_list()[0];
2306 const internal::TypeId first_fixture_id
= first_test_info
->fixture_class_id_
;
2307 const char* const first_test_name
= first_test_info
->name();
2309 // Info about the current test.
2310 const TestInfo
* const this_test_info
= impl
->current_test_info();
2311 const internal::TypeId this_fixture_id
= this_test_info
->fixture_class_id_
;
2312 const char* const this_test_name
= this_test_info
->name();
2314 if (this_fixture_id
!= first_fixture_id
) {
2315 // Is the first test defined using TEST?
2316 const bool first_is_TEST
= first_fixture_id
== internal::GetTestTypeId();
2317 // Is this test defined using TEST?
2318 const bool this_is_TEST
= this_fixture_id
== internal::GetTestTypeId();
2320 if (first_is_TEST
|| this_is_TEST
) {
2321 // Both TEST and TEST_F appear in same test suite, which is incorrect.
2322 // Tell the user how to fix this.
2324 // Gets the name of the TEST and the name of the TEST_F. Note
2325 // that first_is_TEST and this_is_TEST cannot both be true, as
2326 // the fixture IDs are different for the two tests.
2327 const char* const TEST_name
=
2328 first_is_TEST
? first_test_name
: this_test_name
;
2329 const char* const TEST_F_name
=
2330 first_is_TEST
? this_test_name
: first_test_name
;
2333 << "All tests in the same test suite must use the same test fixture\n"
2334 << "class, so mixing TEST_F and TEST in the same test suite is\n"
2335 << "illegal. In test suite " << this_test_info
->test_suite_name()
2337 << "test " << TEST_F_name
<< " is defined using TEST_F but\n"
2338 << "test " << TEST_name
<< " is defined using TEST. You probably\n"
2339 << "want to change the TEST to TEST_F or move it to another test\n"
2342 // Two fixture classes with the same name appear in two different
2343 // namespaces, which is not allowed. Tell the user how to fix this.
2345 << "All tests in the same test suite must use the same test fixture\n"
2346 << "class. However, in test suite "
2347 << this_test_info
->test_suite_name() << ",\n"
2348 << "you defined test " << first_test_name
<< " and test "
2349 << this_test_name
<< "\n"
2350 << "using two different test fixture classes. This can happen if\n"
2351 << "the two classes are from different namespaces or translation\n"
2352 << "units and have the same name. You should probably rename one\n"
2353 << "of the classes to put the tests into different test suites.";
2363 // Adds an "exception thrown" fatal failure to the current test. This
2364 // function returns its result via an output parameter pointer because VC++
2365 // prohibits creation of objects with destructors on stack in functions
2366 // using __try (see error C2712).
2367 static std::string
* FormatSehExceptionMessage(DWORD exception_code
,
2368 const char* location
) {
2370 message
<< "SEH exception with code 0x" << std::setbase(16) <<
2371 exception_code
<< std::setbase(10) << " thrown in " << location
<< ".";
2373 return new std::string(message
.GetString());
2376 #endif // GTEST_HAS_SEH
2378 namespace internal
{
2380 #if GTEST_HAS_EXCEPTIONS
2382 // Adds an "exception thrown" fatal failure to the current test.
2383 static std::string
FormatCxxExceptionMessage(const char* description
,
2384 const char* location
) {
2386 if (description
!= nullptr) {
2387 message
<< "C++ exception with description \"" << description
<< "\"";
2389 message
<< "Unknown C++ exception";
2391 message
<< " thrown in " << location
<< ".";
2393 return message
.GetString();
2396 static std::string
PrintTestPartResultToString(
2397 const TestPartResult
& test_part_result
);
2399 GoogleTestFailureException::GoogleTestFailureException(
2400 const TestPartResult
& failure
)
2401 : ::std::runtime_error(PrintTestPartResultToString(failure
).c_str()) {}
2403 #endif // GTEST_HAS_EXCEPTIONS
2405 // We put these helper functions in the internal namespace as IBM's xlC
2406 // compiler rejects the code if they were declared static.
2408 // Runs the given method and handles SEH exceptions it throws, when
2409 // SEH is supported; returns the 0-value for type Result in case of an
2410 // SEH exception. (Microsoft compilers cannot handle SEH and C++
2411 // exceptions in the same function. Therefore, we provide a separate
2412 // wrapper function for handling SEH exceptions.)
2413 template <class T
, typename Result
>
2414 Result
HandleSehExceptionsInMethodIfSupported(
2415 T
* object
, Result (T::*method
)(), const char* location
) {
2418 return (object
->*method
)();
2419 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
2420 GetExceptionCode())) {
2421 // We create the exception message on the heap because VC++ prohibits
2422 // creation of objects with destructors on stack in functions using __try
2423 // (see error C2712).
2424 std::string
* exception_message
= FormatSehExceptionMessage(
2425 GetExceptionCode(), location
);
2426 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure
,
2427 *exception_message
);
2428 delete exception_message
;
2429 return static_cast<Result
>(0);
2433 return (object
->*method
)();
2434 #endif // GTEST_HAS_SEH
2437 // Runs the given method and catches and reports C++ and/or SEH-style
2438 // exceptions, if they are supported; returns the 0-value for type
2439 // Result in case of an SEH exception.
2440 template <class T
, typename Result
>
2441 Result
HandleExceptionsInMethodIfSupported(
2442 T
* object
, Result (T::*method
)(), const char* location
) {
2443 // NOTE: The user code can affect the way in which Google Test handles
2444 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2445 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2446 // after the exception is caught and either report or re-throw the
2447 // exception based on the flag's value:
2450 // // Perform the test method.
2452 // if (GTEST_FLAG(catch_exceptions))
2453 // // Report the exception as failure.
2455 // throw; // Re-throws the original exception.
2458 // However, the purpose of this flag is to allow the program to drop into
2459 // the debugger when the exception is thrown. On most platforms, once the
2460 // control enters the catch block, the exception origin information is
2461 // lost and the debugger will stop the program at the point of the
2462 // re-throw in this function -- instead of at the point of the original
2463 // throw statement in the code under test. For this reason, we perform
2464 // the check early, sacrificing the ability to affect Google Test's
2465 // exception handling in the method where the exception is thrown.
2466 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2467 #if GTEST_HAS_EXCEPTIONS
2469 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
2470 } catch (const AssertionException
&) { // NOLINT
2471 // This failure was reported already.
2472 } catch (const internal::GoogleTestFailureException
&) { // NOLINT
2473 // This exception type can only be thrown by a failed Google
2474 // Test assertion with the intention of letting another testing
2475 // framework catch it. Therefore we just re-throw it.
2477 } catch (const std::exception
& e
) { // NOLINT
2478 internal::ReportFailureInUnknownLocation(
2479 TestPartResult::kFatalFailure
,
2480 FormatCxxExceptionMessage(e
.what(), location
));
2481 } catch (...) { // NOLINT
2482 internal::ReportFailureInUnknownLocation(
2483 TestPartResult::kFatalFailure
,
2484 FormatCxxExceptionMessage(nullptr, location
));
2486 return static_cast<Result
>(0);
2488 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
2489 #endif // GTEST_HAS_EXCEPTIONS
2491 return (object
->*method
)();
2495 } // namespace internal
2497 // Runs the test and updates the test result.
2499 if (!HasSameFixtureClass()) return;
2501 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2502 impl
->os_stack_trace_getter()->UponLeavingGTest();
2503 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp
, "SetUp()");
2504 // We will run the test only if SetUp() was successful and didn't call
2506 if (!HasFatalFailure() && !IsSkipped()) {
2507 impl
->os_stack_trace_getter()->UponLeavingGTest();
2508 internal::HandleExceptionsInMethodIfSupported(
2509 this, &Test::TestBody
, "the test body");
2512 // However, we want to clean up as much as possible. Hence we will
2513 // always call TearDown(), even if SetUp() or the test body has
2515 impl
->os_stack_trace_getter()->UponLeavingGTest();
2516 internal::HandleExceptionsInMethodIfSupported(
2517 this, &Test::TearDown
, "TearDown()");
2520 // Returns true if and only if the current test has a fatal failure.
2521 bool Test::HasFatalFailure() {
2522 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2525 // Returns true if and only if the current test has a non-fatal failure.
2526 bool Test::HasNonfatalFailure() {
2527 return internal::GetUnitTestImpl()->current_test_result()->
2528 HasNonfatalFailure();
2531 // Returns true if and only if the current test was skipped.
2532 bool Test::IsSkipped() {
2533 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2538 // Constructs a TestInfo object. It assumes ownership of the test factory
2540 TestInfo::TestInfo(const std::string
& a_test_suite_name
,
2541 const std::string
& a_name
, const char* a_type_param
,
2542 const char* a_value_param
,
2543 internal::CodeLocation a_code_location
,
2544 internal::TypeId fixture_class_id
,
2545 internal::TestFactoryBase
* factory
)
2546 : test_suite_name_(a_test_suite_name
),
2548 type_param_(a_type_param
? new std::string(a_type_param
) : nullptr),
2549 value_param_(a_value_param
? new std::string(a_value_param
) : nullptr),
2550 location_(a_code_location
),
2551 fixture_class_id_(fixture_class_id
),
2553 is_disabled_(false),
2554 matches_filter_(false),
2558 // Destructs a TestInfo object.
2559 TestInfo::~TestInfo() { delete factory_
; }
2561 namespace internal
{
2563 // Creates a new TestInfo object and registers it with Google Test;
2564 // returns the created object.
2568 // test_suite_name: name of the test suite
2569 // name: name of the test
2570 // type_param: the name of the test's type parameter, or NULL if
2571 // this is not a typed or a type-parameterized test.
2572 // value_param: text representation of the test's value parameter,
2573 // or NULL if this is not a value-parameterized test.
2574 // code_location: code location where the test is defined
2575 // fixture_class_id: ID of the test fixture class
2576 // set_up_tc: pointer to the function that sets up the test suite
2577 // tear_down_tc: pointer to the function that tears down the test suite
2578 // factory: pointer to the factory that creates a test object.
2579 // The newly created TestInfo instance will assume
2580 // ownership of the factory object.
2581 TestInfo
* MakeAndRegisterTestInfo(
2582 const char* test_suite_name
, const char* name
, const char* type_param
,
2583 const char* value_param
, CodeLocation code_location
,
2584 TypeId fixture_class_id
, SetUpTestSuiteFunc set_up_tc
,
2585 TearDownTestSuiteFunc tear_down_tc
, TestFactoryBase
* factory
) {
2586 TestInfo
* const test_info
=
2587 new TestInfo(test_suite_name
, name
, type_param
, value_param
,
2588 code_location
, fixture_class_id
, factory
);
2589 GetUnitTestImpl()->AddTestInfo(set_up_tc
, tear_down_tc
, test_info
);
2593 void ReportInvalidTestSuiteType(const char* test_suite_name
,
2594 CodeLocation code_location
) {
2597 << "Attempted redefinition of test suite " << test_suite_name
<< ".\n"
2598 << "All tests in the same test suite must use the same test fixture\n"
2599 << "class. However, in test suite " << test_suite_name
<< ", you tried\n"
2600 << "to define a test using a fixture class different from the one\n"
2601 << "used earlier. This can happen if the two fixture classes are\n"
2602 << "from different namespaces and have the same name. You should\n"
2603 << "probably rename one of the classes to put the tests into different\n"
2606 GTEST_LOG_(ERROR
) << FormatFileLocation(code_location
.file
.c_str(),
2608 << " " << errors
.GetString();
2610 } // namespace internal
2614 // A predicate that checks the test name of a TestInfo against a known
2617 // This is used for implementation of the TestSuite class only. We put
2618 // it in the anonymous namespace to prevent polluting the outer
2621 // TestNameIs is copyable.
2626 // TestNameIs has NO default constructor.
2627 explicit TestNameIs(const char* name
)
2630 // Returns true if and only if the test name of test_info matches name_.
2631 bool operator()(const TestInfo
* test_info
) const {
2632 return test_info
&& test_info
->name() == name_
;
2641 namespace internal
{
2643 // This method expands all parameterized tests registered with macros TEST_P
2644 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
2645 // This will be done just once during the program runtime.
2646 void UnitTestImpl::RegisterParameterizedTests() {
2647 if (!parameterized_tests_registered_
) {
2648 parameterized_test_registry_
.RegisterTests();
2649 parameterized_tests_registered_
= true;
2653 } // namespace internal
2655 // Creates the test object, runs it, records its result, and then
2657 void TestInfo::Run() {
2658 if (!should_run_
) return;
2660 // Tells UnitTest where to store test result.
2661 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2662 impl
->set_current_test_info(this);
2664 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
2666 // Notifies the unit test event listeners that a test is about to start.
2667 repeater
->OnTestStart(*this);
2669 const TimeInMillis start
= internal::GetTimeInMillis();
2671 impl
->os_stack_trace_getter()->UponLeavingGTest();
2673 // Creates the test object.
2674 Test
* const test
= internal::HandleExceptionsInMethodIfSupported(
2675 factory_
, &internal::TestFactoryBase::CreateTest
,
2676 "the test fixture's constructor");
2678 // Runs the test if the constructor didn't generate a fatal failure or invoke
2680 // Note that the object will not be null
2681 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2682 // This doesn't throw as all user code that can throw are wrapped into
2683 // exception handling code.
2687 if (test
!= nullptr) {
2688 // Deletes the test object.
2689 impl
->os_stack_trace_getter()->UponLeavingGTest();
2690 internal::HandleExceptionsInMethodIfSupported(
2691 test
, &Test::DeleteSelf_
, "the test fixture's destructor");
2694 result_
.set_start_timestamp(start
);
2695 result_
.set_elapsed_time(internal::GetTimeInMillis() - start
);
2697 // Notifies the unit test event listener that a test has just finished.
2698 repeater
->OnTestEnd(*this);
2700 // Tells UnitTest to stop associating assertion results to this
2702 impl
->set_current_test_info(nullptr);
2707 // Gets the number of successful tests in this test suite.
2708 int TestSuite::successful_test_count() const {
2709 return CountIf(test_info_list_
, TestPassed
);
2712 // Gets the number of successful tests in this test suite.
2713 int TestSuite::skipped_test_count() const {
2714 return CountIf(test_info_list_
, TestSkipped
);
2717 // Gets the number of failed tests in this test suite.
2718 int TestSuite::failed_test_count() const {
2719 return CountIf(test_info_list_
, TestFailed
);
2722 // Gets the number of disabled tests that will be reported in the XML report.
2723 int TestSuite::reportable_disabled_test_count() const {
2724 return CountIf(test_info_list_
, TestReportableDisabled
);
2727 // Gets the number of disabled tests in this test suite.
2728 int TestSuite::disabled_test_count() const {
2729 return CountIf(test_info_list_
, TestDisabled
);
2732 // Gets the number of tests to be printed in the XML report.
2733 int TestSuite::reportable_test_count() const {
2734 return CountIf(test_info_list_
, TestReportable
);
2737 // Get the number of tests in this test suite that should run.
2738 int TestSuite::test_to_run_count() const {
2739 return CountIf(test_info_list_
, ShouldRunTest
);
2742 // Gets the number of all tests.
2743 int TestSuite::total_test_count() const {
2744 return static_cast<int>(test_info_list_
.size());
2747 // Creates a TestSuite with the given name.
2751 // name: name of the test suite
2752 // a_type_param: the name of the test suite's type parameter, or NULL if
2753 // this is not a typed or a type-parameterized test suite.
2754 // set_up_tc: pointer to the function that sets up the test suite
2755 // tear_down_tc: pointer to the function that tears down the test suite
2756 TestSuite::TestSuite(const char* a_name
, const char* a_type_param
,
2757 internal::SetUpTestSuiteFunc set_up_tc
,
2758 internal::TearDownTestSuiteFunc tear_down_tc
)
2760 type_param_(a_type_param
? new std::string(a_type_param
) : nullptr),
2761 set_up_tc_(set_up_tc
),
2762 tear_down_tc_(tear_down_tc
),
2764 start_timestamp_(0),
2767 // Destructor of TestSuite.
2768 TestSuite::~TestSuite() {
2769 // Deletes every Test in the collection.
2770 ForEach(test_info_list_
, internal::Delete
<TestInfo
>);
2773 // Returns the i-th test among all the tests. i can range from 0 to
2774 // total_test_count() - 1. If i is not in that range, returns NULL.
2775 const TestInfo
* TestSuite::GetTestInfo(int i
) const {
2776 const int index
= GetElementOr(test_indices_
, i
, -1);
2777 return index
< 0 ? nullptr : test_info_list_
[static_cast<size_t>(index
)];
2780 // Returns the i-th test among all the tests. i can range from 0 to
2781 // total_test_count() - 1. If i is not in that range, returns NULL.
2782 TestInfo
* TestSuite::GetMutableTestInfo(int i
) {
2783 const int index
= GetElementOr(test_indices_
, i
, -1);
2784 return index
< 0 ? nullptr : test_info_list_
[static_cast<size_t>(index
)];
2787 // Adds a test to this test suite. Will delete the test upon
2788 // destruction of the TestSuite object.
2789 void TestSuite::AddTestInfo(TestInfo
* test_info
) {
2790 test_info_list_
.push_back(test_info
);
2791 test_indices_
.push_back(static_cast<int>(test_indices_
.size()));
2794 // Runs every test in this TestSuite.
2795 void TestSuite::Run() {
2796 if (!should_run_
) return;
2798 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2799 impl
->set_current_test_suite(this);
2801 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
2803 // Call both legacy and the new API
2804 repeater
->OnTestSuiteStart(*this);
2805 // Legacy API is deprecated but still available
2806 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
2807 repeater
->OnTestCaseStart(*this);
2808 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
2810 impl
->os_stack_trace_getter()->UponLeavingGTest();
2811 internal::HandleExceptionsInMethodIfSupported(
2812 this, &TestSuite::RunSetUpTestSuite
, "SetUpTestSuite()");
2814 start_timestamp_
= internal::GetTimeInMillis();
2815 for (int i
= 0; i
< total_test_count(); i
++) {
2816 GetMutableTestInfo(i
)->Run();
2818 elapsed_time_
= internal::GetTimeInMillis() - start_timestamp_
;
2820 impl
->os_stack_trace_getter()->UponLeavingGTest();
2821 internal::HandleExceptionsInMethodIfSupported(
2822 this, &TestSuite::RunTearDownTestSuite
, "TearDownTestSuite()");
2824 // Call both legacy and the new API
2825 repeater
->OnTestSuiteEnd(*this);
2826 // Legacy API is deprecated but still available
2827 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
2828 repeater
->OnTestCaseEnd(*this);
2829 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
2831 impl
->set_current_test_suite(nullptr);
2834 // Clears the results of all tests in this test suite.
2835 void TestSuite::ClearResult() {
2836 ad_hoc_test_result_
.Clear();
2837 ForEach(test_info_list_
, TestInfo::ClearTestResult
);
2840 // Shuffles the tests in this test suite.
2841 void TestSuite::ShuffleTests(internal::Random
* random
) {
2842 Shuffle(random
, &test_indices_
);
2845 // Restores the test order to before the first shuffle.
2846 void TestSuite::UnshuffleTests() {
2847 for (size_t i
= 0; i
< test_indices_
.size(); i
++) {
2848 test_indices_
[i
] = static_cast<int>(i
);
2852 // Formats a countable noun. Depending on its quantity, either the
2853 // singular form or the plural form is used. e.g.
2855 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2856 // FormatCountableNoun(5, "book", "books") returns "5 books".
2857 static std::string
FormatCountableNoun(int count
,
2858 const char * singular_form
,
2859 const char * plural_form
) {
2860 return internal::StreamableToString(count
) + " " +
2861 (count
== 1 ? singular_form
: plural_form
);
2864 // Formats the count of tests.
2865 static std::string
FormatTestCount(int test_count
) {
2866 return FormatCountableNoun(test_count
, "test", "tests");
2869 // Formats the count of test suites.
2870 static std::string
FormatTestSuiteCount(int test_suite_count
) {
2871 return FormatCountableNoun(test_suite_count
, "test suite", "test suites");
2874 // Converts a TestPartResult::Type enum to human-friendly string
2875 // representation. Both kNonFatalFailure and kFatalFailure are translated
2876 // to "Failure", as the user usually doesn't care about the difference
2877 // between the two when viewing the test result.
2878 static const char * TestPartResultTypeToString(TestPartResult::Type type
) {
2880 case TestPartResult::kSkip
:
2882 case TestPartResult::kSuccess
:
2885 case TestPartResult::kNonFatalFailure
:
2886 case TestPartResult::kFatalFailure
:
2893 return "Unknown result type";
2897 namespace internal
{
2899 // Prints a TestPartResult to an std::string.
2900 static std::string
PrintTestPartResultToString(
2901 const TestPartResult
& test_part_result
) {
2903 << internal::FormatFileLocation(test_part_result
.file_name(),
2904 test_part_result
.line_number())
2905 << " " << TestPartResultTypeToString(test_part_result
.type())
2906 << test_part_result
.message()).GetString();
2909 // Prints a TestPartResult.
2910 static void PrintTestPartResult(const TestPartResult
& test_part_result
) {
2911 const std::string
& result
=
2912 PrintTestPartResultToString(test_part_result
);
2913 printf("%s\n", result
.c_str());
2915 // If the test program runs in Visual Studio or a debugger, the
2916 // following statements add the test part result message to the Output
2917 // window such that the user can double-click on it to jump to the
2918 // corresponding source code location; otherwise they do nothing.
2919 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2920 // We don't call OutputDebugString*() on Windows Mobile, as printing
2921 // to stdout is done by OutputDebugString() there already - we don't
2922 // want the same message printed twice.
2923 ::OutputDebugStringA(result
.c_str());
2924 ::OutputDebugStringA("\n");
2928 // class PrettyUnitTestResultPrinter
2929 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2930 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
2932 // Returns the character attribute for the given color.
2933 static WORD
GetColorAttribute(GTestColor color
) {
2935 case COLOR_RED
: return FOREGROUND_RED
;
2936 case COLOR_GREEN
: return FOREGROUND_GREEN
;
2937 case COLOR_YELLOW
: return FOREGROUND_RED
| FOREGROUND_GREEN
;
2942 static int GetBitOffset(WORD color_mask
) {
2943 if (color_mask
== 0) return 0;
2946 while ((color_mask
& 1) == 0) {
2953 static WORD
GetNewColor(GTestColor color
, WORD old_color_attrs
) {
2954 // Let's reuse the BG
2955 static const WORD background_mask
= BACKGROUND_BLUE
| BACKGROUND_GREEN
|
2956 BACKGROUND_RED
| BACKGROUND_INTENSITY
;
2957 static const WORD foreground_mask
= FOREGROUND_BLUE
| FOREGROUND_GREEN
|
2958 FOREGROUND_RED
| FOREGROUND_INTENSITY
;
2959 const WORD existing_bg
= old_color_attrs
& background_mask
;
2962 GetColorAttribute(color
) | existing_bg
| FOREGROUND_INTENSITY
;
2963 static const int bg_bitOffset
= GetBitOffset(background_mask
);
2964 static const int fg_bitOffset
= GetBitOffset(foreground_mask
);
2966 if (((new_color
& background_mask
) >> bg_bitOffset
) ==
2967 ((new_color
& foreground_mask
) >> fg_bitOffset
)) {
2968 new_color
^= FOREGROUND_INTENSITY
; // invert intensity
2975 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
2976 // an invalid input.
2977 static const char* GetAnsiColorCode(GTestColor color
) {
2979 case COLOR_RED
: return "1";
2980 case COLOR_GREEN
: return "2";
2981 case COLOR_YELLOW
: return "3";
2987 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2989 // Returns true if and only if Google Test should use colors in the output.
2990 bool ShouldUseColor(bool stdout_is_tty
) {
2991 const char* const gtest_color
= GTEST_FLAG(color
).c_str();
2993 if (String::CaseInsensitiveCStringEquals(gtest_color
, "auto")) {
2994 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2995 // On Windows the TERM variable is usually not set, but the
2996 // console there does support colors.
2997 return stdout_is_tty
;
2999 // On non-Windows platforms, we rely on the TERM variable.
3000 const char* const term
= posix::GetEnv("TERM");
3001 const bool term_supports_color
=
3002 String::CStringEquals(term
, "xterm") ||
3003 String::CStringEquals(term
, "xterm-color") ||
3004 String::CStringEquals(term
, "xterm-256color") ||
3005 String::CStringEquals(term
, "screen") ||
3006 String::CStringEquals(term
, "screen-256color") ||
3007 String::CStringEquals(term
, "tmux") ||
3008 String::CStringEquals(term
, "tmux-256color") ||
3009 String::CStringEquals(term
, "rxvt-unicode") ||
3010 String::CStringEquals(term
, "rxvt-unicode-256color") ||
3011 String::CStringEquals(term
, "linux") ||
3012 String::CStringEquals(term
, "cygwin");
3013 return stdout_is_tty
&& term_supports_color
;
3014 #endif // GTEST_OS_WINDOWS
3017 return String::CaseInsensitiveCStringEquals(gtest_color
, "yes") ||
3018 String::CaseInsensitiveCStringEquals(gtest_color
, "true") ||
3019 String::CaseInsensitiveCStringEquals(gtest_color
, "t") ||
3020 String::CStringEquals(gtest_color
, "1");
3021 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3022 // value is neither one of these nor "auto", we treat it as "no" to
3026 // Helpers for printing colored strings to stdout. Note that on Windows, we
3027 // cannot simply emit special characters and have the terminal change colors.
3028 // This routine must actually emit the characters rather than return a string
3029 // that would be colored when printed, as can be done on Linux.
3030 void ColoredPrintf(GTestColor color
, const char* fmt
, ...) {
3032 va_start(args
, fmt
);
3034 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
3035 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
3036 const bool use_color
= AlwaysFalse();
3038 static const bool in_color_mode
=
3039 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout
)) != 0);
3040 const bool use_color
= in_color_mode
&& (color
!= COLOR_DEFAULT
);
3041 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
3049 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3050 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3051 const HANDLE stdout_handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
3053 // Gets the current text color.
3054 CONSOLE_SCREEN_BUFFER_INFO buffer_info
;
3055 GetConsoleScreenBufferInfo(stdout_handle
, &buffer_info
);
3056 const WORD old_color_attrs
= buffer_info
.wAttributes
;
3057 const WORD new_color
= GetNewColor(color
, old_color_attrs
);
3059 // We need to flush the stream buffers into the console before each
3060 // SetConsoleTextAttribute call lest it affect the text that is already
3061 // printed but has not yet reached the console.
3063 SetConsoleTextAttribute(stdout_handle
, new_color
);
3068 // Restores the text color.
3069 SetConsoleTextAttribute(stdout_handle
, old_color_attrs
);
3071 printf("\033[0;3%sm", GetAnsiColorCode(color
));
3073 printf("\033[m"); // Resets the terminal to default.
3074 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3078 // Text printed in Google Test's text output and --gtest_list_tests
3079 // output to label the type parameter and value parameter for a test.
3080 static const char kTypeParamLabel
[] = "TypeParam";
3081 static const char kValueParamLabel
[] = "GetParam()";
3083 static void PrintFullTestCommentIfPresent(const TestInfo
& test_info
) {
3084 const char* const type_param
= test_info
.type_param();
3085 const char* const value_param
= test_info
.value_param();
3087 if (type_param
!= nullptr || value_param
!= nullptr) {
3089 if (type_param
!= nullptr) {
3090 printf("%s = %s", kTypeParamLabel
, type_param
);
3091 if (value_param
!= nullptr) printf(" and ");
3093 if (value_param
!= nullptr) {
3094 printf("%s = %s", kValueParamLabel
, value_param
);
3099 // This class implements the TestEventListener interface.
3101 // Class PrettyUnitTestResultPrinter is copyable.
3102 class PrettyUnitTestResultPrinter
: public TestEventListener
{
3104 PrettyUnitTestResultPrinter() {}
3105 static void PrintTestName(const char* test_suite
, const char* test
) {
3106 printf("%s.%s", test_suite
, test
);
3109 // The following methods override what's in the TestEventListener class.
3110 void OnTestProgramStart(const UnitTest
& /*unit_test*/) override
{}
3111 void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
) override
;
3112 void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
) override
;
3113 void OnEnvironmentsSetUpEnd(const UnitTest
& /*unit_test*/) override
{}
3114 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3115 void OnTestCaseStart(const TestCase
& test_case
) override
;
3117 void OnTestSuiteStart(const TestSuite
& test_suite
) override
;
3118 #endif // OnTestCaseStart
3120 void OnTestStart(const TestInfo
& test_info
) override
;
3122 void OnTestPartResult(const TestPartResult
& result
) override
;
3123 void OnTestEnd(const TestInfo
& test_info
) override
;
3124 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3125 void OnTestCaseEnd(const TestCase
& test_case
) override
;
3127 void OnTestSuiteEnd(const TestSuite
& test_suite
) override
;
3128 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3130 void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
) override
;
3131 void OnEnvironmentsTearDownEnd(const UnitTest
& /*unit_test*/) override
{}
3132 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3133 void OnTestProgramEnd(const UnitTest
& /*unit_test*/) override
{}
3136 static void PrintFailedTests(const UnitTest
& unit_test
);
3137 static void PrintSkippedTests(const UnitTest
& unit_test
);
3140 // Fired before each iteration of tests starts.
3141 void PrettyUnitTestResultPrinter::OnTestIterationStart(
3142 const UnitTest
& unit_test
, int iteration
) {
3143 if (GTEST_FLAG(repeat
) != 1)
3144 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration
+ 1);
3146 const char* const filter
= GTEST_FLAG(filter
).c_str();
3148 // Prints the filter if it's not *. This reminds the user that some
3149 // tests may be skipped.
3150 if (!String::CStringEquals(filter
, kUniversalFilter
)) {
3151 ColoredPrintf(COLOR_YELLOW
,
3152 "Note: %s filter = %s\n", GTEST_NAME_
, filter
);
3155 if (internal::ShouldShard(kTestTotalShards
, kTestShardIndex
, false)) {
3156 const Int32 shard_index
= Int32FromEnvOrDie(kTestShardIndex
, -1);
3157 ColoredPrintf(COLOR_YELLOW
,
3158 "Note: This is test shard %d of %s.\n",
3159 static_cast<int>(shard_index
) + 1,
3160 internal::posix::GetEnv(kTestTotalShards
));
3163 if (GTEST_FLAG(shuffle
)) {
3164 ColoredPrintf(COLOR_YELLOW
,
3165 "Note: Randomizing tests' orders with a seed of %d .\n",
3166 unit_test
.random_seed());
3169 ColoredPrintf(COLOR_GREEN
, "[==========] ");
3170 printf("Running %s from %s.\n",
3171 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
3172 FormatTestSuiteCount(unit_test
.test_suite_to_run_count()).c_str());
3176 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3177 const UnitTest
& /*unit_test*/) {
3178 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3179 printf("Global test environment set-up.\n");
3183 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3184 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase
& test_case
) {
3185 const std::string counts
=
3186 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
3187 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3188 printf("%s from %s", counts
.c_str(), test_case
.name());
3189 if (test_case
.type_param() == nullptr) {
3192 printf(", where %s = %s\n", kTypeParamLabel
, test_case
.type_param());
3197 void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3198 const TestSuite
& test_suite
) {
3199 const std::string counts
=
3200 FormatCountableNoun(test_suite
.test_to_run_count(), "test", "tests");
3201 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3202 printf("%s from %s", counts
.c_str(), test_suite
.name());
3203 if (test_suite
.type_param() == nullptr) {
3206 printf(", where %s = %s\n", kTypeParamLabel
, test_suite
.type_param());
3210 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3212 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo
& test_info
) {
3213 ColoredPrintf(COLOR_GREEN
, "[ RUN ] ");
3214 PrintTestName(test_info
.test_suite_name(), test_info
.name());
3219 // Called after an assertion failure.
3220 void PrettyUnitTestResultPrinter::OnTestPartResult(
3221 const TestPartResult
& result
) {
3222 switch (result
.type()) {
3223 // If the test part succeeded, or was skipped,
3224 // we don't need to do anything.
3225 case TestPartResult::kSkip
:
3226 case TestPartResult::kSuccess
:
3229 // Print failure message from the assertion
3230 // (e.g. expected this and got that).
3231 PrintTestPartResult(result
);
3236 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo
& test_info
) {
3237 if (test_info
.result()->Passed()) {
3238 ColoredPrintf(COLOR_GREEN
, "[ OK ] ");
3239 } else if (test_info
.result()->Skipped()) {
3240 ColoredPrintf(COLOR_GREEN
, "[ SKIPPED ] ");
3242 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
3244 PrintTestName(test_info
.test_suite_name(), test_info
.name());
3245 if (test_info
.result()->Failed())
3246 PrintFullTestCommentIfPresent(test_info
);
3248 if (GTEST_FLAG(print_time
)) {
3249 printf(" (%s ms)\n", internal::StreamableToString(
3250 test_info
.result()->elapsed_time()).c_str());
3257 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3258 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase
& test_case
) {
3259 if (!GTEST_FLAG(print_time
)) return;
3261 const std::string counts
=
3262 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
3263 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3264 printf("%s from %s (%s ms total)\n\n", counts
.c_str(), test_case
.name(),
3265 internal::StreamableToString(test_case
.elapsed_time()).c_str());
3269 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite
& test_suite
) {
3270 if (!GTEST_FLAG(print_time
)) return;
3272 const std::string counts
=
3273 FormatCountableNoun(test_suite
.test_to_run_count(), "test", "tests");
3274 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3275 printf("%s from %s (%s ms total)\n\n", counts
.c_str(), test_suite
.name(),
3276 internal::StreamableToString(test_suite
.elapsed_time()).c_str());
3279 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3281 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3282 const UnitTest
& /*unit_test*/) {
3283 ColoredPrintf(COLOR_GREEN
, "[----------] ");
3284 printf("Global test environment tear-down\n");
3288 // Internal helper for printing the list of failed tests.
3289 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest
& unit_test
) {
3290 const int failed_test_count
= unit_test
.failed_test_count();
3291 if (failed_test_count
== 0) {
3295 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3296 const TestSuite
& test_suite
= *unit_test
.GetTestSuite(i
);
3297 if (!test_suite
.should_run() || (test_suite
.failed_test_count() == 0)) {
3300 for (int j
= 0; j
< test_suite
.total_test_count(); ++j
) {
3301 const TestInfo
& test_info
= *test_suite
.GetTestInfo(j
);
3302 if (!test_info
.should_run() || !test_info
.result()->Failed()) {
3305 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
3306 printf("%s.%s", test_suite
.name(), test_info
.name());
3307 PrintFullTestCommentIfPresent(test_info
);
3313 // Internal helper for printing the list of skipped tests.
3314 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest
& unit_test
) {
3315 const int skipped_test_count
= unit_test
.skipped_test_count();
3316 if (skipped_test_count
== 0) {
3320 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3321 const TestSuite
& test_suite
= *unit_test
.GetTestSuite(i
);
3322 if (!test_suite
.should_run() || (test_suite
.skipped_test_count() == 0)) {
3325 for (int j
= 0; j
< test_suite
.total_test_count(); ++j
) {
3326 const TestInfo
& test_info
= *test_suite
.GetTestInfo(j
);
3327 if (!test_info
.should_run() || !test_info
.result()->Skipped()) {
3330 ColoredPrintf(COLOR_GREEN
, "[ SKIPPED ] ");
3331 printf("%s.%s", test_suite
.name(), test_info
.name());
3337 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
3338 int /*iteration*/) {
3339 ColoredPrintf(COLOR_GREEN
, "[==========] ");
3340 printf("%s from %s ran.",
3341 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
3342 FormatTestSuiteCount(unit_test
.test_suite_to_run_count()).c_str());
3343 if (GTEST_FLAG(print_time
)) {
3344 printf(" (%s ms total)",
3345 internal::StreamableToString(unit_test
.elapsed_time()).c_str());
3348 ColoredPrintf(COLOR_GREEN
, "[ PASSED ] ");
3349 printf("%s.\n", FormatTestCount(unit_test
.successful_test_count()).c_str());
3351 const int skipped_test_count
= unit_test
.skipped_test_count();
3352 if (skipped_test_count
> 0) {
3353 ColoredPrintf(COLOR_GREEN
, "[ SKIPPED ] ");
3354 printf("%s, listed below:\n", FormatTestCount(skipped_test_count
).c_str());
3355 PrintSkippedTests(unit_test
);
3358 int num_failures
= unit_test
.failed_test_count();
3359 if (!unit_test
.Passed()) {
3360 const int failed_test_count
= unit_test
.failed_test_count();
3361 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
3362 printf("%s, listed below:\n", FormatTestCount(failed_test_count
).c_str());
3363 PrintFailedTests(unit_test
);
3364 printf("\n%2d FAILED %s\n", num_failures
,
3365 num_failures
== 1 ? "TEST" : "TESTS");
3368 int num_disabled
= unit_test
.reportable_disabled_test_count();
3369 if (num_disabled
&& !GTEST_FLAG(also_run_disabled_tests
)) {
3370 if (!num_failures
) {
3371 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3373 ColoredPrintf(COLOR_YELLOW
,
3374 " YOU HAVE %d DISABLED %s\n\n",
3376 num_disabled
== 1 ? "TEST" : "TESTS");
3378 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3382 // End PrettyUnitTestResultPrinter
3384 // class TestEventRepeater
3386 // This class forwards events to other event listeners.
3387 class TestEventRepeater
: public TestEventListener
{
3389 TestEventRepeater() : forwarding_enabled_(true) {}
3390 ~TestEventRepeater() override
;
3391 void Append(TestEventListener
*listener
);
3392 TestEventListener
* Release(TestEventListener
* listener
);
3394 // Controls whether events will be forwarded to listeners_. Set to false
3395 // in death test child processes.
3396 bool forwarding_enabled() const { return forwarding_enabled_
; }
3397 void set_forwarding_enabled(bool enable
) { forwarding_enabled_
= enable
; }
3399 void OnTestProgramStart(const UnitTest
& unit_test
) override
;
3400 void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
) override
;
3401 void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
) override
;
3402 void OnEnvironmentsSetUpEnd(const UnitTest
& unit_test
) override
;
3403 // Legacy API is deprecated but still available
3404 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3405 void OnTestCaseStart(const TestSuite
& parameter
) override
;
3406 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3407 void OnTestSuiteStart(const TestSuite
& parameter
) override
;
3408 void OnTestStart(const TestInfo
& test_info
) override
;
3409 void OnTestPartResult(const TestPartResult
& result
) override
;
3410 void OnTestEnd(const TestInfo
& test_info
) override
;
3411 // Legacy API is deprecated but still available
3412 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3413 void OnTestCaseEnd(const TestCase
& parameter
) override
;
3414 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3415 void OnTestSuiteEnd(const TestSuite
& parameter
) override
;
3416 void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
) override
;
3417 void OnEnvironmentsTearDownEnd(const UnitTest
& unit_test
) override
;
3418 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3419 void OnTestProgramEnd(const UnitTest
& unit_test
) override
;
3422 // Controls whether events will be forwarded to listeners_. Set to false
3423 // in death test child processes.
3424 bool forwarding_enabled_
;
3425 // The list of listeners that receive events.
3426 std::vector
<TestEventListener
*> listeners_
;
3428 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater
);
3431 TestEventRepeater::~TestEventRepeater() {
3432 ForEach(listeners_
, Delete
<TestEventListener
>);
3435 void TestEventRepeater::Append(TestEventListener
*listener
) {
3436 listeners_
.push_back(listener
);
3439 TestEventListener
* TestEventRepeater::Release(TestEventListener
*listener
) {
3440 for (size_t i
= 0; i
< listeners_
.size(); ++i
) {
3441 if (listeners_
[i
] == listener
) {
3442 listeners_
.erase(listeners_
.begin() + static_cast<int>(i
));
3450 // Since most methods are very similar, use macros to reduce boilerplate.
3451 // This defines a member that forwards the call to all listeners.
3452 #define GTEST_REPEATER_METHOD_(Name, Type) \
3453 void TestEventRepeater::Name(const Type& parameter) { \
3454 if (forwarding_enabled_) { \
3455 for (size_t i = 0; i < listeners_.size(); i++) { \
3456 listeners_[i]->Name(parameter); \
3460 // This defines a member that forwards the call to all listeners in reverse
3462 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3463 void TestEventRepeater::Name(const Type& parameter) { \
3464 if (forwarding_enabled_) { \
3465 for (size_t i = listeners_.size(); i != 0; i--) { \
3466 listeners_[i - 1]->Name(parameter); \
3471 GTEST_REPEATER_METHOD_(OnTestProgramStart
, UnitTest
)
3472 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart
, UnitTest
)
3473 // Legacy API is deprecated but still available
3474 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3475 GTEST_REPEATER_METHOD_(OnTestCaseStart
, TestSuite
)
3476 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3477 GTEST_REPEATER_METHOD_(OnTestSuiteStart
, TestSuite
)
3478 GTEST_REPEATER_METHOD_(OnTestStart
, TestInfo
)
3479 GTEST_REPEATER_METHOD_(OnTestPartResult
, TestPartResult
)
3480 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart
, UnitTest
)
3481 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd
, UnitTest
)
3482 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd
, UnitTest
)
3483 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd
, TestInfo
)
3484 // Legacy API is deprecated but still available
3485 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3486 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd
, TestSuite
)
3487 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3488 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd
, TestSuite
)
3489 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd
, UnitTest
)
3491 #undef GTEST_REPEATER_METHOD_
3492 #undef GTEST_REVERSE_REPEATER_METHOD_
3494 void TestEventRepeater::OnTestIterationStart(const UnitTest
& unit_test
,
3496 if (forwarding_enabled_
) {
3497 for (size_t i
= 0; i
< listeners_
.size(); i
++) {
3498 listeners_
[i
]->OnTestIterationStart(unit_test
, iteration
);
3503 void TestEventRepeater::OnTestIterationEnd(const UnitTest
& unit_test
,
3505 if (forwarding_enabled_
) {
3506 for (size_t i
= listeners_
.size(); i
> 0; i
--) {
3507 listeners_
[i
- 1]->OnTestIterationEnd(unit_test
, iteration
);
3512 // End TestEventRepeater
3514 // This class generates an XML output file.
3515 class XmlUnitTestResultPrinter
: public EmptyTestEventListener
{
3517 explicit XmlUnitTestResultPrinter(const char* output_file
);
3519 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3520 void ListTestsMatchingFilter(const std::vector
<TestSuite
*>& test_suites
);
3522 // Prints an XML summary of all unit tests.
3523 static void PrintXmlTestsList(std::ostream
* stream
,
3524 const std::vector
<TestSuite
*>& test_suites
);
3527 // Is c a whitespace character that is normalized to a space character
3528 // when it appears in an XML attribute value?
3529 static bool IsNormalizableWhitespace(char c
) {
3530 return c
== 0x9 || c
== 0xA || c
== 0xD;
3533 // May c appear in a well-formed XML document?
3534 static bool IsValidXmlCharacter(char c
) {
3535 return IsNormalizableWhitespace(c
) || c
>= 0x20;
3538 // Returns an XML-escaped copy of the input string str. If
3539 // is_attribute is true, the text is meant to appear as an attribute
3540 // value, and normalizable whitespace is preserved by replacing it
3541 // with character references.
3542 static std::string
EscapeXml(const std::string
& str
, bool is_attribute
);
3544 // Returns the given string with all characters invalid in XML removed.
3545 static std::string
RemoveInvalidXmlCharacters(const std::string
& str
);
3547 // Convenience wrapper around EscapeXml when str is an attribute value.
3548 static std::string
EscapeXmlAttribute(const std::string
& str
) {
3549 return EscapeXml(str
, true);
3552 // Convenience wrapper around EscapeXml when str is not an attribute value.
3553 static std::string
EscapeXmlText(const char* str
) {
3554 return EscapeXml(str
, false);
3557 // Verifies that the given attribute belongs to the given element and
3558 // streams the attribute as XML.
3559 static void OutputXmlAttribute(std::ostream
* stream
,
3560 const std::string
& element_name
,
3561 const std::string
& name
,
3562 const std::string
& value
);
3564 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3565 static void OutputXmlCDataSection(::std::ostream
* stream
, const char* data
);
3567 // Streams an XML representation of a TestInfo object.
3568 static void OutputXmlTestInfo(::std::ostream
* stream
,
3569 const char* test_suite_name
,
3570 const TestInfo
& test_info
);
3572 // Prints an XML representation of a TestSuite object
3573 static void PrintXmlTestSuite(::std::ostream
* stream
,
3574 const TestSuite
& test_suite
);
3576 // Prints an XML summary of unit_test to output stream out.
3577 static void PrintXmlUnitTest(::std::ostream
* stream
,
3578 const UnitTest
& unit_test
);
3580 // Produces a string representing the test properties in a result as space
3581 // delimited XML attributes based on the property key="value" pairs.
3582 // When the std::string is not empty, it includes a space at the beginning,
3583 // to delimit this attribute from prior attributes.
3584 static std::string
TestPropertiesAsXmlAttributes(const TestResult
& result
);
3586 // Streams an XML representation of the test properties of a TestResult
3588 static void OutputXmlTestProperties(std::ostream
* stream
,
3589 const TestResult
& result
);
3592 const std::string output_file_
;
3594 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter
);
3597 // Creates a new XmlUnitTestResultPrinter.
3598 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file
)
3599 : output_file_(output_file
) {
3600 if (output_file_
.empty()) {
3601 GTEST_LOG_(FATAL
) << "XML output file may not be null";
3605 // Called after the unit test ends.
3606 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
3607 int /*iteration*/) {
3608 FILE* xmlout
= OpenFileForWriting(output_file_
);
3609 std::stringstream stream
;
3610 PrintXmlUnitTest(&stream
, unit_test
);
3611 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
3615 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
3616 const std::vector
<TestSuite
*>& test_suites
) {
3617 FILE* xmlout
= OpenFileForWriting(output_file_
);
3618 std::stringstream stream
;
3619 PrintXmlTestsList(&stream
, test_suites
);
3620 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
3624 // Returns an XML-escaped copy of the input string str. If is_attribute
3625 // is true, the text is meant to appear as an attribute value, and
3626 // normalizable whitespace is preserved by replacing it with character
3629 // Invalid XML characters in str, if any, are stripped from the output.
3630 // It is expected that most, if not all, of the text processed by this
3631 // module will consist of ordinary English text.
3632 // If this module is ever modified to produce version 1.1 XML output,
3633 // most invalid characters can be retained using character references.
3634 std::string
XmlUnitTestResultPrinter::EscapeXml(
3635 const std::string
& str
, bool is_attribute
) {
3638 for (size_t i
= 0; i
< str
.size(); ++i
) {
3639 const char ch
= str
[i
];
3663 if (IsValidXmlCharacter(ch
)) {
3664 if (is_attribute
&& IsNormalizableWhitespace(ch
))
3665 m
<< "&#x" << String::FormatByte(static_cast<unsigned char>(ch
))
3674 return m
.GetString();
3677 // Returns the given string with all characters invalid in XML removed.
3678 // Currently invalid characters are dropped from the string. An
3679 // alternative is to replace them with certain characters such as . or ?.
3680 std::string
XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
3681 const std::string
& str
) {
3683 output
.reserve(str
.size());
3684 for (std::string::const_iterator it
= str
.begin(); it
!= str
.end(); ++it
)
3685 if (IsValidXmlCharacter(*it
))
3686 output
.push_back(*it
);
3691 // The following routines generate an XML representation of a UnitTest
3693 // GOOGLETEST_CM0009 DO NOT DELETE
3695 // This is how Google Test concepts map to the DTD:
3697 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3698 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
3699 // <testcase name="test-name"> <-- corresponds to a TestInfo object
3700 // <failure message="...">...</failure>
3701 // <failure message="...">...</failure>
3702 // <failure message="...">...</failure>
3703 // <-- individual assertion failures
3708 // Formats the given time in milliseconds as seconds.
3709 std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
) {
3710 ::std::stringstream ss
;
3711 ss
<< (static_cast<double>(ms
) * 1e-3);
3715 static bool PortableLocaltime(time_t seconds
, struct tm
* out
) {
3716 #if defined(_MSC_VER)
3717 return localtime_s(out
, &seconds
) == 0;
3718 #elif defined(__MINGW32__) || defined(__MINGW64__)
3719 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
3720 // Windows' localtime(), which has a thread-local tm buffer.
3721 struct tm
* tm_ptr
= localtime(&seconds
); // NOLINT
3722 if (tm_ptr
== nullptr) return false;
3726 return localtime_r(&seconds
, out
) != nullptr;
3730 // Converts the given epoch time in milliseconds to a date string in the ISO
3731 // 8601 format, without the timezone information.
3732 std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
) {
3733 struct tm time_struct
;
3734 if (!PortableLocaltime(static_cast<time_t>(ms
/ 1000), &time_struct
))
3736 // YYYY-MM-DDThh:mm:ss
3737 return StreamableToString(time_struct
.tm_year
+ 1900) + "-" +
3738 String::FormatIntWidth2(time_struct
.tm_mon
+ 1) + "-" +
3739 String::FormatIntWidth2(time_struct
.tm_mday
) + "T" +
3740 String::FormatIntWidth2(time_struct
.tm_hour
) + ":" +
3741 String::FormatIntWidth2(time_struct
.tm_min
) + ":" +
3742 String::FormatIntWidth2(time_struct
.tm_sec
);
3745 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3746 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream
* stream
,
3748 const char* segment
= data
;
3749 *stream
<< "<![CDATA[";
3751 const char* const next_segment
= strstr(segment
, "]]>");
3752 if (next_segment
!= nullptr) {
3754 segment
, static_cast<std::streamsize
>(next_segment
- segment
));
3755 *stream
<< "]]>]]><![CDATA[";
3756 segment
= next_segment
+ strlen("]]>");
3765 void XmlUnitTestResultPrinter::OutputXmlAttribute(
3766 std::ostream
* stream
,
3767 const std::string
& element_name
,
3768 const std::string
& name
,
3769 const std::string
& value
) {
3770 const std::vector
<std::string
>& allowed_names
=
3771 GetReservedOutputAttributesForElement(element_name
);
3773 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
3774 allowed_names
.end())
3775 << "Attribute " << name
<< " is not allowed for element <" << element_name
3778 *stream
<< " " << name
<< "=\"" << EscapeXmlAttribute(value
) << "\"";
3781 // Prints an XML representation of a TestInfo object.
3782 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream
* stream
,
3783 const char* test_suite_name
,
3784 const TestInfo
& test_info
) {
3785 const TestResult
& result
= *test_info
.result();
3786 const std::string kTestsuite
= "testcase";
3788 if (test_info
.is_in_another_shard()) {
3792 *stream
<< " <testcase";
3793 OutputXmlAttribute(stream
, kTestsuite
, "name", test_info
.name());
3795 if (test_info
.value_param() != nullptr) {
3796 OutputXmlAttribute(stream
, kTestsuite
, "value_param",
3797 test_info
.value_param());
3799 if (test_info
.type_param() != nullptr) {
3800 OutputXmlAttribute(stream
, kTestsuite
, "type_param",
3801 test_info
.type_param());
3803 if (GTEST_FLAG(list_tests
)) {
3804 OutputXmlAttribute(stream
, kTestsuite
, "file", test_info
.file());
3805 OutputXmlAttribute(stream
, kTestsuite
, "line",
3806 StreamableToString(test_info
.line()));
3811 OutputXmlAttribute(stream
, kTestsuite
, "status",
3812 test_info
.should_run() ? "run" : "notrun");
3813 OutputXmlAttribute(stream
, kTestsuite
, "result",
3814 test_info
.should_run()
3815 ? (result
.Skipped() ? "skipped" : "completed")
3817 OutputXmlAttribute(stream
, kTestsuite
, "time",
3818 FormatTimeInMillisAsSeconds(result
.elapsed_time()));
3820 stream
, kTestsuite
, "timestamp",
3821 FormatEpochTimeInMillisAsIso8601(result
.start_timestamp()));
3822 OutputXmlAttribute(stream
, kTestsuite
, "classname", test_suite_name
);
3825 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
3826 const TestPartResult
& part
= result
.GetTestPartResult(i
);
3827 if (part
.failed()) {
3828 if (++failures
== 1) {
3831 const std::string location
=
3832 internal::FormatCompilerIndependentFileLocation(part
.file_name(),
3833 part
.line_number());
3834 const std::string summary
= location
+ "\n" + part
.summary();
3835 *stream
<< " <failure message=\""
3836 << EscapeXmlAttribute(summary
.c_str())
3838 const std::string detail
= location
+ "\n" + part
.message();
3839 OutputXmlCDataSection(stream
, RemoveInvalidXmlCharacters(detail
).c_str());
3840 *stream
<< "</failure>\n";
3844 if (failures
== 0 && result
.test_property_count() == 0) {
3847 if (failures
== 0) {
3850 OutputXmlTestProperties(stream
, result
);
3851 *stream
<< " </testcase>\n";
3855 // Prints an XML representation of a TestSuite object
3856 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream
* stream
,
3857 const TestSuite
& test_suite
) {
3858 const std::string kTestsuite
= "testsuite";
3859 *stream
<< " <" << kTestsuite
;
3860 OutputXmlAttribute(stream
, kTestsuite
, "name", test_suite
.name());
3861 OutputXmlAttribute(stream
, kTestsuite
, "tests",
3862 StreamableToString(test_suite
.reportable_test_count()));
3863 if (!GTEST_FLAG(list_tests
)) {
3864 OutputXmlAttribute(stream
, kTestsuite
, "failures",
3865 StreamableToString(test_suite
.failed_test_count()));
3867 stream
, kTestsuite
, "disabled",
3868 StreamableToString(test_suite
.reportable_disabled_test_count()));
3869 OutputXmlAttribute(stream
, kTestsuite
, "errors", "0");
3870 OutputXmlAttribute(stream
, kTestsuite
, "time",
3871 FormatTimeInMillisAsSeconds(test_suite
.elapsed_time()));
3873 stream
, kTestsuite
, "timestamp",
3874 FormatEpochTimeInMillisAsIso8601(test_suite
.start_timestamp()));
3875 *stream
<< TestPropertiesAsXmlAttributes(test_suite
.ad_hoc_test_result());
3878 for (int i
= 0; i
< test_suite
.total_test_count(); ++i
) {
3879 if (test_suite
.GetTestInfo(i
)->is_reportable())
3880 OutputXmlTestInfo(stream
, test_suite
.name(), *test_suite
.GetTestInfo(i
));
3882 *stream
<< " </" << kTestsuite
<< ">\n";
3885 // Prints an XML summary of unit_test to output stream out.
3886 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream
* stream
,
3887 const UnitTest
& unit_test
) {
3888 const std::string kTestsuites
= "testsuites";
3890 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3891 *stream
<< "<" << kTestsuites
;
3893 OutputXmlAttribute(stream
, kTestsuites
, "tests",
3894 StreamableToString(unit_test
.reportable_test_count()));
3895 OutputXmlAttribute(stream
, kTestsuites
, "failures",
3896 StreamableToString(unit_test
.failed_test_count()));
3898 stream
, kTestsuites
, "disabled",
3899 StreamableToString(unit_test
.reportable_disabled_test_count()));
3900 OutputXmlAttribute(stream
, kTestsuites
, "errors", "0");
3901 OutputXmlAttribute(stream
, kTestsuites
, "time",
3902 FormatTimeInMillisAsSeconds(unit_test
.elapsed_time()));
3904 stream
, kTestsuites
, "timestamp",
3905 FormatEpochTimeInMillisAsIso8601(unit_test
.start_timestamp()));
3907 if (GTEST_FLAG(shuffle
)) {
3908 OutputXmlAttribute(stream
, kTestsuites
, "random_seed",
3909 StreamableToString(unit_test
.random_seed()));
3911 *stream
<< TestPropertiesAsXmlAttributes(unit_test
.ad_hoc_test_result());
3913 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
3916 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3917 if (unit_test
.GetTestSuite(i
)->reportable_test_count() > 0)
3918 PrintXmlTestSuite(stream
, *unit_test
.GetTestSuite(i
));
3920 *stream
<< "</" << kTestsuites
<< ">\n";
3923 void XmlUnitTestResultPrinter::PrintXmlTestsList(
3924 std::ostream
* stream
, const std::vector
<TestSuite
*>& test_suites
) {
3925 const std::string kTestsuites
= "testsuites";
3927 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3928 *stream
<< "<" << kTestsuites
;
3930 int total_tests
= 0;
3931 for (auto test_suite
: test_suites
) {
3932 total_tests
+= test_suite
->total_test_count();
3934 OutputXmlAttribute(stream
, kTestsuites
, "tests",
3935 StreamableToString(total_tests
));
3936 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
3939 for (auto test_suite
: test_suites
) {
3940 PrintXmlTestSuite(stream
, *test_suite
);
3942 *stream
<< "</" << kTestsuites
<< ">\n";
3945 // Produces a string representing the test properties in a result as space
3946 // delimited XML attributes based on the property key="value" pairs.
3947 std::string
XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3948 const TestResult
& result
) {
3950 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
3951 const TestProperty
& property
= result
.GetTestProperty(i
);
3952 attributes
<< " " << property
.key() << "="
3953 << "\"" << EscapeXmlAttribute(property
.value()) << "\"";
3955 return attributes
.GetString();
3958 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
3959 std::ostream
* stream
, const TestResult
& result
) {
3960 const std::string kProperties
= "properties";
3961 const std::string kProperty
= "property";
3963 if (result
.test_property_count() <= 0) {
3967 *stream
<< "<" << kProperties
<< ">\n";
3968 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
3969 const TestProperty
& property
= result
.GetTestProperty(i
);
3970 *stream
<< "<" << kProperty
;
3971 *stream
<< " name=\"" << EscapeXmlAttribute(property
.key()) << "\"";
3972 *stream
<< " value=\"" << EscapeXmlAttribute(property
.value()) << "\"";
3975 *stream
<< "</" << kProperties
<< ">\n";
3978 // End XmlUnitTestResultPrinter
3980 // This class generates an JSON output file.
3981 class JsonUnitTestResultPrinter
: public EmptyTestEventListener
{
3983 explicit JsonUnitTestResultPrinter(const char* output_file
);
3985 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3987 // Prints an JSON summary of all unit tests.
3988 static void PrintJsonTestList(::std::ostream
* stream
,
3989 const std::vector
<TestSuite
*>& test_suites
);
3992 // Returns an JSON-escaped copy of the input string str.
3993 static std::string
EscapeJson(const std::string
& str
);
3995 //// Verifies that the given attribute belongs to the given element and
3996 //// streams the attribute as JSON.
3997 static void OutputJsonKey(std::ostream
* stream
,
3998 const std::string
& element_name
,
3999 const std::string
& name
,
4000 const std::string
& value
,
4001 const std::string
& indent
,
4003 static void OutputJsonKey(std::ostream
* stream
,
4004 const std::string
& element_name
,
4005 const std::string
& name
,
4007 const std::string
& indent
,
4010 // Streams a JSON representation of a TestInfo object.
4011 static void OutputJsonTestInfo(::std::ostream
* stream
,
4012 const char* test_suite_name
,
4013 const TestInfo
& test_info
);
4015 // Prints a JSON representation of a TestSuite object
4016 static void PrintJsonTestSuite(::std::ostream
* stream
,
4017 const TestSuite
& test_suite
);
4019 // Prints a JSON summary of unit_test to output stream out.
4020 static void PrintJsonUnitTest(::std::ostream
* stream
,
4021 const UnitTest
& unit_test
);
4023 // Produces a string representing the test properties in a result as
4024 // a JSON dictionary.
4025 static std::string
TestPropertiesAsJson(const TestResult
& result
,
4026 const std::string
& indent
);
4029 const std::string output_file_
;
4031 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter
);
4034 // Creates a new JsonUnitTestResultPrinter.
4035 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file
)
4036 : output_file_(output_file
) {
4037 if (output_file_
.empty()) {
4038 GTEST_LOG_(FATAL
) << "JSON output file may not be null";
4042 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4043 int /*iteration*/) {
4044 FILE* jsonout
= OpenFileForWriting(output_file_
);
4045 std::stringstream stream
;
4046 PrintJsonUnitTest(&stream
, unit_test
);
4047 fprintf(jsonout
, "%s", StringStreamToString(&stream
).c_str());
4051 // Returns an JSON-escaped copy of the input string str.
4052 std::string
JsonUnitTestResultPrinter::EscapeJson(const std::string
& str
) {
4055 for (size_t i
= 0; i
< str
.size(); ++i
) {
4056 const char ch
= str
[i
];
4080 m
<< "\\u00" << String::FormatByte(static_cast<unsigned char>(ch
));
4088 return m
.GetString();
4091 // The following routines generate an JSON representation of a UnitTest
4094 // Formats the given time in milliseconds as seconds.
4095 static std::string
FormatTimeInMillisAsDuration(TimeInMillis ms
) {
4096 ::std::stringstream ss
;
4097 ss
<< (static_cast<double>(ms
) * 1e-3) << "s";
4101 // Converts the given epoch time in milliseconds to a date string in the
4102 // RFC3339 format, without the timezone information.
4103 static std::string
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms
) {
4104 struct tm time_struct
;
4105 if (!PortableLocaltime(static_cast<time_t>(ms
/ 1000), &time_struct
))
4107 // YYYY-MM-DDThh:mm:ss
4108 return StreamableToString(time_struct
.tm_year
+ 1900) + "-" +
4109 String::FormatIntWidth2(time_struct
.tm_mon
+ 1) + "-" +
4110 String::FormatIntWidth2(time_struct
.tm_mday
) + "T" +
4111 String::FormatIntWidth2(time_struct
.tm_hour
) + ":" +
4112 String::FormatIntWidth2(time_struct
.tm_min
) + ":" +
4113 String::FormatIntWidth2(time_struct
.tm_sec
) + "Z";
4116 static inline std::string
Indent(size_t width
) {
4117 return std::string(width
, ' ');
4120 void JsonUnitTestResultPrinter::OutputJsonKey(
4121 std::ostream
* stream
,
4122 const std::string
& element_name
,
4123 const std::string
& name
,
4124 const std::string
& value
,
4125 const std::string
& indent
,
4127 const std::vector
<std::string
>& allowed_names
=
4128 GetReservedOutputAttributesForElement(element_name
);
4130 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4131 allowed_names
.end())
4132 << "Key \"" << name
<< "\" is not allowed for value \"" << element_name
4135 *stream
<< indent
<< "\"" << name
<< "\": \"" << EscapeJson(value
) << "\"";
4140 void JsonUnitTestResultPrinter::OutputJsonKey(
4141 std::ostream
* stream
,
4142 const std::string
& element_name
,
4143 const std::string
& name
,
4145 const std::string
& indent
,
4147 const std::vector
<std::string
>& allowed_names
=
4148 GetReservedOutputAttributesForElement(element_name
);
4150 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4151 allowed_names
.end())
4152 << "Key \"" << name
<< "\" is not allowed for value \"" << element_name
4155 *stream
<< indent
<< "\"" << name
<< "\": " << StreamableToString(value
);
4160 // Prints a JSON representation of a TestInfo object.
4161 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream
* stream
,
4162 const char* test_suite_name
,
4163 const TestInfo
& test_info
) {
4164 const TestResult
& result
= *test_info
.result();
4165 const std::string kTestsuite
= "testcase";
4166 const std::string kIndent
= Indent(10);
4168 *stream
<< Indent(8) << "{\n";
4169 OutputJsonKey(stream
, kTestsuite
, "name", test_info
.name(), kIndent
);
4171 if (test_info
.value_param() != nullptr) {
4172 OutputJsonKey(stream
, kTestsuite
, "value_param", test_info
.value_param(),
4175 if (test_info
.type_param() != nullptr) {
4176 OutputJsonKey(stream
, kTestsuite
, "type_param", test_info
.type_param(),
4179 if (GTEST_FLAG(list_tests
)) {
4180 OutputJsonKey(stream
, kTestsuite
, "file", test_info
.file(), kIndent
);
4181 OutputJsonKey(stream
, kTestsuite
, "line", test_info
.line(), kIndent
, false);
4182 *stream
<< "\n" << Indent(8) << "}";
4186 OutputJsonKey(stream
, kTestsuite
, "status",
4187 test_info
.should_run() ? "RUN" : "NOTRUN", kIndent
);
4188 OutputJsonKey(stream
, kTestsuite
, "result",
4189 test_info
.should_run()
4190 ? (result
.Skipped() ? "SKIPPED" : "COMPLETED")
4193 OutputJsonKey(stream
, kTestsuite
, "timestamp",
4194 FormatEpochTimeInMillisAsRFC3339(result
.start_timestamp()),
4196 OutputJsonKey(stream
, kTestsuite
, "time",
4197 FormatTimeInMillisAsDuration(result
.elapsed_time()), kIndent
);
4198 OutputJsonKey(stream
, kTestsuite
, "classname", test_suite_name
, kIndent
,
4200 *stream
<< TestPropertiesAsJson(result
, kIndent
);
4203 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
4204 const TestPartResult
& part
= result
.GetTestPartResult(i
);
4205 if (part
.failed()) {
4207 if (++failures
== 1) {
4208 *stream
<< kIndent
<< "\"" << "failures" << "\": [\n";
4210 const std::string location
=
4211 internal::FormatCompilerIndependentFileLocation(part
.file_name(),
4212 part
.line_number());
4213 const std::string message
= EscapeJson(location
+ "\n" + part
.message());
4214 *stream
<< kIndent
<< " {\n"
4215 << kIndent
<< " \"failure\": \"" << message
<< "\",\n"
4216 << kIndent
<< " \"type\": \"\"\n"
4222 *stream
<< "\n" << kIndent
<< "]";
4223 *stream
<< "\n" << Indent(8) << "}";
4226 // Prints an JSON representation of a TestSuite object
4227 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4228 std::ostream
* stream
, const TestSuite
& test_suite
) {
4229 const std::string kTestsuite
= "testsuite";
4230 const std::string kIndent
= Indent(6);
4232 *stream
<< Indent(4) << "{\n";
4233 OutputJsonKey(stream
, kTestsuite
, "name", test_suite
.name(), kIndent
);
4234 OutputJsonKey(stream
, kTestsuite
, "tests", test_suite
.reportable_test_count(),
4236 if (!GTEST_FLAG(list_tests
)) {
4237 OutputJsonKey(stream
, kTestsuite
, "failures",
4238 test_suite
.failed_test_count(), kIndent
);
4239 OutputJsonKey(stream
, kTestsuite
, "disabled",
4240 test_suite
.reportable_disabled_test_count(), kIndent
);
4241 OutputJsonKey(stream
, kTestsuite
, "errors", 0, kIndent
);
4243 stream
, kTestsuite
, "timestamp",
4244 FormatEpochTimeInMillisAsRFC3339(test_suite
.start_timestamp()),
4246 OutputJsonKey(stream
, kTestsuite
, "time",
4247 FormatTimeInMillisAsDuration(test_suite
.elapsed_time()),
4249 *stream
<< TestPropertiesAsJson(test_suite
.ad_hoc_test_result(), kIndent
)
4253 *stream
<< kIndent
<< "\"" << kTestsuite
<< "\": [\n";
4256 for (int i
= 0; i
< test_suite
.total_test_count(); ++i
) {
4257 if (test_suite
.GetTestInfo(i
)->is_reportable()) {
4263 OutputJsonTestInfo(stream
, test_suite
.name(), *test_suite
.GetTestInfo(i
));
4266 *stream
<< "\n" << kIndent
<< "]\n" << Indent(4) << "}";
4269 // Prints a JSON summary of unit_test to output stream out.
4270 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream
* stream
,
4271 const UnitTest
& unit_test
) {
4272 const std::string kTestsuites
= "testsuites";
4273 const std::string kIndent
= Indent(2);
4276 OutputJsonKey(stream
, kTestsuites
, "tests", unit_test
.reportable_test_count(),
4278 OutputJsonKey(stream
, kTestsuites
, "failures", unit_test
.failed_test_count(),
4280 OutputJsonKey(stream
, kTestsuites
, "disabled",
4281 unit_test
.reportable_disabled_test_count(), kIndent
);
4282 OutputJsonKey(stream
, kTestsuites
, "errors", 0, kIndent
);
4283 if (GTEST_FLAG(shuffle
)) {
4284 OutputJsonKey(stream
, kTestsuites
, "random_seed", unit_test
.random_seed(),
4287 OutputJsonKey(stream
, kTestsuites
, "timestamp",
4288 FormatEpochTimeInMillisAsRFC3339(unit_test
.start_timestamp()),
4290 OutputJsonKey(stream
, kTestsuites
, "time",
4291 FormatTimeInMillisAsDuration(unit_test
.elapsed_time()), kIndent
,
4294 *stream
<< TestPropertiesAsJson(unit_test
.ad_hoc_test_result(), kIndent
)
4297 OutputJsonKey(stream
, kTestsuites
, "name", "AllTests", kIndent
);
4298 *stream
<< kIndent
<< "\"" << kTestsuites
<< "\": [\n";
4301 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
4302 if (unit_test
.GetTestSuite(i
)->reportable_test_count() > 0) {
4308 PrintJsonTestSuite(stream
, *unit_test
.GetTestSuite(i
));
4312 *stream
<< "\n" << kIndent
<< "]\n" << "}\n";
4315 void JsonUnitTestResultPrinter::PrintJsonTestList(
4316 std::ostream
* stream
, const std::vector
<TestSuite
*>& test_suites
) {
4317 const std::string kTestsuites
= "testsuites";
4318 const std::string kIndent
= Indent(2);
4320 int total_tests
= 0;
4321 for (auto test_suite
: test_suites
) {
4322 total_tests
+= test_suite
->total_test_count();
4324 OutputJsonKey(stream
, kTestsuites
, "tests", total_tests
, kIndent
);
4326 OutputJsonKey(stream
, kTestsuites
, "name", "AllTests", kIndent
);
4327 *stream
<< kIndent
<< "\"" << kTestsuites
<< "\": [\n";
4329 for (size_t i
= 0; i
< test_suites
.size(); ++i
) {
4333 PrintJsonTestSuite(stream
, *test_suites
[i
]);
4340 // Produces a string representing the test properties in a result as
4341 // a JSON dictionary.
4342 std::string
JsonUnitTestResultPrinter::TestPropertiesAsJson(
4343 const TestResult
& result
, const std::string
& indent
) {
4345 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4346 const TestProperty
& property
= result
.GetTestProperty(i
);
4347 attributes
<< ",\n" << indent
<< "\"" << property
.key() << "\": "
4348 << "\"" << EscapeJson(property
.value()) << "\"";
4350 return attributes
.GetString();
4353 // End JsonUnitTestResultPrinter
4355 #if GTEST_CAN_STREAM_RESULTS_
4357 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4358 // replaces them by "%xx" where xx is their hexadecimal value. For
4359 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4360 // in both time and space -- important as the input str may contain an
4361 // arbitrarily long test failure message and stack trace.
4362 std::string
StreamingListener::UrlEncode(const char* str
) {
4364 result
.reserve(strlen(str
) + 1);
4365 for (char ch
= *str
; ch
!= '\0'; ch
= *++str
) {
4371 result
.append("%" + String::FormatByte(static_cast<unsigned char>(ch
)));
4374 result
.push_back(ch
);
4381 void StreamingListener::SocketWriter::MakeConnection() {
4382 GTEST_CHECK_(sockfd_
== -1)
4383 << "MakeConnection() can't be called when there is already a connection.";
4386 memset(&hints
, 0, sizeof(hints
));
4387 hints
.ai_family
= AF_UNSPEC
; // To allow both IPv4 and IPv6 addresses.
4388 hints
.ai_socktype
= SOCK_STREAM
;
4389 addrinfo
* servinfo
= nullptr;
4391 // Use the getaddrinfo() to get a linked list of IP addresses for
4392 // the given host name.
4393 const int error_num
= getaddrinfo(
4394 host_name_
.c_str(), port_num_
.c_str(), &hints
, &servinfo
);
4395 if (error_num
!= 0) {
4396 GTEST_LOG_(WARNING
) << "stream_result_to: getaddrinfo() failed: "
4397 << gai_strerror(error_num
);
4400 // Loop through all the results and connect to the first we can.
4401 for (addrinfo
* cur_addr
= servinfo
; sockfd_
== -1 && cur_addr
!= nullptr;
4402 cur_addr
= cur_addr
->ai_next
) {
4404 cur_addr
->ai_family
, cur_addr
->ai_socktype
, cur_addr
->ai_protocol
);
4405 if (sockfd_
!= -1) {
4406 // Connect the client socket to the server socket.
4407 if (connect(sockfd_
, cur_addr
->ai_addr
, cur_addr
->ai_addrlen
) == -1) {
4414 freeaddrinfo(servinfo
); // all done with this structure
4416 if (sockfd_
== -1) {
4417 GTEST_LOG_(WARNING
) << "stream_result_to: failed to connect to "
4418 << host_name_
<< ":" << port_num_
;
4422 // End of class Streaming Listener
4423 #endif // GTEST_CAN_STREAM_RESULTS__
4425 // class OsStackTraceGetter
4427 const char* const OsStackTraceGetterInterface::kElidedFramesMarker
=
4428 "... " GTEST_NAME_
" internal frames ...";
4430 std::string
OsStackTraceGetter::CurrentStackTrace(int max_depth
, int skip_count
)
4431 GTEST_LOCK_EXCLUDED_(mutex_
) {
4435 if (max_depth
<= 0) {
4439 max_depth
= std::min(max_depth
, kMaxStackTraceDepth
);
4441 std::vector
<void*> raw_stack(max_depth
);
4442 // Skips the frames requested by the caller, plus this function.
4443 const int raw_stack_size
=
4444 absl::GetStackTrace(&raw_stack
[0], max_depth
, skip_count
+ 1);
4446 void* caller_frame
= nullptr;
4448 MutexLock
lock(&mutex_
);
4449 caller_frame
= caller_frame_
;
4452 for (int i
= 0; i
< raw_stack_size
; ++i
) {
4453 if (raw_stack
[i
] == caller_frame
&&
4454 !GTEST_FLAG(show_internal_stack_frames
)) {
4455 // Add a marker to the trace and stop adding frames.
4456 absl::StrAppend(&result
, kElidedFramesMarker
, "\n");
4461 const char* symbol
= "(unknown)";
4462 if (absl::Symbolize(raw_stack
[i
], tmp
, sizeof(tmp
))) {
4467 snprintf(line
, sizeof(line
), " %p: %s\n", raw_stack
[i
], symbol
);
4473 #else // !GTEST_HAS_ABSL
4474 static_cast<void>(max_depth
);
4475 static_cast<void>(skip_count
);
4477 #endif // GTEST_HAS_ABSL
4480 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_
) {
4482 void* caller_frame
= nullptr;
4483 if (absl::GetStackTrace(&caller_frame
, 1, 3) <= 0) {
4484 caller_frame
= nullptr;
4487 MutexLock
lock(&mutex_
);
4488 caller_frame_
= caller_frame
;
4489 #endif // GTEST_HAS_ABSL
4492 // A helper class that creates the premature-exit file in its
4493 // constructor and deletes the file in its destructor.
4494 class ScopedPrematureExitFile
{
4496 explicit ScopedPrematureExitFile(const char* premature_exit_filepath
)
4497 : premature_exit_filepath_(premature_exit_filepath
?
4498 premature_exit_filepath
: "") {
4499 // If a path to the premature-exit file is specified...
4500 if (!premature_exit_filepath_
.empty()) {
4501 // create the file with a single "0" character in it. I/O
4502 // errors are ignored as there's nothing better we can do and we
4503 // don't want to fail the test because of this.
4504 FILE* pfile
= posix::FOpen(premature_exit_filepath
, "w");
4505 fwrite("0", 1, 1, pfile
);
4510 ~ScopedPrematureExitFile() {
4511 if (!premature_exit_filepath_
.empty()) {
4512 int retval
= remove(premature_exit_filepath_
.c_str());
4514 GTEST_LOG_(ERROR
) << "Failed to remove premature exit filepath \""
4515 << premature_exit_filepath_
<< "\" with error "
4522 const std::string premature_exit_filepath_
;
4524 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile
);
4527 } // namespace internal
4529 // class TestEventListeners
4531 TestEventListeners::TestEventListeners()
4532 : repeater_(new internal::TestEventRepeater()),
4533 default_result_printer_(nullptr),
4534 default_xml_generator_(nullptr) {}
4536 TestEventListeners::~TestEventListeners() { delete repeater_
; }
4538 // Returns the standard listener responsible for the default console
4539 // output. Can be removed from the listeners list to shut down default
4540 // console output. Note that removing this object from the listener list
4541 // with Release transfers its ownership to the user.
4542 void TestEventListeners::Append(TestEventListener
* listener
) {
4543 repeater_
->Append(listener
);
4546 // Removes the given event listener from the list and returns it. It then
4547 // becomes the caller's responsibility to delete the listener. Returns
4548 // NULL if the listener is not found in the list.
4549 TestEventListener
* TestEventListeners::Release(TestEventListener
* listener
) {
4550 if (listener
== default_result_printer_
)
4551 default_result_printer_
= nullptr;
4552 else if (listener
== default_xml_generator_
)
4553 default_xml_generator_
= nullptr;
4554 return repeater_
->Release(listener
);
4557 // Returns repeater that broadcasts the TestEventListener events to all
4559 TestEventListener
* TestEventListeners::repeater() { return repeater_
; }
4561 // Sets the default_result_printer attribute to the provided listener.
4562 // The listener is also added to the listener list and previous
4563 // default_result_printer is removed from it and deleted. The listener can
4564 // also be NULL in which case it will not be added to the list. Does
4565 // nothing if the previous and the current listener objects are the same.
4566 void TestEventListeners::SetDefaultResultPrinter(TestEventListener
* listener
) {
4567 if (default_result_printer_
!= listener
) {
4568 // It is an error to pass this method a listener that is already in the
4570 delete Release(default_result_printer_
);
4571 default_result_printer_
= listener
;
4572 if (listener
!= nullptr) Append(listener
);
4576 // Sets the default_xml_generator attribute to the provided listener. The
4577 // listener is also added to the listener list and previous
4578 // default_xml_generator is removed from it and deleted. The listener can
4579 // also be NULL in which case it will not be added to the list. Does
4580 // nothing if the previous and the current listener objects are the same.
4581 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener
* listener
) {
4582 if (default_xml_generator_
!= listener
) {
4583 // It is an error to pass this method a listener that is already in the
4585 delete Release(default_xml_generator_
);
4586 default_xml_generator_
= listener
;
4587 if (listener
!= nullptr) Append(listener
);
4591 // Controls whether events will be forwarded by the repeater to the
4592 // listeners in the list.
4593 bool TestEventListeners::EventForwardingEnabled() const {
4594 return repeater_
->forwarding_enabled();
4597 void TestEventListeners::SuppressEventForwarding() {
4598 repeater_
->set_forwarding_enabled(false);
4603 // Gets the singleton UnitTest object. The first time this method is
4604 // called, a UnitTest object is constructed and returned. Consecutive
4605 // calls will return the same object.
4607 // We don't protect this under mutex_ as a user is not supposed to
4608 // call this before main() starts, from which point on the return
4609 // value will never change.
4610 UnitTest
* UnitTest::GetInstance() {
4611 // CodeGear C++Builder insists on a public destructor for the
4612 // default implementation. Use this implementation to keep good OO
4613 // design with private destructor.
4615 #if defined(__BORLANDC__)
4616 static UnitTest
* const instance
= new UnitTest
;
4619 static UnitTest instance
;
4621 #endif // defined(__BORLANDC__)
4624 // Gets the number of successful test suites.
4625 int UnitTest::successful_test_suite_count() const {
4626 return impl()->successful_test_suite_count();
4629 // Gets the number of failed test suites.
4630 int UnitTest::failed_test_suite_count() const {
4631 return impl()->failed_test_suite_count();
4634 // Gets the number of all test suites.
4635 int UnitTest::total_test_suite_count() const {
4636 return impl()->total_test_suite_count();
4639 // Gets the number of all test suites that contain at least one test
4641 int UnitTest::test_suite_to_run_count() const {
4642 return impl()->test_suite_to_run_count();
4645 // Legacy API is deprecated but still available
4646 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4647 int UnitTest::successful_test_case_count() const {
4648 return impl()->successful_test_suite_count();
4650 int UnitTest::failed_test_case_count() const {
4651 return impl()->failed_test_suite_count();
4653 int UnitTest::total_test_case_count() const {
4654 return impl()->total_test_suite_count();
4656 int UnitTest::test_case_to_run_count() const {
4657 return impl()->test_suite_to_run_count();
4659 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4661 // Gets the number of successful tests.
4662 int UnitTest::successful_test_count() const {
4663 return impl()->successful_test_count();
4666 // Gets the number of skipped tests.
4667 int UnitTest::skipped_test_count() const {
4668 return impl()->skipped_test_count();
4671 // Gets the number of failed tests.
4672 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4674 // Gets the number of disabled tests that will be reported in the XML report.
4675 int UnitTest::reportable_disabled_test_count() const {
4676 return impl()->reportable_disabled_test_count();
4679 // Gets the number of disabled tests.
4680 int UnitTest::disabled_test_count() const {
4681 return impl()->disabled_test_count();
4684 // Gets the number of tests to be printed in the XML report.
4685 int UnitTest::reportable_test_count() const {
4686 return impl()->reportable_test_count();
4689 // Gets the number of all tests.
4690 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4692 // Gets the number of tests that should run.
4693 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4695 // Gets the time of the test program start, in ms from the start of the
4697 internal::TimeInMillis
UnitTest::start_timestamp() const {
4698 return impl()->start_timestamp();
4701 // Gets the elapsed time, in milliseconds.
4702 internal::TimeInMillis
UnitTest::elapsed_time() const {
4703 return impl()->elapsed_time();
4706 // Returns true if and only if the unit test passed (i.e. all test suites
4708 bool UnitTest::Passed() const { return impl()->Passed(); }
4710 // Returns true if and only if the unit test failed (i.e. some test suite
4711 // failed or something outside of all tests failed).
4712 bool UnitTest::Failed() const { return impl()->Failed(); }
4714 // Gets the i-th test suite among all the test suites. i can range from 0 to
4715 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
4716 const TestSuite
* UnitTest::GetTestSuite(int i
) const {
4717 return impl()->GetTestSuite(i
);
4720 // Legacy API is deprecated but still available
4721 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4722 const TestCase
* UnitTest::GetTestCase(int i
) const {
4723 return impl()->GetTestCase(i
);
4725 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4727 // Returns the TestResult containing information on test failures and
4728 // properties logged outside of individual test suites.
4729 const TestResult
& UnitTest::ad_hoc_test_result() const {
4730 return *impl()->ad_hoc_test_result();
4733 // Gets the i-th test suite among all the test suites. i can range from 0 to
4734 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
4735 TestSuite
* UnitTest::GetMutableTestSuite(int i
) {
4736 return impl()->GetMutableSuiteCase(i
);
4739 // Returns the list of event listeners that can be used to track events
4740 // inside Google Test.
4741 TestEventListeners
& UnitTest::listeners() {
4742 return *impl()->listeners();
4745 // Registers and returns a global test environment. When a test
4746 // program is run, all global test environments will be set-up in the
4747 // order they were registered. After all tests in the program have
4748 // finished, all global test environments will be torn-down in the
4749 // *reverse* order they were registered.
4751 // The UnitTest object takes ownership of the given environment.
4753 // We don't protect this under mutex_, as we only support calling it
4754 // from the main thread.
4755 Environment
* UnitTest::AddEnvironment(Environment
* env
) {
4756 if (env
== nullptr) {
4760 impl_
->environments().push_back(env
);
4764 // Adds a TestPartResult to the current TestResult object. All Google Test
4765 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4766 // this to report their results. The user code should use the
4767 // assertion macros instead of calling this directly.
4768 void UnitTest::AddTestPartResult(
4769 TestPartResult::Type result_type
,
4770 const char* file_name
,
4772 const std::string
& message
,
4773 const std::string
& os_stack_trace
) GTEST_LOCK_EXCLUDED_(mutex_
) {
4777 internal::MutexLock
lock(&mutex_
);
4778 if (impl_
->gtest_trace_stack().size() > 0) {
4779 msg
<< "\n" << GTEST_NAME_
<< " trace:";
4781 for (size_t i
= impl_
->gtest_trace_stack().size(); i
> 0; --i
) {
4782 const internal::TraceInfo
& trace
= impl_
->gtest_trace_stack()[i
- 1];
4783 msg
<< "\n" << internal::FormatFileLocation(trace
.file
, trace
.line
)
4784 << " " << trace
.message
;
4788 if (os_stack_trace
.c_str() != nullptr && !os_stack_trace
.empty()) {
4789 msg
<< internal::kStackTraceMarker
<< os_stack_trace
;
4792 const TestPartResult result
= TestPartResult(
4793 result_type
, file_name
, line_number
, msg
.GetString().c_str());
4794 impl_
->GetTestPartResultReporterForCurrentThread()->
4795 ReportTestPartResult(result
);
4797 if (result_type
!= TestPartResult::kSuccess
&&
4798 result_type
!= TestPartResult::kSkip
) {
4799 // gtest_break_on_failure takes precedence over
4800 // gtest_throw_on_failure. This allows a user to set the latter
4801 // in the code (perhaps in order to use Google Test assertions
4802 // with another testing framework) and specify the former on the
4803 // command line for debugging.
4804 if (GTEST_FLAG(break_on_failure
)) {
4805 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4806 // Using DebugBreak on Windows allows gtest to still break into a debugger
4807 // when a failure happens and both the --gtest_break_on_failure and
4808 // the --gtest_catch_exceptions flags are specified.
4810 #elif (!defined(__native_client__)) && \
4811 ((defined(__clang__) || defined(__GNUC__)) && \
4812 (defined(__x86_64__) || defined(__i386__)))
4813 // with clang/gcc we can achieve the same effect on x86 by invoking int3
4816 // Dereference nullptr through a volatile pointer to prevent the compiler
4817 // from removing. We use this rather than abort() or __builtin_trap() for
4818 // portability: some debuggers don't correctly trap abort().
4819 *static_cast<volatile int*>(nullptr) = 1;
4820 #endif // GTEST_OS_WINDOWS
4821 } else if (GTEST_FLAG(throw_on_failure
)) {
4822 #if GTEST_HAS_EXCEPTIONS
4823 throw internal::GoogleTestFailureException(result
);
4825 // We cannot call abort() as it generates a pop-up in debug mode
4826 // that cannot be suppressed in VC 7.1 or below.
4833 // Adds a TestProperty to the current TestResult object when invoked from
4834 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
4835 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
4836 // when invoked elsewhere. If the result already contains a property with
4837 // the same key, the value will be updated.
4838 void UnitTest::RecordProperty(const std::string
& key
,
4839 const std::string
& value
) {
4840 impl_
->RecordProperty(TestProperty(key
, value
));
4843 // Runs all tests in this UnitTest object and prints the result.
4844 // Returns 0 if successful, or 1 otherwise.
4846 // We don't protect this under mutex_, as we only support calling it
4847 // from the main thread.
4848 int UnitTest::Run() {
4849 const bool in_death_test_child_process
=
4850 internal::GTEST_FLAG(internal_run_death_test
).length() > 0;
4852 // Google Test implements this protocol for catching that a test
4853 // program exits before returning control to Google Test:
4855 // 1. Upon start, Google Test creates a file whose absolute path
4856 // is specified by the environment variable
4857 // TEST_PREMATURE_EXIT_FILE.
4858 // 2. When Google Test has finished its work, it deletes the file.
4860 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
4861 // running a Google-Test-based test program and check the existence
4862 // of the file at the end of the test execution to see if it has
4863 // exited prematurely.
4865 // If we are in the child process of a death test, don't
4866 // create/delete the premature exit file, as doing so is unnecessary
4867 // and will confuse the parent process. Otherwise, create/delete
4868 // the file upon entering/leaving this function. If the program
4869 // somehow exits before this function has a chance to return, the
4870 // premature-exit file will be left undeleted, causing a test runner
4871 // that understands the premature-exit-file protocol to report the
4872 // test as having failed.
4873 const internal::ScopedPrematureExitFile
premature_exit_file(
4874 in_death_test_child_process
4876 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
4878 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
4879 // used for the duration of the program.
4880 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions
));
4882 #if GTEST_OS_WINDOWS
4883 // Either the user wants Google Test to catch exceptions thrown by the
4884 // tests or this is executing in the context of death test child
4885 // process. In either case the user does not want to see pop-up dialogs
4886 // about crashes - they are expected.
4887 if (impl()->catch_exceptions() || in_death_test_child_process
) {
4888 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4889 // SetErrorMode doesn't exist on CE.
4890 SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOALIGNMENTFAULTEXCEPT
|
4891 SEM_NOGPFAULTERRORBOX
| SEM_NOOPENFILEERRORBOX
);
4892 # endif // !GTEST_OS_WINDOWS_MOBILE
4894 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4895 // Death test children can be terminated with _abort(). On Windows,
4896 // _abort() can show a dialog with a warning message. This forces the
4897 // abort message to go to stderr instead.
4898 _set_error_mode(_OUT_TO_STDERR
);
4901 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
4902 // In the debug version, Visual Studio pops up a separate dialog
4903 // offering a choice to debug the aborted program. We need to suppress
4904 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
4905 // executed. Google Test will notify the user of any unexpected
4906 // failure via stderr.
4907 if (!GTEST_FLAG(break_on_failure
))
4908 _set_abort_behavior(
4909 0x0, // Clear the following flags:
4910 _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
); // pop-up window, core dump.
4913 // In debug mode, the Windows CRT can crash with an assertion over invalid
4914 // input (e.g. passing an invalid file descriptor). The default handling
4915 // for these assertions is to pop up a dialog and wait for user input.
4916 // Instead ask the CRT to dump such assertions to stderr non-interactively.
4917 if (!IsDebuggerPresent()) {
4918 (void)_CrtSetReportMode(_CRT_ASSERT
,
4919 _CRTDBG_MODE_FILE
| _CRTDBG_MODE_DEBUG
);
4920 (void)_CrtSetReportFile(_CRT_ASSERT
, _CRTDBG_FILE_STDERR
);
4923 #endif // GTEST_OS_WINDOWS
4925 return internal::HandleExceptionsInMethodIfSupported(
4927 &internal::UnitTestImpl::RunAllTests
,
4928 "auxiliary test code (environments or event listeners)") ? 0 : 1;
4931 // Returns the working directory when the first TEST() or TEST_F() was
4933 const char* UnitTest::original_working_dir() const {
4934 return impl_
->original_working_dir_
.c_str();
4937 // Returns the TestSuite object for the test that's currently running,
4938 // or NULL if no test is running.
4939 const TestSuite
* UnitTest::current_test_suite() const
4940 GTEST_LOCK_EXCLUDED_(mutex_
) {
4941 internal::MutexLock
lock(&mutex_
);
4942 return impl_
->current_test_suite();
4945 // Legacy API is still available but deprecated
4946 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4947 const TestCase
* UnitTest::current_test_case() const
4948 GTEST_LOCK_EXCLUDED_(mutex_
) {
4949 internal::MutexLock
lock(&mutex_
);
4950 return impl_
->current_test_suite();
4954 // Returns the TestInfo object for the test that's currently running,
4955 // or NULL if no test is running.
4956 const TestInfo
* UnitTest::current_test_info() const
4957 GTEST_LOCK_EXCLUDED_(mutex_
) {
4958 internal::MutexLock
lock(&mutex_
);
4959 return impl_
->current_test_info();
4962 // Returns the random seed used at the start of the current test run.
4963 int UnitTest::random_seed() const { return impl_
->random_seed(); }
4965 // Returns ParameterizedTestSuiteRegistry object used to keep track of
4966 // value-parameterized tests and instantiate and register them.
4967 internal::ParameterizedTestSuiteRegistry
&
4968 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_
) {
4969 return impl_
->parameterized_test_registry();
4972 // Creates an empty UnitTest.
4973 UnitTest::UnitTest() {
4974 impl_
= new internal::UnitTestImpl(this);
4977 // Destructor of UnitTest.
4978 UnitTest::~UnitTest() {
4982 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
4983 // Google Test trace stack.
4984 void UnitTest::PushGTestTrace(const internal::TraceInfo
& trace
)
4985 GTEST_LOCK_EXCLUDED_(mutex_
) {
4986 internal::MutexLock
lock(&mutex_
);
4987 impl_
->gtest_trace_stack().push_back(trace
);
4990 // Pops a trace from the per-thread Google Test trace stack.
4991 void UnitTest::PopGTestTrace()
4992 GTEST_LOCK_EXCLUDED_(mutex_
) {
4993 internal::MutexLock
lock(&mutex_
);
4994 impl_
->gtest_trace_stack().pop_back();
4997 namespace internal
{
4999 UnitTestImpl::UnitTestImpl(UnitTest
* parent
)
5001 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5002 default_global_test_part_result_reporter_(this),
5003 default_per_thread_test_part_result_reporter_(this),
5004 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
5005 &default_global_test_part_result_reporter_
),
5006 per_thread_test_part_result_reporter_(
5007 &default_per_thread_test_part_result_reporter_
),
5008 parameterized_test_registry_(),
5009 parameterized_tests_registered_(false),
5010 last_death_test_suite_(-1),
5011 current_test_suite_(nullptr),
5012 current_test_info_(nullptr),
5013 ad_hoc_test_result_(),
5014 os_stack_trace_getter_(nullptr),
5015 post_flag_parse_init_performed_(false),
5016 random_seed_(0), // Will be overridden by the flag before first use.
5017 random_(0), // Will be reseeded before first use.
5018 start_timestamp_(0),
5020 #if GTEST_HAS_DEATH_TEST
5021 death_test_factory_(new DefaultDeathTestFactory
),
5023 // Will be overridden by the flag before first use.
5024 catch_exceptions_(false) {
5025 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter
);
5028 UnitTestImpl::~UnitTestImpl() {
5029 // Deletes every TestSuite.
5030 ForEach(test_suites_
, internal::Delete
<TestSuite
>);
5032 // Deletes every Environment.
5033 ForEach(environments_
, internal::Delete
<Environment
>);
5035 delete os_stack_trace_getter_
;
5038 // Adds a TestProperty to the current TestResult object when invoked in a
5039 // context of a test, to current test suite's ad_hoc_test_result when invoke
5040 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
5041 // otherwise. If the result already contains a property with the same key,
5042 // the value will be updated.
5043 void UnitTestImpl::RecordProperty(const TestProperty
& test_property
) {
5044 std::string xml_element
;
5045 TestResult
* test_result
; // TestResult appropriate for property recording.
5047 if (current_test_info_
!= nullptr) {
5048 xml_element
= "testcase";
5049 test_result
= &(current_test_info_
->result_
);
5050 } else if (current_test_suite_
!= nullptr) {
5051 xml_element
= "testsuite";
5052 test_result
= &(current_test_suite_
->ad_hoc_test_result_
);
5054 xml_element
= "testsuites";
5055 test_result
= &ad_hoc_test_result_
;
5057 test_result
->RecordProperty(xml_element
, test_property
);
5060 #if GTEST_HAS_DEATH_TEST
5061 // Disables event forwarding if the control is currently in a death test
5062 // subprocess. Must not be called before InitGoogleTest.
5063 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5064 if (internal_run_death_test_flag_
.get() != nullptr)
5065 listeners()->SuppressEventForwarding();
5067 #endif // GTEST_HAS_DEATH_TEST
5069 // Initializes event listeners performing XML output as specified by
5070 // UnitTestOptions. Must not be called before InitGoogleTest.
5071 void UnitTestImpl::ConfigureXmlOutput() {
5072 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5073 if (output_format
== "xml") {
5074 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5075 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5076 } else if (output_format
== "json") {
5077 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
5078 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5079 } else if (output_format
!= "") {
5080 GTEST_LOG_(WARNING
) << "WARNING: unrecognized output format \""
5081 << output_format
<< "\" ignored.";
5085 #if GTEST_CAN_STREAM_RESULTS_
5086 // Initializes event listeners for streaming test results in string form.
5087 // Must not be called before InitGoogleTest.
5088 void UnitTestImpl::ConfigureStreamingOutput() {
5089 const std::string
& target
= GTEST_FLAG(stream_result_to
);
5090 if (!target
.empty()) {
5091 const size_t pos
= target
.find(':');
5092 if (pos
!= std::string::npos
) {
5093 listeners()->Append(new StreamingListener(target
.substr(0, pos
),
5094 target
.substr(pos
+1)));
5096 GTEST_LOG_(WARNING
) << "unrecognized streaming target \"" << target
5101 #endif // GTEST_CAN_STREAM_RESULTS_
5103 // Performs initialization dependent upon flag values obtained in
5104 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5105 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5106 // this function is also called from RunAllTests. Since this function can be
5107 // called more than once, it has to be idempotent.
5108 void UnitTestImpl::PostFlagParsingInit() {
5109 // Ensures that this function does not execute more than once.
5110 if (!post_flag_parse_init_performed_
) {
5111 post_flag_parse_init_performed_
= true;
5113 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5114 // Register to send notifications about key process state changes.
5115 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5116 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5118 #if GTEST_HAS_DEATH_TEST
5119 InitDeathTestSubprocessControlInfo();
5120 SuppressTestEventsIfInSubprocess();
5121 #endif // GTEST_HAS_DEATH_TEST
5123 // Registers parameterized tests. This makes parameterized tests
5124 // available to the UnitTest reflection API without running
5126 RegisterParameterizedTests();
5128 // Configures listeners for XML output. This makes it possible for users
5129 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5130 ConfigureXmlOutput();
5132 #if GTEST_CAN_STREAM_RESULTS_
5133 // Configures listeners for streaming test results to the specified server.
5134 ConfigureStreamingOutput();
5135 #endif // GTEST_CAN_STREAM_RESULTS_
5138 if (GTEST_FLAG(install_failure_signal_handler
)) {
5139 absl::FailureSignalHandlerOptions options
;
5140 absl::InstallFailureSignalHandler(options
);
5142 #endif // GTEST_HAS_ABSL
5146 // A predicate that checks the name of a TestSuite against a known
5149 // This is used for implementation of the UnitTest class only. We put
5150 // it in the anonymous namespace to prevent polluting the outer
5153 // TestSuiteNameIs is copyable.
5154 class TestSuiteNameIs
{
5157 explicit TestSuiteNameIs(const std::string
& name
) : name_(name
) {}
5159 // Returns true if and only if the name of test_suite matches name_.
5160 bool operator()(const TestSuite
* test_suite
) const {
5161 return test_suite
!= nullptr &&
5162 strcmp(test_suite
->name(), name_
.c_str()) == 0;
5169 // Finds and returns a TestSuite with the given name. If one doesn't
5170 // exist, creates one and returns it. It's the CALLER'S
5171 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5172 // TESTS ARE NOT SHUFFLED.
5176 // test_suite_name: name of the test suite
5177 // type_param: the name of the test suite's type parameter, or NULL if
5178 // this is not a typed or a type-parameterized test suite.
5179 // set_up_tc: pointer to the function that sets up the test suite
5180 // tear_down_tc: pointer to the function that tears down the test suite
5181 TestSuite
* UnitTestImpl::GetTestSuite(
5182 const char* test_suite_name
, const char* type_param
,
5183 internal::SetUpTestSuiteFunc set_up_tc
,
5184 internal::TearDownTestSuiteFunc tear_down_tc
) {
5185 // Can we find a TestSuite with the given name?
5186 const auto test_suite
=
5187 std::find_if(test_suites_
.rbegin(), test_suites_
.rend(),
5188 TestSuiteNameIs(test_suite_name
));
5190 if (test_suite
!= test_suites_
.rend()) return *test_suite
;
5192 // No. Let's create one.
5193 auto* const new_test_suite
=
5194 new TestSuite(test_suite_name
, type_param
, set_up_tc
, tear_down_tc
);
5196 // Is this a death test suite?
5197 if (internal::UnitTestOptions::MatchesFilter(test_suite_name
,
5198 kDeathTestSuiteFilter
)) {
5199 // Yes. Inserts the test suite after the last death test suite
5200 // defined so far. This only works when the test suites haven't
5201 // been shuffled. Otherwise we may end up running a death test
5202 // after a non-death test.
5203 ++last_death_test_suite_
;
5204 test_suites_
.insert(test_suites_
.begin() + last_death_test_suite_
,
5207 // No. Appends to the end of the list.
5208 test_suites_
.push_back(new_test_suite
);
5211 test_suite_indices_
.push_back(static_cast<int>(test_suite_indices_
.size()));
5212 return new_test_suite
;
5215 // Helpers for setting up / tearing down the given environment. They
5216 // are for use in the ForEach() function.
5217 static void SetUpEnvironment(Environment
* env
) { env
->SetUp(); }
5218 static void TearDownEnvironment(Environment
* env
) { env
->TearDown(); }
5220 // Runs all tests in this UnitTest object, prints the result, and
5221 // returns true if all tests are successful. If any exception is
5222 // thrown during a test, the test is considered to be failed, but the
5223 // rest of the tests will still be run.
5225 // When parameterized tests are enabled, it expands and registers
5226 // parameterized tests first in RegisterParameterizedTests().
5227 // All other functions called from RunAllTests() may safely assume that
5228 // parameterized tests are ready to be counted and run.
5229 bool UnitTestImpl::RunAllTests() {
5230 // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
5232 const bool gtest_is_initialized_before_run_all_tests
= GTestIsInitialized();
5234 // Do not run any test if the --help flag was specified.
5238 // Repeats the call to the post-flag parsing initialization in case the
5239 // user didn't call InitGoogleTest.
5240 PostFlagParsingInit();
5242 // Even if sharding is not on, test runners may want to use the
5243 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5245 internal::WriteToShardStatusFileIfNeeded();
5247 // True if and only if we are in a subprocess for running a thread-safe-style
5249 bool in_subprocess_for_death_test
= false;
5251 #if GTEST_HAS_DEATH_TEST
5252 in_subprocess_for_death_test
=
5253 (internal_run_death_test_flag_
.get() != nullptr);
5254 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5255 if (in_subprocess_for_death_test
) {
5256 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5258 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5259 #endif // GTEST_HAS_DEATH_TEST
5261 const bool should_shard
= ShouldShard(kTestTotalShards
, kTestShardIndex
,
5262 in_subprocess_for_death_test
);
5264 // Compares the full test names with the filter to decide which
5266 const bool has_tests_to_run
= FilterTests(should_shard
5267 ? HONOR_SHARDING_PROTOCOL
5268 : IGNORE_SHARDING_PROTOCOL
) > 0;
5270 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5271 if (GTEST_FLAG(list_tests
)) {
5272 // This must be called *after* FilterTests() has been called.
5273 ListTestsMatchingFilter();
5277 random_seed_
= GTEST_FLAG(shuffle
) ?
5278 GetRandomSeedFromFlag(GTEST_FLAG(random_seed
)) : 0;
5280 // True if and only if at least one test has failed.
5281 bool failed
= false;
5283 TestEventListener
* repeater
= listeners()->repeater();
5285 start_timestamp_
= GetTimeInMillis();
5286 repeater
->OnTestProgramStart(*parent_
);
5288 // How many times to repeat the tests? We don't want to repeat them
5289 // when we are inside the subprocess of a death test.
5290 const int repeat
= in_subprocess_for_death_test
? 1 : GTEST_FLAG(repeat
);
5291 // Repeats forever if the repeat count is negative.
5292 const bool gtest_repeat_forever
= repeat
< 0;
5293 for (int i
= 0; gtest_repeat_forever
|| i
!= repeat
; i
++) {
5294 // We want to preserve failures generated by ad-hoc test
5295 // assertions executed before RUN_ALL_TESTS().
5296 ClearNonAdHocTestResult();
5298 const TimeInMillis start
= GetTimeInMillis();
5300 // Shuffles test suites and tests if requested.
5301 if (has_tests_to_run
&& GTEST_FLAG(shuffle
)) {
5302 random()->Reseed(static_cast<UInt32
>(random_seed_
));
5303 // This should be done before calling OnTestIterationStart(),
5304 // such that a test event listener can see the actual test order
5309 // Tells the unit test event listeners that the tests are about to start.
5310 repeater
->OnTestIterationStart(*parent_
, i
);
5312 // Runs each test suite if there is at least one test to run.
5313 if (has_tests_to_run
) {
5314 // Sets up all environments beforehand.
5315 repeater
->OnEnvironmentsSetUpStart(*parent_
);
5316 ForEach(environments_
, SetUpEnvironment
);
5317 repeater
->OnEnvironmentsSetUpEnd(*parent_
);
5319 // Runs the tests only if there was no fatal failure or skip triggered
5320 // during global set-up.
5321 if (Test::IsSkipped()) {
5322 // Emit diagnostics when global set-up calls skip, as it will not be
5323 // emitted by default.
5324 TestResult
& test_result
=
5325 *internal::GetUnitTestImpl()->current_test_result();
5326 for (int j
= 0; j
< test_result
.total_part_count(); ++j
) {
5327 const TestPartResult
& test_part_result
=
5328 test_result
.GetTestPartResult(j
);
5329 if (test_part_result
.type() == TestPartResult::kSkip
) {
5330 const std::string
& result
= test_part_result
.message();
5331 printf("%s\n", result
.c_str());
5335 } else if (!Test::HasFatalFailure()) {
5336 for (int test_index
= 0; test_index
< total_test_suite_count();
5338 GetMutableSuiteCase(test_index
)->Run();
5342 // Tears down all environments in reverse order afterwards.
5343 repeater
->OnEnvironmentsTearDownStart(*parent_
);
5344 std::for_each(environments_
.rbegin(), environments_
.rend(),
5345 TearDownEnvironment
);
5346 repeater
->OnEnvironmentsTearDownEnd(*parent_
);
5349 elapsed_time_
= GetTimeInMillis() - start
;
5351 // Tells the unit test event listener that the tests have just finished.
5352 repeater
->OnTestIterationEnd(*parent_
, i
);
5354 // Gets the result and clears it.
5359 // Restores the original test order after the iteration. This
5360 // allows the user to quickly repro a failure that happens in the
5361 // N-th iteration without repeating the first (N - 1) iterations.
5362 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5363 // case the user somehow changes the value of the flag somewhere
5364 // (it's always safe to unshuffle the tests).
5367 if (GTEST_FLAG(shuffle
)) {
5368 // Picks a new random seed for each iteration.
5369 random_seed_
= GetNextRandomSeed(random_seed_
);
5373 repeater
->OnTestProgramEnd(*parent_
);
5375 if (!gtest_is_initialized_before_run_all_tests
) {
5378 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5379 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5380 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5381 " will start to enforce the valid usage. "
5382 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
5383 #if GTEST_FOR_GOOGLE_
5384 ColoredPrintf(COLOR_RED
,
5385 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5386 #endif // GTEST_FOR_GOOGLE_
5392 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5393 // if the variable is present. If a file already exists at this location, this
5394 // function will write over it. If the variable is present, but the file cannot
5395 // be created, prints an error and exits.
5396 void WriteToShardStatusFileIfNeeded() {
5397 const char* const test_shard_file
= posix::GetEnv(kTestShardStatusFile
);
5398 if (test_shard_file
!= nullptr) {
5399 FILE* const file
= posix::FOpen(test_shard_file
, "w");
5400 if (file
== nullptr) {
5401 ColoredPrintf(COLOR_RED
,
5402 "Could not write to the test shard status file \"%s\" "
5403 "specified by the %s environment variable.\n",
5404 test_shard_file
, kTestShardStatusFile
);
5412 // Checks whether sharding is enabled by examining the relevant
5413 // environment variable values. If the variables are present,
5414 // but inconsistent (i.e., shard_index >= total_shards), prints
5415 // an error and exits. If in_subprocess_for_death_test, sharding is
5416 // disabled because it must only be applied to the original test
5417 // process. Otherwise, we could filter out death tests we intended to execute.
5418 bool ShouldShard(const char* total_shards_env
,
5419 const char* shard_index_env
,
5420 bool in_subprocess_for_death_test
) {
5421 if (in_subprocess_for_death_test
) {
5425 const Int32 total_shards
= Int32FromEnvOrDie(total_shards_env
, -1);
5426 const Int32 shard_index
= Int32FromEnvOrDie(shard_index_env
, -1);
5428 if (total_shards
== -1 && shard_index
== -1) {
5430 } else if (total_shards
== -1 && shard_index
!= -1) {
5431 const Message msg
= Message()
5432 << "Invalid environment variables: you have "
5433 << kTestShardIndex
<< " = " << shard_index
5434 << ", but have left " << kTestTotalShards
<< " unset.\n";
5435 ColoredPrintf(COLOR_RED
, "%s", msg
.GetString().c_str());
5438 } else if (total_shards
!= -1 && shard_index
== -1) {
5439 const Message msg
= Message()
5440 << "Invalid environment variables: you have "
5441 << kTestTotalShards
<< " = " << total_shards
5442 << ", but have left " << kTestShardIndex
<< " unset.\n";
5443 ColoredPrintf(COLOR_RED
, "%s", msg
.GetString().c_str());
5446 } else if (shard_index
< 0 || shard_index
>= total_shards
) {
5447 const Message msg
= Message()
5448 << "Invalid environment variables: we require 0 <= "
5449 << kTestShardIndex
<< " < " << kTestTotalShards
5450 << ", but you have " << kTestShardIndex
<< "=" << shard_index
5451 << ", " << kTestTotalShards
<< "=" << total_shards
<< ".\n";
5452 ColoredPrintf(COLOR_RED
, "%s", msg
.GetString().c_str());
5457 return total_shards
> 1;
5460 // Parses the environment variable var as an Int32. If it is unset,
5461 // returns default_val. If it is not an Int32, prints an error
5463 Int32
Int32FromEnvOrDie(const char* var
, Int32 default_val
) {
5464 const char* str_val
= posix::GetEnv(var
);
5465 if (str_val
== nullptr) {
5470 if (!ParseInt32(Message() << "The value of environment variable " << var
,
5471 str_val
, &result
)) {
5477 // Given the total number of shards, the shard index, and the test id,
5478 // returns true if and only if the test should be run on this shard. The test id
5479 // is some arbitrary but unique non-negative integer assigned to each test
5480 // method. Assumes that 0 <= shard_index < total_shards.
5481 bool ShouldRunTestOnShard(int total_shards
, int shard_index
, int test_id
) {
5482 return (test_id
% total_shards
) == shard_index
;
5485 // Compares the name of each test with the user-specified filter to
5486 // decide whether the test should be run, then records the result in
5487 // each TestSuite and TestInfo object.
5488 // If shard_tests == true, further filters tests based on sharding
5489 // variables in the environment - see
5490 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
5491 // . Returns the number of tests that should run.
5492 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests
) {
5493 const Int32 total_shards
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5494 Int32FromEnvOrDie(kTestTotalShards
, -1) : -1;
5495 const Int32 shard_index
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5496 Int32FromEnvOrDie(kTestShardIndex
, -1) : -1;
5498 // num_runnable_tests are the number of tests that will
5499 // run across all shards (i.e., match filter and are not disabled).
5500 // num_selected_tests are the number of tests to be run on
5502 int num_runnable_tests
= 0;
5503 int num_selected_tests
= 0;
5504 for (auto* test_suite
: test_suites_
) {
5505 const std::string
& test_suite_name
= test_suite
->name();
5506 test_suite
->set_should_run(false);
5508 for (size_t j
= 0; j
< test_suite
->test_info_list().size(); j
++) {
5509 TestInfo
* const test_info
= test_suite
->test_info_list()[j
];
5510 const std::string
test_name(test_info
->name());
5511 // A test is disabled if test suite name or test name matches
5512 // kDisableTestFilter.
5513 const bool is_disabled
= internal::UnitTestOptions::MatchesFilter(
5514 test_suite_name
, kDisableTestFilter
) ||
5515 internal::UnitTestOptions::MatchesFilter(
5516 test_name
, kDisableTestFilter
);
5517 test_info
->is_disabled_
= is_disabled
;
5519 const bool matches_filter
= internal::UnitTestOptions::FilterMatchesTest(
5520 test_suite_name
, test_name
);
5521 test_info
->matches_filter_
= matches_filter
;
5523 const bool is_runnable
=
5524 (GTEST_FLAG(also_run_disabled_tests
) || !is_disabled
) &&
5527 const bool is_in_another_shard
=
5528 shard_tests
!= IGNORE_SHARDING_PROTOCOL
&&
5529 !ShouldRunTestOnShard(total_shards
, shard_index
, num_runnable_tests
);
5530 test_info
->is_in_another_shard_
= is_in_another_shard
;
5531 const bool is_selected
= is_runnable
&& !is_in_another_shard
;
5533 num_runnable_tests
+= is_runnable
;
5534 num_selected_tests
+= is_selected
;
5536 test_info
->should_run_
= is_selected
;
5537 test_suite
->set_should_run(test_suite
->should_run() || is_selected
);
5540 return num_selected_tests
;
5543 // Prints the given C-string on a single line by replacing all '\n'
5544 // characters with string "\\n". If the output takes more than
5545 // max_length characters, only prints the first max_length characters
5547 static void PrintOnOneLine(const char* str
, int max_length
) {
5548 if (str
!= nullptr) {
5549 for (int i
= 0; *str
!= '\0'; ++str
) {
5550 if (i
>= max_length
) {
5565 // Prints the names of the tests matching the user-specified filter flag.
5566 void UnitTestImpl::ListTestsMatchingFilter() {
5567 // Print at most this many characters for each type/value parameter.
5568 const int kMaxParamLength
= 250;
5570 for (auto* test_suite
: test_suites_
) {
5571 bool printed_test_suite_name
= false;
5573 for (size_t j
= 0; j
< test_suite
->test_info_list().size(); j
++) {
5574 const TestInfo
* const test_info
= test_suite
->test_info_list()[j
];
5575 if (test_info
->matches_filter_
) {
5576 if (!printed_test_suite_name
) {
5577 printed_test_suite_name
= true;
5578 printf("%s.", test_suite
->name());
5579 if (test_suite
->type_param() != nullptr) {
5580 printf(" # %s = ", kTypeParamLabel
);
5581 // We print the type parameter on a single line to make
5582 // the output easy to parse by a program.
5583 PrintOnOneLine(test_suite
->type_param(), kMaxParamLength
);
5587 printf(" %s", test_info
->name());
5588 if (test_info
->value_param() != nullptr) {
5589 printf(" # %s = ", kValueParamLabel
);
5590 // We print the value parameter on a single line to make the
5591 // output easy to parse by a program.
5592 PrintOnOneLine(test_info
->value_param(), kMaxParamLength
);
5599 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5600 if (output_format
== "xml" || output_format
== "json") {
5601 FILE* fileout
= OpenFileForWriting(
5602 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
5603 std::stringstream stream
;
5604 if (output_format
== "xml") {
5605 XmlUnitTestResultPrinter(
5606 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5607 .PrintXmlTestsList(&stream
, test_suites_
);
5608 } else if (output_format
== "json") {
5609 JsonUnitTestResultPrinter(
5610 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5611 .PrintJsonTestList(&stream
, test_suites_
);
5613 fprintf(fileout
, "%s", StringStreamToString(&stream
).c_str());
5618 // Sets the OS stack trace getter.
5620 // Does nothing if the input and the current OS stack trace getter are
5621 // the same; otherwise, deletes the old getter and makes the input the
5623 void UnitTestImpl::set_os_stack_trace_getter(
5624 OsStackTraceGetterInterface
* getter
) {
5625 if (os_stack_trace_getter_
!= getter
) {
5626 delete os_stack_trace_getter_
;
5627 os_stack_trace_getter_
= getter
;
5631 // Returns the current OS stack trace getter if it is not NULL;
5632 // otherwise, creates an OsStackTraceGetter, makes it the current
5633 // getter, and returns it.
5634 OsStackTraceGetterInterface
* UnitTestImpl::os_stack_trace_getter() {
5635 if (os_stack_trace_getter_
== nullptr) {
5636 #ifdef GTEST_OS_STACK_TRACE_GETTER_
5637 os_stack_trace_getter_
= new GTEST_OS_STACK_TRACE_GETTER_
;
5639 os_stack_trace_getter_
= new OsStackTraceGetter
;
5640 #endif // GTEST_OS_STACK_TRACE_GETTER_
5643 return os_stack_trace_getter_
;
5646 // Returns the most specific TestResult currently running.
5647 TestResult
* UnitTestImpl::current_test_result() {
5648 if (current_test_info_
!= nullptr) {
5649 return ¤t_test_info_
->result_
;
5651 if (current_test_suite_
!= nullptr) {
5652 return ¤t_test_suite_
->ad_hoc_test_result_
;
5654 return &ad_hoc_test_result_
;
5657 // Shuffles all test suites, and the tests within each test suite,
5658 // making sure that death tests are still run first.
5659 void UnitTestImpl::ShuffleTests() {
5660 // Shuffles the death test suites.
5661 ShuffleRange(random(), 0, last_death_test_suite_
+ 1, &test_suite_indices_
);
5663 // Shuffles the non-death test suites.
5664 ShuffleRange(random(), last_death_test_suite_
+ 1,
5665 static_cast<int>(test_suites_
.size()), &test_suite_indices_
);
5667 // Shuffles the tests inside each test suite.
5668 for (auto& test_suite
: test_suites_
) {
5669 test_suite
->ShuffleTests(random());
5673 // Restores the test suites and tests to their order before the first shuffle.
5674 void UnitTestImpl::UnshuffleTests() {
5675 for (size_t i
= 0; i
< test_suites_
.size(); i
++) {
5676 // Unshuffles the tests in each test suite.
5677 test_suites_
[i
]->UnshuffleTests();
5678 // Resets the index of each test suite.
5679 test_suite_indices_
[i
] = static_cast<int>(i
);
5683 // Returns the current OS stack trace as an std::string.
5685 // The maximum number of stack frames to be included is specified by
5686 // the gtest_stack_trace_depth flag. The skip_count parameter
5687 // specifies the number of top frames to be skipped, which doesn't
5688 // count against the number of frames to be included.
5690 // For example, if Foo() calls Bar(), which in turn calls
5691 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5692 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5693 std::string
GetCurrentOsStackTraceExceptTop(UnitTest
* /*unit_test*/,
5695 // We pass skip_count + 1 to skip this wrapper function in addition
5696 // to what the user really wants to skip.
5697 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count
+ 1);
5700 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5701 // suppress unreachable code warnings.
5703 class ClassUniqueToAlwaysTrue
{};
5706 bool IsTrue(bool condition
) { return condition
; }
5709 #if GTEST_HAS_EXCEPTIONS
5710 // This condition is always false so AlwaysTrue() never actually throws,
5711 // but it makes the compiler think that it may throw.
5713 throw ClassUniqueToAlwaysTrue();
5714 #endif // GTEST_HAS_EXCEPTIONS
5718 // If *pstr starts with the given prefix, modifies *pstr to be right
5719 // past the prefix and returns true; otherwise leaves *pstr unchanged
5720 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5721 bool SkipPrefix(const char* prefix
, const char** pstr
) {
5722 const size_t prefix_len
= strlen(prefix
);
5723 if (strncmp(*pstr
, prefix
, prefix_len
) == 0) {
5724 *pstr
+= prefix_len
;
5730 // Parses a string as a command line flag. The string should have
5731 // the format "--flag=value". When def_optional is true, the "=value"
5732 // part can be omitted.
5734 // Returns the value of the flag, or NULL if the parsing failed.
5735 static const char* ParseFlagValue(const char* str
, const char* flag
,
5736 bool def_optional
) {
5737 // str and flag must not be NULL.
5738 if (str
== nullptr || flag
== nullptr) return nullptr;
5740 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5741 const std::string flag_str
= std::string("--") + GTEST_FLAG_PREFIX_
+ flag
;
5742 const size_t flag_len
= flag_str
.length();
5743 if (strncmp(str
, flag_str
.c_str(), flag_len
) != 0) return nullptr;
5745 // Skips the flag name.
5746 const char* flag_end
= str
+ flag_len
;
5748 // When def_optional is true, it's OK to not have a "=value" part.
5749 if (def_optional
&& (flag_end
[0] == '\0')) {
5753 // If def_optional is true and there are more characters after the
5754 // flag name, or if def_optional is false, there must be a '=' after
5756 if (flag_end
[0] != '=') return nullptr;
5758 // Returns the string after "=".
5759 return flag_end
+ 1;
5762 // Parses a string for a bool flag, in the form of either
5763 // "--flag=value" or "--flag".
5765 // In the former case, the value is taken as true as long as it does
5766 // not start with '0', 'f', or 'F'.
5768 // In the latter case, the value is taken as true.
5770 // On success, stores the value of the flag in *value, and returns
5771 // true. On failure, returns false without changing *value.
5772 static bool ParseBoolFlag(const char* str
, const char* flag
, bool* value
) {
5773 // Gets the value of the flag as a string.
5774 const char* const value_str
= ParseFlagValue(str
, flag
, true);
5776 // Aborts if the parsing failed.
5777 if (value_str
== nullptr) return false;
5779 // Converts the string value to a bool.
5780 *value
= !(*value_str
== '0' || *value_str
== 'f' || *value_str
== 'F');
5784 // Parses a string for an Int32 flag, in the form of
5787 // On success, stores the value of the flag in *value, and returns
5788 // true. On failure, returns false without changing *value.
5789 bool ParseInt32Flag(const char* str
, const char* flag
, Int32
* value
) {
5790 // Gets the value of the flag as a string.
5791 const char* const value_str
= ParseFlagValue(str
, flag
, false);
5793 // Aborts if the parsing failed.
5794 if (value_str
== nullptr) return false;
5796 // Sets *value to the value of the flag.
5797 return ParseInt32(Message() << "The value of flag --" << flag
,
5801 // Parses a string for a string flag, in the form of
5804 // On success, stores the value of the flag in *value, and returns
5805 // true. On failure, returns false without changing *value.
5806 template <typename String
>
5807 static bool ParseStringFlag(const char* str
, const char* flag
, String
* value
) {
5808 // Gets the value of the flag as a string.
5809 const char* const value_str
= ParseFlagValue(str
, flag
, false);
5811 // Aborts if the parsing failed.
5812 if (value_str
== nullptr) return false;
5814 // Sets *value to the value of the flag.
5819 // Determines whether a string has a prefix that Google Test uses for its
5820 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5821 // If Google Test detects that a command line flag has its prefix but is not
5822 // recognized, it will print its help message. Flags starting with
5823 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5824 // internal flags and do not trigger the help message.
5825 static bool HasGoogleTestFlagPrefix(const char* str
) {
5826 return (SkipPrefix("--", &str
) ||
5827 SkipPrefix("-", &str
) ||
5828 SkipPrefix("/", &str
)) &&
5829 !SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str
) &&
5830 (SkipPrefix(GTEST_FLAG_PREFIX_
, &str
) ||
5831 SkipPrefix(GTEST_FLAG_PREFIX_DASH_
, &str
));
5834 // Prints a string containing code-encoded text. The following escape
5835 // sequences can be used in the string to control the text color:
5837 // @@ prints a single '@' character.
5838 // @R changes the color to red.
5839 // @G changes the color to green.
5840 // @Y changes the color to yellow.
5841 // @D changes to the default terminal text color.
5843 static void PrintColorEncoded(const char* str
) {
5844 GTestColor color
= COLOR_DEFAULT
; // The current color.
5846 // Conceptually, we split the string into segments divided by escape
5847 // sequences. Then we print one segment at a time. At the end of
5848 // each iteration, the str pointer advances to the beginning of the
5851 const char* p
= strchr(str
, '@');
5853 ColoredPrintf(color
, "%s", str
);
5857 ColoredPrintf(color
, "%s", std::string(str
, p
).c_str());
5859 const char ch
= p
[1];
5862 ColoredPrintf(color
, "@");
5863 } else if (ch
== 'D') {
5864 color
= COLOR_DEFAULT
;
5865 } else if (ch
== 'R') {
5867 } else if (ch
== 'G') {
5868 color
= COLOR_GREEN
;
5869 } else if (ch
== 'Y') {
5870 color
= COLOR_YELLOW
;
5877 static const char kColorEncodedHelpMessage
[] =
5878 "This program contains tests written using " GTEST_NAME_
". You can use the\n"
5879 "following command line flags to control its behavior:\n"
5882 " @G--" GTEST_FLAG_PREFIX_
"list_tests@D\n"
5883 " List the names of all tests instead of running them. The name of\n"
5884 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
5885 " @G--" GTEST_FLAG_PREFIX_
"filter=@YPOSTIVE_PATTERNS"
5886 "[@G-@YNEGATIVE_PATTERNS]@D\n"
5887 " Run only the tests whose name matches one of the positive patterns but\n"
5888 " none of the negative patterns. '?' matches any single character; '*'\n"
5889 " matches any substring; ':' separates two patterns.\n"
5890 " @G--" GTEST_FLAG_PREFIX_
"also_run_disabled_tests@D\n"
5891 " Run all disabled tests too.\n"
5894 " @G--" GTEST_FLAG_PREFIX_
"repeat=@Y[COUNT]@D\n"
5895 " Run the tests repeatedly; use a negative count to repeat forever.\n"
5896 " @G--" GTEST_FLAG_PREFIX_
"shuffle@D\n"
5897 " Randomize tests' orders on every iteration.\n"
5898 " @G--" GTEST_FLAG_PREFIX_
"random_seed=@Y[NUMBER]@D\n"
5899 " Random number seed to use for shuffling test orders (between 1 and\n"
5900 " 99999, or 0 to use a seed based on the current time).\n"
5903 " @G--" GTEST_FLAG_PREFIX_
"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5904 " Enable/disable colored output. The default is @Gauto@D.\n"
5905 " -@G-" GTEST_FLAG_PREFIX_
"print_time=0@D\n"
5906 " Don't print the elapsed time of each test.\n"
5907 " @G--" GTEST_FLAG_PREFIX_
"output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
5908 GTEST_PATH_SEP_
"@Y|@G:@YFILE_PATH]@D\n"
5909 " Generate a JSON or XML report in the given directory or with the given\n"
5910 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
5911 # if GTEST_CAN_STREAM_RESULTS_
5912 " @G--" GTEST_FLAG_PREFIX_
"stream_result_to=@YHOST@G:@YPORT@D\n"
5913 " Stream test results to the given server.\n"
5914 # endif // GTEST_CAN_STREAM_RESULTS_
5916 "Assertion Behavior:\n"
5917 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5918 " @G--" GTEST_FLAG_PREFIX_
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5919 " Set the default death test style.\n"
5920 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5921 " @G--" GTEST_FLAG_PREFIX_
"break_on_failure@D\n"
5922 " Turn assertion failures into debugger break-points.\n"
5923 " @G--" GTEST_FLAG_PREFIX_
"throw_on_failure@D\n"
5924 " Turn assertion failures into C++ exceptions for use by an external\n"
5925 " test framework.\n"
5926 " @G--" GTEST_FLAG_PREFIX_
"catch_exceptions=0@D\n"
5927 " Do not report exceptions as test failures. Instead, allow them\n"
5928 " to crash the program or throw a pop-up (on Windows).\n"
5930 "Except for @G--" GTEST_FLAG_PREFIX_
"list_tests@D, you can alternatively set "
5931 "the corresponding\n"
5932 "environment variable of a flag (all letters in upper-case). For example, to\n"
5933 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5934 "color=no@D or set\n"
5935 "the @G" GTEST_FLAG_PREFIX_UPPER_
"COLOR@D environment variable to @Gno@D.\n"
5937 "For more information, please read the " GTEST_NAME_
" documentation at\n"
5938 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
"\n"
5939 "(not one in your own code or tests), please report it to\n"
5940 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
5942 static bool ParseGoogleTestFlag(const char* const arg
) {
5943 return ParseBoolFlag(arg
, kAlsoRunDisabledTestsFlag
,
5944 >EST_FLAG(also_run_disabled_tests
)) ||
5945 ParseBoolFlag(arg
, kBreakOnFailureFlag
,
5946 >EST_FLAG(break_on_failure
)) ||
5947 ParseBoolFlag(arg
, kCatchExceptionsFlag
,
5948 >EST_FLAG(catch_exceptions
)) ||
5949 ParseStringFlag(arg
, kColorFlag
, >EST_FLAG(color
)) ||
5950 ParseStringFlag(arg
, kDeathTestStyleFlag
,
5951 >EST_FLAG(death_test_style
)) ||
5952 ParseBoolFlag(arg
, kDeathTestUseFork
,
5953 >EST_FLAG(death_test_use_fork
)) ||
5954 ParseStringFlag(arg
, kFilterFlag
, >EST_FLAG(filter
)) ||
5955 ParseStringFlag(arg
, kInternalRunDeathTestFlag
,
5956 >EST_FLAG(internal_run_death_test
)) ||
5957 ParseBoolFlag(arg
, kListTestsFlag
, >EST_FLAG(list_tests
)) ||
5958 ParseStringFlag(arg
, kOutputFlag
, >EST_FLAG(output
)) ||
5959 ParseBoolFlag(arg
, kPrintTimeFlag
, >EST_FLAG(print_time
)) ||
5960 ParseBoolFlag(arg
, kPrintUTF8Flag
, >EST_FLAG(print_utf8
)) ||
5961 ParseInt32Flag(arg
, kRandomSeedFlag
, >EST_FLAG(random_seed
)) ||
5962 ParseInt32Flag(arg
, kRepeatFlag
, >EST_FLAG(repeat
)) ||
5963 ParseBoolFlag(arg
, kShuffleFlag
, >EST_FLAG(shuffle
)) ||
5964 ParseInt32Flag(arg
, kStackTraceDepthFlag
,
5965 >EST_FLAG(stack_trace_depth
)) ||
5966 ParseStringFlag(arg
, kStreamResultToFlag
,
5967 >EST_FLAG(stream_result_to
)) ||
5968 ParseBoolFlag(arg
, kThrowOnFailureFlag
,
5969 >EST_FLAG(throw_on_failure
));
5972 #if GTEST_USE_OWN_FLAGFILE_FLAG_
5973 static void LoadFlagsFromFile(const std::string
& path
) {
5974 FILE* flagfile
= posix::FOpen(path
.c_str(), "r");
5976 GTEST_LOG_(FATAL
) << "Unable to open file \"" << GTEST_FLAG(flagfile
)
5979 std::string
contents(ReadEntireFile(flagfile
));
5980 posix::FClose(flagfile
);
5981 std::vector
<std::string
> lines
;
5982 SplitString(contents
, '\n', &lines
);
5983 for (size_t i
= 0; i
< lines
.size(); ++i
) {
5984 if (lines
[i
].empty())
5986 if (!ParseGoogleTestFlag(lines
[i
].c_str()))
5990 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
5992 // Parses the command line for Google Test flags, without initializing
5993 // other parts of Google Test. The type parameter CharType can be
5994 // instantiated to either char or wchar_t.
5995 template <typename CharType
>
5996 void ParseGoogleTestFlagsOnlyImpl(int* argc
, CharType
** argv
) {
5997 for (int i
= 1; i
< *argc
; i
++) {
5998 const std::string arg_string
= StreamableToString(argv
[i
]);
5999 const char* const arg
= arg_string
.c_str();
6001 using internal::ParseBoolFlag
;
6002 using internal::ParseInt32Flag
;
6003 using internal::ParseStringFlag
;
6005 bool remove_flag
= false;
6006 if (ParseGoogleTestFlag(arg
)) {
6008 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6009 } else if (ParseStringFlag(arg
, kFlagfileFlag
, >EST_FLAG(flagfile
))) {
6010 LoadFlagsFromFile(GTEST_FLAG(flagfile
));
6012 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6013 } else if (arg_string
== "--help" || arg_string
== "-h" ||
6014 arg_string
== "-?" || arg_string
== "/?" ||
6015 HasGoogleTestFlagPrefix(arg
)) {
6016 // Both help flag and unrecognized Google Test flags (excluding
6017 // internal ones) trigger help display.
6022 // Shift the remainder of the argv list left by one. Note
6023 // that argv has (*argc + 1) elements, the last one always being
6024 // NULL. The following loop moves the trailing NULL element as
6026 for (int j
= i
; j
!= *argc
; j
++) {
6027 argv
[j
] = argv
[j
+ 1];
6030 // Decrements the argument count.
6033 // We also need to decrement the iterator as we just removed
6040 // We print the help here instead of in RUN_ALL_TESTS(), as the
6041 // latter may not be called at all if the user is using Google
6042 // Test with another testing framework.
6043 PrintColorEncoded(kColorEncodedHelpMessage
);
6047 // Parses the command line for Google Test flags, without initializing
6048 // other parts of Google Test.
6049 void ParseGoogleTestFlagsOnly(int* argc
, char** argv
) {
6050 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6052 // Fix the value of *_NSGetArgc() on macOS, but if and only if
6053 // *_NSGetArgv() == argv
6054 // Only applicable to char** version of argv
6056 #ifndef GTEST_OS_IOS
6057 if (*_NSGetArgv() == argv
) {
6058 *_NSGetArgc() = *argc
;
6063 void ParseGoogleTestFlagsOnly(int* argc
, wchar_t** argv
) {
6064 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6067 // The internal implementation of InitGoogleTest().
6069 // The type parameter CharType can be instantiated to either char or
6071 template <typename CharType
>
6072 void InitGoogleTestImpl(int* argc
, CharType
** argv
) {
6073 // We don't want to run the initialization code twice.
6074 if (GTestIsInitialized()) return;
6076 if (*argc
<= 0) return;
6079 for (int i
= 0; i
!= *argc
; i
++) {
6080 g_argvs
.push_back(StreamableToString(argv
[i
]));
6084 absl::InitializeSymbolizer(g_argvs
[0].c_str());
6085 #endif // GTEST_HAS_ABSL
6087 ParseGoogleTestFlagsOnly(argc
, argv
);
6088 GetUnitTestImpl()->PostFlagParsingInit();
6091 } // namespace internal
6093 // Initializes Google Test. This must be called before calling
6094 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6095 // flags that Google Test recognizes. Whenever a Google Test flag is
6096 // seen, it is removed from argv, and *argc is decremented.
6098 // No value is returned. Instead, the Google Test flag variables are
6101 // Calling the function for the second time has no user-visible effect.
6102 void InitGoogleTest(int* argc
, char** argv
) {
6103 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6104 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc
, argv
);
6105 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6106 internal::InitGoogleTestImpl(argc
, argv
);
6107 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6110 // This overloaded version can be used in Windows programs compiled in
6112 void InitGoogleTest(int* argc
, wchar_t** argv
) {
6113 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6114 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc
, argv
);
6115 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6116 internal::InitGoogleTestImpl(argc
, argv
);
6117 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6120 // This overloaded version can be used on Arduino/embedded platforms where
6121 // there is no argc/argv.
6122 void InitGoogleTest() {
6123 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
6125 const auto arg0
= "dummy";
6126 char* argv0
= const_cast<char*>(arg0
);
6127 char** argv
= &argv0
;
6129 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6130 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc
, argv
);
6131 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6132 internal::InitGoogleTestImpl(&argc
, argv
);
6133 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6136 std::string
TempDir() {
6137 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6138 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6141 #if GTEST_OS_WINDOWS_MOBILE
6143 #elif GTEST_OS_WINDOWS
6144 const char* temp_dir
= internal::posix::GetEnv("TEMP");
6145 if (temp_dir
== nullptr || temp_dir
[0] == '\0')
6147 else if (temp_dir
[strlen(temp_dir
) - 1] == '\\')
6150 return std::string(temp_dir
) + "\\";
6151 #elif GTEST_OS_LINUX_ANDROID
6155 #endif // GTEST_OS_WINDOWS_MOBILE
6158 // Class ScopedTrace
6160 // Pushes the given source file location and message onto a per-thread
6161 // trace stack maintained by Google Test.
6162 void ScopedTrace::PushTrace(const char* file
, int line
, std::string message
) {
6163 internal::TraceInfo trace
;
6166 trace
.message
.swap(message
);
6168 UnitTest::GetInstance()->PushGTestTrace(trace
);
6171 // Pops the info pushed by the c'tor.
6172 ScopedTrace::~ScopedTrace()
6173 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
6174 UnitTest::GetInstance()->PopGTestTrace();
6177 } // namespace testing