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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // The Google C++ Testing Framework (Google Test)
34 #include <gtest/gtest.h>
35 #include <gtest/gtest-spi.h>
52 // TODO(kenton@google.com): Use autoconf to detect availability of
54 #define GTEST_HAS_GETTIMEOFDAY_ 1
59 // Declares vsnprintf(). This header is not available on Windows.
67 #elif GTEST_OS_SYMBIAN
68 #define GTEST_HAS_GETTIMEOFDAY_ 1
69 #include <sys/time.h> // NOLINT
72 #define GTEST_HAS_GETTIMEOFDAY_ 1
73 #include <sys/time.h> // NOLINT
75 // On z/OS we additionally need strings.h for strcasecmp.
76 #include <strings.h> // NOLINT
78 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
80 #include <windows.h> // NOLINT
82 #elif GTEST_OS_WINDOWS // We are on Windows proper.
84 #include <io.h> // NOLINT
85 #include <sys/timeb.h> // NOLINT
86 #include <sys/types.h> // NOLINT
87 #include <sys/stat.h> // NOLINT
89 #if GTEST_OS_WINDOWS_MINGW
90 // MinGW has gettimeofday() but not _ftime64().
91 // TODO(kenton@google.com): Use autoconf to detect availability of
93 // TODO(kenton@google.com): There are other ways to get the time on
94 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
95 // supports these. consider using them instead.
96 #define GTEST_HAS_GETTIMEOFDAY_ 1
97 #include <sys/time.h> // NOLINT
98 #endif // GTEST_OS_WINDOWS_MINGW
100 // cpplint thinks that the header is already included, so we want to
102 #include <windows.h> // NOLINT
106 // Assume other platforms have gettimeofday().
107 // TODO(kenton@google.com): Use autoconf to detect availability of
109 #define GTEST_HAS_GETTIMEOFDAY_ 1
111 // cpplint thinks that the header is already included, so we want to
113 #include <sys/time.h> // NOLINT
114 #include <unistd.h> // NOLINT
116 #endif // GTEST_OS_LINUX
118 #if GTEST_HAS_EXCEPTIONS
122 // Indicates that this translation unit is part of Google Test's
123 // implementation. It must come before gtest-internal-inl.h is
124 // included, or there will be a compiler error. This trick is to
125 // prevent a user from accidentally including gtest-internal-inl.h in
127 #define GTEST_IMPLEMENTATION_ 1
128 #include "gtest/internal/gtest-internal-inl.h"
129 #undef GTEST_IMPLEMENTATION_
132 #define vsnprintf _vsnprintf
133 #endif // GTEST_OS_WINDOWS
137 using internal::CountIf;
138 using internal::ForEach;
139 using internal::GetElementOr;
140 using internal::Shuffle;
144 // A test whose test case name or test name matches this filter is
145 // disabled and not run.
146 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
148 // A test case whose name matches this filter is considered a death
149 // test case and will be run before test cases whose name doesn't
150 // match this filter.
151 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
153 // A test filter that matches everything.
154 static const char kUniversalFilter[] = "*";
156 // The default output file for XML output.
157 static const char kDefaultOutputFile[] = "test_detail.xml";
159 // The environment variable name for the test shard index.
160 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
161 // The environment variable name for the total number of test shards.
162 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
163 // The environment variable name for the test shard status file.
164 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
168 // The text used in failure messages to indicate the start of the
170 const char kStackTraceMarker[] = "\nStack trace:\n";
172 // g_help_flag is true iff the --help flag or an equivalent form is
173 // specified on the command line.
174 bool g_help_flag = false;
176 } // namespace internal
179 also_run_disabled_tests,
180 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
181 "Run disabled tests too, in addition to the tests normally being run.");
185 internal::BoolFromGTestEnv("break_on_failure", false),
186 "True iff a failed assertion should be a debugger break-point.");
190 internal::BoolFromGTestEnv("catch_exceptions", false),
191 "True iff " GTEST_NAME_
192 " should catch exceptions and treat them as test failures.");
194 GTEST_DEFINE_string_(
196 internal::StringFromGTestEnv("color", "auto"),
197 "Whether to use colors in the output. Valid values: yes, no, "
198 "and auto. 'auto' means to use colors if the output is "
199 "being sent to a terminal and the TERM environment variable "
200 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
202 GTEST_DEFINE_string_(
204 internal::StringFromGTestEnv("filter", kUniversalFilter),
205 "A colon-separated list of glob (not regex) patterns "
206 "for filtering the tests to run, optionally followed by a "
207 "'-' and a : separated list of negative patterns (tests to "
208 "exclude). A test is run if it matches one of the positive "
209 "patterns and does not match any of the negative patterns.");
211 GTEST_DEFINE_bool_(list_tests, false,
212 "List all tests without running them.");
214 GTEST_DEFINE_string_(
216 internal::StringFromGTestEnv("output", ""),
217 "A format (currently must be \"xml\"), optionally followed "
218 "by a colon and an output file name or directory. A directory "
219 "is indicated by a trailing pathname separator. "
220 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
221 "If a directory is specified, output files will be created "
222 "within that directory, with file-names based on the test "
223 "executable's name and, if necessary, made unique by adding "
228 internal::BoolFromGTestEnv("print_time", true),
229 "True iff " GTEST_NAME_
230 " should display elapsed time in text output.");
234 internal::Int32FromGTestEnv("random_seed", 0),
235 "Random number seed to use when shuffling test orders. Must be in range "
236 "[1, 99999], or 0 to use a seed based on the current time.");
240 internal::Int32FromGTestEnv("repeat", 1),
241 "How many times to repeat each test. Specify a negative number "
242 "for repeating forever. Useful for shaking out flaky tests.");
245 show_internal_stack_frames, false,
246 "True iff " GTEST_NAME_ " should include internal stack frames when "
247 "printing test failure stack traces.");
251 internal::BoolFromGTestEnv("shuffle", false),
252 "True iff " GTEST_NAME_
253 " should randomize tests' order on every run.");
257 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
258 "The maximum number of stack frames to print when an "
259 "assertion fails. The valid range is 0 through 100, inclusive.");
263 internal::BoolFromGTestEnv("throw_on_failure", false),
264 "When this flag is specified, a failed assertion will throw an exception "
265 "if exceptions are enabled or exit the program with a non-zero code "
270 // Generates a random number from [0, range), using a Linear
271 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
273 UInt32 Random::Generate(UInt32 range) {
274 // These constants are the same as are used in glibc's rand(3).
275 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
277 GTEST_CHECK_(range > 0)
278 << "Cannot generate a number in the range [0, 0).";
279 GTEST_CHECK_(range <= kMaxRange)
280 << "Generation of a number in [0, " << range << ") was requested, "
281 << "but this can only generate numbers in [0, " << kMaxRange << ").";
283 // Converting via modulus introduces a bit of downward bias, but
284 // it's simple, and a linear congruential generator isn't too good
286 return state_ % range;
289 // GTestIsInitialized() returns true iff the user has initialized
290 // Google Test. Useful for catching the user mistake of not initializing
291 // Google Test before calling RUN_ALL_TESTS().
293 // A user must call testing::InitGoogleTest() to initialize Google
294 // Test. g_init_gtest_count is set to the number of times
295 // InitGoogleTest() has been called. We don't protect this variable
296 // under a mutex as it is only accessed in the main thread.
297 int g_init_gtest_count = 0;
298 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
300 // Iterates over a vector of TestCases, keeping a running sum of the
301 // results of calling a given int-returning method on each.
303 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
304 int (TestCase::*method)() const) {
306 for (size_t i = 0; i < case_list.size(); i++) {
307 sum += (case_list[i]->*method)();
312 // Returns true iff the test case passed.
313 static bool TestCasePassed(const TestCase* test_case) {
314 return test_case->should_run() && test_case->Passed();
317 // Returns true iff the test case failed.
318 static bool TestCaseFailed(const TestCase* test_case) {
319 return test_case->should_run() && test_case->Failed();
322 // Returns true iff test_case contains at least one test that should
324 static bool ShouldRunTestCase(const TestCase* test_case) {
325 return test_case->should_run();
328 // AssertHelper constructor.
329 AssertHelper::AssertHelper(TestPartResult::Type type,
333 : data_(new AssertHelperData(type, file, line, message)) {
336 AssertHelper::~AssertHelper() {
340 // Message assignment, for assertion streaming support.
341 void AssertHelper::operator=(const Message& message) const {
342 UnitTest::GetInstance()->
343 AddTestPartResult(data_->type, data_->file, data_->line,
344 AppendUserMessage(data_->message, message),
345 UnitTest::GetInstance()->impl()
346 ->CurrentOsStackTraceExceptTop(1)
347 // Skips the stack frame for this function itself.
351 // Mutex for linked pointers.
352 GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
354 // Application pathname gotten in InitGoogleTest.
355 String g_executable_path;
357 // Returns the current application's name, removing directory path if that
359 FilePath GetCurrentExecutableName() {
363 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
365 result.Set(FilePath(g_executable_path));
366 #endif // GTEST_OS_WINDOWS
368 return result.RemoveDirectoryName();
371 // Functions for processing the gtest_output flag.
373 // Returns the output format, or "" for normal printed output.
374 String UnitTestOptions::GetOutputFormat() {
375 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
376 if (gtest_output_flag == NULL) return String("");
378 const char* const colon = strchr(gtest_output_flag, ':');
379 return (colon == NULL) ?
380 String(gtest_output_flag) :
381 String(gtest_output_flag, colon - gtest_output_flag);
384 // Returns the name of the requested output file, or the default if none
385 // was explicitly specified.
386 String UnitTestOptions::GetAbsolutePathToOutputFile() {
387 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
388 if (gtest_output_flag == NULL)
391 const char* const colon = strchr(gtest_output_flag, ':');
393 return String(internal::FilePath::ConcatPaths(
395 UnitTest::GetInstance()->original_working_dir()),
396 internal::FilePath(kDefaultOutputFile)).ToString() );
398 internal::FilePath output_name(colon + 1);
399 if (!output_name.IsAbsolutePath())
400 // TODO(wan@google.com): on Windows \some\path is not an absolute
401 // path (as its meaning depends on the current drive), yet the
402 // following logic for turning it into an absolute path is wrong.
404 output_name = internal::FilePath::ConcatPaths(
405 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
406 internal::FilePath(colon + 1));
408 if (!output_name.IsDirectory())
409 return output_name.ToString();
411 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
412 output_name, internal::GetCurrentExecutableName(),
413 GetOutputFormat().c_str()));
414 return result.ToString();
417 // Returns true iff the wildcard pattern matches the string. The
418 // first ':' or '\0' character in pattern marks the end of it.
420 // This recursive algorithm isn't very efficient, but is clear and
421 // works well enough for matching test names, which are short.
422 bool UnitTestOptions::PatternMatchesString(const char *pattern,
426 case ':': // Either ':' or '\0' marks the end of the pattern.
428 case '?': // Matches any single character.
429 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
430 case '*': // Matches any string (possibly empty) of characters.
431 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
432 PatternMatchesString(pattern + 1, str);
433 default: // Non-special character. Matches itself.
434 return *pattern == *str &&
435 PatternMatchesString(pattern + 1, str + 1);
439 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
440 const char *cur_pattern = filter;
442 if (PatternMatchesString(cur_pattern, name.c_str())) {
446 // Finds the next pattern in the filter.
447 cur_pattern = strchr(cur_pattern, ':');
449 // Returns if no more pattern can be found.
450 if (cur_pattern == NULL) {
454 // Skips the pattern separater (the ':' character).
459 // TODO(keithray): move String function implementations to gtest-string.cc.
461 // Returns true iff the user-specified filter matches the test case
462 // name and the test name.
463 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
464 const String &test_name) {
465 const String& full_name = String::Format("%s.%s",
466 test_case_name.c_str(),
469 // Split --gtest_filter at '-', if there is one, to separate into
470 // positive filter and negative filter portions
471 const char* const p = GTEST_FLAG(filter).c_str();
472 const char* const dash = strchr(p, '-');
476 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
477 negative = String("");
479 positive = String(p, dash - p); // Everything up to the dash
480 negative = String(dash+1); // Everything after the dash
481 if (positive.empty()) {
482 // Treat '-test1' as the same as '*-test1'
483 positive = kUniversalFilter;
487 // A filter is a colon-separated list of patterns. It matches a
488 // test if any pattern in it matches the test.
489 return (MatchesFilter(full_name, positive.c_str()) &&
490 !MatchesFilter(full_name, negative.c_str()));
494 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
495 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
496 // This function is useful as an __except condition.
497 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
498 // Google Test should handle an exception if:
499 // 1. the user wants it to, AND
500 // 2. this is not a breakpoint exception.
501 return (GTEST_FLAG(catch_exceptions) &&
502 exception_code != EXCEPTION_BREAKPOINT) ?
503 EXCEPTION_EXECUTE_HANDLER :
504 EXCEPTION_CONTINUE_SEARCH;
506 #endif // GTEST_OS_WINDOWS
508 } // namespace internal
510 // The c'tor sets this object as the test part result reporter used by
511 // Google Test. The 'result' parameter specifies where to report the
512 // results. Intercepts only failures from the current thread.
513 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
514 TestPartResultArray* result)
515 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
520 // The c'tor sets this object as the test part result reporter used by
521 // Google Test. The 'result' parameter specifies where to report the
523 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
524 InterceptMode intercept_mode, TestPartResultArray* result)
525 : intercept_mode_(intercept_mode),
530 void ScopedFakeTestPartResultReporter::Init() {
531 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
532 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
533 old_reporter_ = impl->GetGlobalTestPartResultReporter();
534 impl->SetGlobalTestPartResultReporter(this);
536 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
537 impl->SetTestPartResultReporterForCurrentThread(this);
541 // The d'tor restores the test part result reporter used by Google Test
543 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
544 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
545 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
546 impl->SetGlobalTestPartResultReporter(old_reporter_);
548 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
552 // Increments the test part result count and remembers the result.
553 // This method is from the TestPartResultReporterInterface interface.
554 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
555 const TestPartResult& result) {
556 result_->Append(result);
561 // Returns the type ID of ::testing::Test. We should always call this
562 // instead of GetTypeId< ::testing::Test>() to get the type ID of
563 // testing::Test. This is to work around a suspected linker bug when
564 // using Google Test as a framework on Mac OS X. The bug causes
565 // GetTypeId< ::testing::Test>() to return different values depending
566 // on whether the call is from the Google Test framework itself or
567 // from user test code. GetTestTypeId() is guaranteed to always
568 // return the same value, as it always calls GetTypeId<>() from the
569 // gtest.cc, which is within the Google Test framework.
570 TypeId GetTestTypeId() {
571 return GetTypeId<Test>();
574 // The value of GetTestTypeId() as seen from within the Google Test
575 // library. This is solely for testing GetTestTypeId().
576 const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
578 // This predicate-formatter checks that 'results' contains a test part
579 // failure of the given type and that the failure message contains the
581 AssertionResult HasOneFailure(const char* /* results_expr */,
582 const char* /* type_expr */,
583 const char* /* substr_expr */,
584 const TestPartResultArray& results,
585 TestPartResult::Type type,
586 const char* substr) {
587 const String expected(type == TestPartResult::kFatalFailure ?
589 "1 non-fatal failure");
591 if (results.size() != 1) {
592 msg << "Expected: " << expected << "\n"
593 << " Actual: " << results.size() << " failures";
594 for (int i = 0; i < results.size(); i++) {
595 msg << "\n" << results.GetTestPartResult(i);
597 return AssertionFailure(msg);
600 const TestPartResult& r = results.GetTestPartResult(0);
601 if (r.type() != type) {
602 msg << "Expected: " << expected << "\n"
605 return AssertionFailure(msg);
608 if (strstr(r.message(), substr) == NULL) {
609 msg << "Expected: " << expected << " containing \""
613 return AssertionFailure(msg);
616 return AssertionSuccess();
619 // The constructor of SingleFailureChecker remembers where to look up
620 // test part results, what type of failure we expect, and what
621 // substring the failure message should contain.
622 SingleFailureChecker:: SingleFailureChecker(
623 const TestPartResultArray* results,
624 TestPartResult::Type type,
630 // The destructor of SingleFailureChecker verifies that the given
631 // TestPartResultArray contains exactly one failure that has the given
632 // type and contains the given substring. If that's not the case, a
633 // non-fatal failure will be generated.
634 SingleFailureChecker::~SingleFailureChecker() {
635 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
638 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
639 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
641 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
642 const TestPartResult& result) {
643 unit_test_->current_test_result()->AddTestPartResult(result);
644 unit_test_->listeners()->repeater()->OnTestPartResult(result);
647 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
648 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
650 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
651 const TestPartResult& result) {
652 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
655 // Returns the global test part result reporter.
656 TestPartResultReporterInterface*
657 UnitTestImpl::GetGlobalTestPartResultReporter() {
658 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
659 return global_test_part_result_repoter_;
662 // Sets the global test part result reporter.
663 void UnitTestImpl::SetGlobalTestPartResultReporter(
664 TestPartResultReporterInterface* reporter) {
665 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
666 global_test_part_result_repoter_ = reporter;
669 // Returns the test part result reporter for the current thread.
670 TestPartResultReporterInterface*
671 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
672 return per_thread_test_part_result_reporter_.get();
675 // Sets the test part result reporter for the current thread.
676 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
677 TestPartResultReporterInterface* reporter) {
678 per_thread_test_part_result_reporter_.set(reporter);
681 // Gets the number of successful test cases.
682 int UnitTestImpl::successful_test_case_count() const {
683 return CountIf(test_cases_, TestCasePassed);
686 // Gets the number of failed test cases.
687 int UnitTestImpl::failed_test_case_count() const {
688 return CountIf(test_cases_, TestCaseFailed);
691 // Gets the number of all test cases.
692 int UnitTestImpl::total_test_case_count() const {
693 return static_cast<int>(test_cases_.size());
696 // Gets the number of all test cases that contain at least one test
698 int UnitTestImpl::test_case_to_run_count() const {
699 return CountIf(test_cases_, ShouldRunTestCase);
702 // Gets the number of successful tests.
703 int UnitTestImpl::successful_test_count() const {
704 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
707 // Gets the number of failed tests.
708 int UnitTestImpl::failed_test_count() const {
709 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
712 // Gets the number of disabled tests.
713 int UnitTestImpl::disabled_test_count() const {
714 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
717 // Gets the number of all tests.
718 int UnitTestImpl::total_test_count() const {
719 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
722 // Gets the number of tests that should run.
723 int UnitTestImpl::test_to_run_count() const {
724 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
727 // Returns the current OS stack trace as a String.
729 // The maximum number of stack frames to be included is specified by
730 // the gtest_stack_trace_depth flag. The skip_count parameter
731 // specifies the number of top frames to be skipped, which doesn't
732 // count against the number of frames to be included.
734 // For example, if Foo() calls Bar(), which in turn calls
735 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
736 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
737 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
742 // Returns the current time in milliseconds.
743 TimeInMillis GetTimeInMillis() {
744 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
745 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
746 // http://analogous.blogspot.com/2005/04/epoch.html
747 const TimeInMillis kJavaEpochToWinFileTimeDelta =
748 static_cast<TimeInMillis>(116444736UL) * 100000UL;
749 const DWORD kTenthMicrosInMilliSecond = 10000;
751 SYSTEMTIME now_systime;
752 FILETIME now_filetime;
753 ULARGE_INTEGER now_int64;
754 // TODO(kenton@google.com): Shouldn't this just use
755 // GetSystemTimeAsFileTime()?
756 GetSystemTime(&now_systime);
757 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
758 now_int64.LowPart = now_filetime.dwLowDateTime;
759 now_int64.HighPart = now_filetime.dwHighDateTime;
760 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
761 kJavaEpochToWinFileTimeDelta;
762 return now_int64.QuadPart;
765 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
768 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
769 // (deprecated function) there.
770 // TODO(kenton@google.com): Use GetTickCount()? Or use
771 // SystemTimeToFileTime()
772 #pragma warning(push) // Saves the current warning state.
773 #pragma warning(disable:4996) // Temporarily disables warning 4996.
775 #pragma warning(pop) // Restores the warning state.
779 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
780 #elif GTEST_HAS_GETTIMEOFDAY_
782 gettimeofday(&now, NULL);
783 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
785 #error "Don't know how to get the current time on your system."
793 // Returns the input enclosed in double quotes if it's not NULL;
794 // otherwise returns "(null)". For example, "\"Hello\"" is returned
795 // for input "Hello".
797 // This is useful for printing a C string in the syntax of a literal.
799 // Known issue: escape sequences are not handled yet.
800 String String::ShowCStringQuoted(const char* c_str) {
801 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
804 // Copies at most length characters from str into a newly-allocated
805 // piece of memory of size length+1. The memory is allocated with new[].
806 // A terminating null byte is written to the memory, and a pointer to it
807 // is returned. If str is NULL, NULL is returned.
808 static char* CloneString(const char* str, size_t length) {
812 char* const clone = new char[length + 1];
813 posix::StrNCpy(clone, str, length);
814 clone[length] = '\0';
819 // Clones a 0-terminated C string, allocating memory using new. The
820 // caller is responsible for deleting[] the return value. Returns the
821 // cloned string, or NULL if the input is NULL.
822 const char * String::CloneCString(const char* c_str) {
823 return (c_str == NULL) ?
824 NULL : CloneString(c_str, strlen(c_str));
827 #if GTEST_OS_WINDOWS_MOBILE
828 // Creates a UTF-16 wide string from the given ANSI string, allocating
829 // memory using new. The caller is responsible for deleting the return
830 // value using delete[]. Returns the wide string, or NULL if the
832 LPCWSTR String::AnsiToUtf16(const char* ansi) {
833 if (!ansi) return NULL;
834 const int length = strlen(ansi);
835 const int unicode_length =
836 MultiByteToWideChar(CP_ACP, 0, ansi, length,
838 WCHAR* unicode = new WCHAR[unicode_length + 1];
839 MultiByteToWideChar(CP_ACP, 0, ansi, length,
840 unicode, unicode_length);
841 unicode[unicode_length] = 0;
845 // Creates an ANSI string from the given wide string, allocating
846 // memory using new. The caller is responsible for deleting the return
847 // value using delete[]. Returns the ANSI string, or NULL if the
849 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
850 if (!utf16_str) return NULL;
851 const int ansi_length =
852 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
853 NULL, 0, NULL, NULL);
854 char* ansi = new char[ansi_length + 1];
855 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
856 ansi, ansi_length, NULL, NULL);
857 ansi[ansi_length] = 0;
861 #endif // GTEST_OS_WINDOWS_MOBILE
863 // Compares two C strings. Returns true iff they have the same content.
865 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
866 // C string is considered different to any non-NULL C string,
867 // including the empty string.
868 bool String::CStringEquals(const char * lhs, const char * rhs) {
869 if ( lhs == NULL ) return rhs == NULL;
871 if ( rhs == NULL ) return false;
873 return strcmp(lhs, rhs) == 0;
876 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
878 // Converts an array of wide chars to a narrow string using the UTF-8
879 // encoding, and streams the result to the given Message object.
880 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
882 // TODO(wan): consider allowing a testing::String object to
883 // contain '\0'. This will make it behave more like std::string,
884 // and will allow ToUtf8String() to return the correct encoding
885 // for '\0' s.t. we can get rid of the conditional here (and in
886 // several other places).
887 for (size_t i = 0; i != length; ) { // NOLINT
888 if (wstr[i] != L'\0') {
889 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
890 while (i != length && wstr[i] != L'\0')
899 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
901 } // namespace internal
903 #if GTEST_HAS_STD_WSTRING
904 // Converts the given wide string to a narrow string using the UTF-8
905 // encoding, and streams the result to this Message object.
906 Message& Message::operator <<(const ::std::wstring& wstr) {
907 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
910 #endif // GTEST_HAS_STD_WSTRING
912 #if GTEST_HAS_GLOBAL_WSTRING
913 // Converts the given wide string to a narrow string using the UTF-8
914 // encoding, and streams the result to this Message object.
915 Message& Message::operator <<(const ::wstring& wstr) {
916 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
919 #endif // GTEST_HAS_GLOBAL_WSTRING
923 // Formats a value to be used in a failure message.
925 // For a char value, we print it as a C++ char literal and as an
926 // unsigned integer (both in decimal and in hexadecimal).
927 String FormatForFailureMessage(char ch) {
928 const unsigned int ch_as_uint = ch;
929 // A String object cannot contain '\0', so we print "\\0" when ch is
931 return String::Format("'%s' (%u, 0x%X)",
932 ch ? String::Format("%c", ch).c_str() : "\\0",
933 ch_as_uint, ch_as_uint);
936 // For a wchar_t value, we print it as a C++ wchar_t literal and as an
937 // unsigned integer (both in decimal and in hexidecimal).
938 String FormatForFailureMessage(wchar_t wchar) {
939 // The C++ standard doesn't specify the exact size of the wchar_t
940 // type. It just says that it shall have the same size as another
941 // integral type, called its underlying type.
943 // Therefore, in order to print a wchar_t value in the numeric form,
944 // we first convert it to the largest integral type (UInt64) and
945 // then print the converted value.
947 // We use streaming to print the value as "%llu" doesn't work
948 // correctly with MSVC 7.1.
949 const UInt64 wchar_as_uint64 = wchar;
951 // A String object cannot contain '\0', so we print "\\0" when wchar is
953 char buffer[32]; // CodePointToUtf8 requires a buffer that big.
955 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
956 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
957 << wchar_as_uint64 << ")";
958 return msg.GetString();
961 } // namespace internal
963 // AssertionResult constructors.
964 // Used in EXPECT_TRUE/FALSE(assertion_result).
965 AssertionResult::AssertionResult(const AssertionResult& other)
966 : success_(other.success_),
967 message_(other.message_.get() != NULL ?
968 new internal::String(*other.message_) :
969 static_cast<internal::String*>(NULL)) {
972 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
973 AssertionResult AssertionResult::operator!() const {
974 AssertionResult negation(!success_);
975 if (message_.get() != NULL)
976 negation << *message_;
980 // Makes a successful assertion result.
981 AssertionResult AssertionSuccess() {
982 return AssertionResult(true);
985 // Makes a failed assertion result.
986 AssertionResult AssertionFailure() {
987 return AssertionResult(false);
990 // Makes a failed assertion result with the given failure message.
991 // Deprecated; use AssertionFailure() << message.
992 AssertionResult AssertionFailure(const Message& message) {
993 return AssertionFailure() << message;
998 // Constructs and returns the message for an equality assertion
999 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1001 // The first four parameters are the expressions used in the assertion
1002 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1003 // where foo is 5 and bar is 6, we have:
1005 // expected_expression: "foo"
1006 // actual_expression: "bar"
1007 // expected_value: "5"
1008 // actual_value: "6"
1010 // The ignoring_case parameter is true iff the assertion is a
1011 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
1012 // be inserted into the message.
1013 AssertionResult EqFailure(const char* expected_expression,
1014 const char* actual_expression,
1015 const String& expected_value,
1016 const String& actual_value,
1017 bool ignoring_case) {
1019 msg << "Value of: " << actual_expression;
1020 if (actual_value != actual_expression) {
1021 msg << "\n Actual: " << actual_value;
1024 msg << "\nExpected: " << expected_expression;
1025 if (ignoring_case) {
1026 msg << " (ignoring case)";
1028 if (expected_value != expected_expression) {
1029 msg << "\nWhich is: " << expected_value;
1032 return AssertionFailure(msg);
1035 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1036 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1037 const char* expression_text,
1038 const char* actual_predicate_value,
1039 const char* expected_predicate_value) {
1040 const char* actual_message = assertion_result.message();
1042 msg << "Value of: " << expression_text
1043 << "\n Actual: " << actual_predicate_value;
1044 if (actual_message[0] != '\0')
1045 msg << " (" << actual_message << ")";
1046 msg << "\nExpected: " << expected_predicate_value;
1047 return msg.GetString();
1050 // Helper function for implementing ASSERT_NEAR.
1051 AssertionResult DoubleNearPredFormat(const char* expr1,
1053 const char* abs_error_expr,
1057 const double diff = fabs(val1 - val2);
1058 if (diff <= abs_error) return AssertionSuccess();
1060 // TODO(wan): do not print the value of an expression if it's
1061 // already a literal.
1063 msg << "The difference between " << expr1 << " and " << expr2
1064 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1065 << expr1 << " evaluates to " << val1 << ",\n"
1066 << expr2 << " evaluates to " << val2 << ", and\n"
1067 << abs_error_expr << " evaluates to " << abs_error << ".";
1068 return AssertionFailure(msg);
1072 // Helper template for implementing FloatLE() and DoubleLE().
1073 template <typename RawType>
1074 AssertionResult FloatingPointLE(const char* expr1,
1078 // Returns success if val1 is less than val2,
1080 return AssertionSuccess();
1083 // or if val1 is almost equal to val2.
1084 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1085 if (lhs.AlmostEquals(rhs)) {
1086 return AssertionSuccess();
1089 // Note that the above two checks will both fail if either val1 or
1090 // val2 is NaN, as the IEEE floating-point standard requires that
1091 // any predicate involving a NaN must return false.
1094 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1098 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1102 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1103 << " Actual: " << StrStreamToString(&val1_ss) << " vs "
1104 << StrStreamToString(&val2_ss);
1106 return AssertionFailure(msg);
1109 } // namespace internal
1111 // Asserts that val1 is less than, or almost equal to, val2. Fails
1112 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1113 AssertionResult FloatLE(const char* expr1, const char* expr2,
1114 float val1, float val2) {
1115 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1118 // Asserts that val1 is less than, or almost equal to, val2. Fails
1119 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1120 AssertionResult DoubleLE(const char* expr1, const char* expr2,
1121 double val1, double val2) {
1122 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1125 namespace internal {
1127 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
1129 AssertionResult CmpHelperEQ(const char* expected_expression,
1130 const char* actual_expression,
1131 BiggestInt expected,
1132 BiggestInt actual) {
1133 if (expected == actual) {
1134 return AssertionSuccess();
1137 return EqFailure(expected_expression,
1139 FormatForComparisonFailureMessage(expected, actual),
1140 FormatForComparisonFailureMessage(actual, expected),
1144 // A macro for implementing the helper functions needed to implement
1145 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1146 // just to avoid copy-and-paste of similar code.
1147 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1148 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1149 BiggestInt val1, BiggestInt val2) {\
1150 if (val1 op val2) {\
1151 return AssertionSuccess();\
1154 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1155 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1156 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1157 return AssertionFailure(msg);\
1161 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
1163 GTEST_IMPL_CMP_HELPER_(NE, !=)
1164 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
1166 GTEST_IMPL_CMP_HELPER_(LE, <=)
1167 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
1169 GTEST_IMPL_CMP_HELPER_(LT, < )
1170 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
1172 GTEST_IMPL_CMP_HELPER_(GE, >=)
1173 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
1175 GTEST_IMPL_CMP_HELPER_(GT, > )
1177 #undef GTEST_IMPL_CMP_HELPER_
1179 // The helper function for {ASSERT|EXPECT}_STREQ.
1180 AssertionResult CmpHelperSTREQ(const char* expected_expression,
1181 const char* actual_expression,
1182 const char* expected,
1183 const char* actual) {
1184 if (String::CStringEquals(expected, actual)) {
1185 return AssertionSuccess();
1188 return EqFailure(expected_expression,
1190 String::ShowCStringQuoted(expected),
1191 String::ShowCStringQuoted(actual),
1195 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1196 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1197 const char* actual_expression,
1198 const char* expected,
1199 const char* actual) {
1200 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1201 return AssertionSuccess();
1204 return EqFailure(expected_expression,
1206 String::ShowCStringQuoted(expected),
1207 String::ShowCStringQuoted(actual),
1211 // The helper function for {ASSERT|EXPECT}_STRNE.
1212 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1213 const char* s2_expression,
1216 if (!String::CStringEquals(s1, s2)) {
1217 return AssertionSuccess();
1220 msg << "Expected: (" << s1_expression << ") != ("
1221 << s2_expression << "), actual: \""
1222 << s1 << "\" vs \"" << s2 << "\"";
1223 return AssertionFailure(msg);
1227 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1228 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1229 const char* s2_expression,
1232 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1233 return AssertionSuccess();
1236 msg << "Expected: (" << s1_expression << ") != ("
1237 << s2_expression << ") (ignoring case), actual: \""
1238 << s1 << "\" vs \"" << s2 << "\"";
1239 return AssertionFailure(msg);
1243 } // namespace internal
1247 // Helper functions for implementing IsSubString() and IsNotSubstring().
1249 // This group of overloaded functions return true iff needle is a
1250 // substring of haystack. NULL is considered a substring of itself
1253 bool IsSubstringPred(const char* needle, const char* haystack) {
1254 if (needle == NULL || haystack == NULL)
1255 return needle == haystack;
1257 return strstr(haystack, needle) != NULL;
1260 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1261 if (needle == NULL || haystack == NULL)
1262 return needle == haystack;
1264 return wcsstr(haystack, needle) != NULL;
1267 // StringType here can be either ::std::string or ::std::wstring.
1268 template <typename StringType>
1269 bool IsSubstringPred(const StringType& needle,
1270 const StringType& haystack) {
1271 return haystack.find(needle) != StringType::npos;
1274 // This function implements either IsSubstring() or IsNotSubstring(),
1275 // depending on the value of the expected_to_be_substring parameter.
1276 // StringType here can be const char*, const wchar_t*, ::std::string,
1277 // or ::std::wstring.
1278 template <typename StringType>
1279 AssertionResult IsSubstringImpl(
1280 bool expected_to_be_substring,
1281 const char* needle_expr, const char* haystack_expr,
1282 const StringType& needle, const StringType& haystack) {
1283 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1284 return AssertionSuccess();
1286 const bool is_wide_string = sizeof(needle[0]) > 1;
1287 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1288 return AssertionFailure(
1290 << "Value of: " << needle_expr << "\n"
1291 << " Actual: " << begin_string_quote << needle << "\"\n"
1292 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1293 << "a substring of " << haystack_expr << "\n"
1294 << "Which is: " << begin_string_quote << haystack << "\"");
1299 // IsSubstring() and IsNotSubstring() check whether needle is a
1300 // substring of haystack (NULL is considered a substring of itself
1301 // only), and return an appropriate error message when they fail.
1303 AssertionResult IsSubstring(
1304 const char* needle_expr, const char* haystack_expr,
1305 const char* needle, const char* haystack) {
1306 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1309 AssertionResult IsSubstring(
1310 const char* needle_expr, const char* haystack_expr,
1311 const wchar_t* needle, const wchar_t* haystack) {
1312 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1315 AssertionResult IsNotSubstring(
1316 const char* needle_expr, const char* haystack_expr,
1317 const char* needle, const char* haystack) {
1318 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1321 AssertionResult IsNotSubstring(
1322 const char* needle_expr, const char* haystack_expr,
1323 const wchar_t* needle, const wchar_t* haystack) {
1324 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1327 AssertionResult IsSubstring(
1328 const char* needle_expr, const char* haystack_expr,
1329 const ::std::string& needle, const ::std::string& haystack) {
1330 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1333 AssertionResult IsNotSubstring(
1334 const char* needle_expr, const char* haystack_expr,
1335 const ::std::string& needle, const ::std::string& haystack) {
1336 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1339 #if GTEST_HAS_STD_WSTRING
1340 AssertionResult IsSubstring(
1341 const char* needle_expr, const char* haystack_expr,
1342 const ::std::wstring& needle, const ::std::wstring& haystack) {
1343 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1346 AssertionResult IsNotSubstring(
1347 const char* needle_expr, const char* haystack_expr,
1348 const ::std::wstring& needle, const ::std::wstring& haystack) {
1349 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1351 #endif // GTEST_HAS_STD_WSTRING
1353 namespace internal {
1355 #if GTEST_OS_WINDOWS
1359 // Helper function for IsHRESULT{SuccessFailure} predicates
1360 AssertionResult HRESULTFailureHelper(const char* expr,
1361 const char* expected,
1362 long hr) { // NOLINT
1363 #if GTEST_OS_WINDOWS_MOBILE
1364 // Windows CE doesn't support FormatMessage.
1365 const char error_text[] = "";
1367 // Looks up the human-readable system message for the HRESULT code
1368 // and since we're not passing any params to FormatMessage, we don't
1369 // want inserts expanded.
1370 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1371 FORMAT_MESSAGE_IGNORE_INSERTS;
1372 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1373 // Gets the system's human readable message string for this HRESULT.
1374 char error_text[kBufSize] = { '\0' };
1375 DWORD message_length = ::FormatMessageA(kFlags,
1376 0, // no source, we're asking system
1378 0, // no line width restrictions
1379 error_text, // output buffer
1380 kBufSize, // buf size
1381 NULL); // no arguments for inserts
1382 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1383 for (; message_length && isspace(error_text[message_length - 1]);
1385 error_text[message_length - 1] = '\0';
1387 #endif // GTEST_OS_WINDOWS_MOBILE
1389 const String error_hex(String::Format("0x%08X ", hr));
1391 msg << "Expected: " << expr << " " << expected << ".\n"
1392 << " Actual: " << error_hex << error_text << "\n";
1394 return ::testing::AssertionFailure(msg);
1399 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1400 if (SUCCEEDED(hr)) {
1401 return AssertionSuccess();
1403 return HRESULTFailureHelper(expr, "succeeds", hr);
1406 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1408 return AssertionSuccess();
1410 return HRESULTFailureHelper(expr, "fails", hr);
1413 #endif // GTEST_OS_WINDOWS
1415 // Utility functions for encoding Unicode text (wide strings) in
1418 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1421 // Code-point length Encoding
1422 // 0 - 7 bits 0xxxxxxx
1423 // 8 - 11 bits 110xxxxx 10xxxxxx
1424 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1425 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1427 // The maximum code-point a one-byte UTF-8 sequence can represent.
1428 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1430 // The maximum code-point a two-byte UTF-8 sequence can represent.
1431 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1433 // The maximum code-point a three-byte UTF-8 sequence can represent.
1434 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1436 // The maximum code-point a four-byte UTF-8 sequence can represent.
1437 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1439 // Chops off the n lowest bits from a bit pattern. Returns the n
1440 // lowest bits. As a side effect, the original bit pattern will be
1441 // shifted to the right by n bits.
1442 inline UInt32 ChopLowBits(UInt32* bits, int n) {
1443 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1448 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
1449 // code_point parameter is of type UInt32 because wchar_t may not be
1450 // wide enough to contain a code point.
1451 // The output buffer str must containt at least 32 characters.
1452 // The function returns the address of the output buffer.
1453 // If the code_point is not a valid Unicode code point
1454 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1455 // as '(Invalid Unicode 0xXXXXXXXX)'.
1456 char* CodePointToUtf8(UInt32 code_point, char* str) {
1457 if (code_point <= kMaxCodePoint1) {
1459 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1460 } else if (code_point <= kMaxCodePoint2) {
1462 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1463 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1464 } else if (code_point <= kMaxCodePoint3) {
1466 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1467 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1468 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1469 } else if (code_point <= kMaxCodePoint4) {
1471 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1472 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1473 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1474 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1476 // The longest string String::Format can produce when invoked
1477 // with these parameters is 28 character long (not including
1478 // the terminating nul character). We are asking for 32 character
1479 // buffer just in case. This is also enough for strncpy to
1480 // null-terminate the destination string.
1482 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
1483 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1484 // the result unterminated.
1489 // The following two functions only make sense if the the system
1490 // uses UTF-16 for wide string encoding. All supported systems
1491 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1493 // Determines if the arguments constitute UTF-16 surrogate pair
1494 // and thus should be combined into a single Unicode code point
1495 // using CreateCodePointFromUtf16SurrogatePair.
1496 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1497 return sizeof(wchar_t) == 2 &&
1498 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1501 // Creates a Unicode code point from UTF16 surrogate pair.
1502 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1504 const UInt32 mask = (1 << 10) - 1;
1505 return (sizeof(wchar_t) == 2) ?
1506 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1507 // This function should not be called when the condition is
1508 // false, but we provide a sensible default in case it is.
1509 static_cast<UInt32>(first);
1512 // Converts a wide string to a narrow string in UTF-8 encoding.
1513 // The wide string is assumed to have the following encoding:
1514 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1515 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1516 // Parameter str points to a null-terminated wide string.
1517 // Parameter num_chars may additionally limit the number
1518 // of wchar_t characters processed. -1 is used when the entire string
1519 // should be processed.
1520 // If the string contains code points that are not valid Unicode code points
1521 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1522 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1523 // and contains invalid UTF-16 surrogate pairs, values in those pairs
1524 // will be encoded as individual Unicode characters from Basic Normal Plane.
1525 String WideStringToUtf8(const wchar_t* str, int num_chars) {
1526 if (num_chars == -1)
1527 num_chars = static_cast<int>(wcslen(str));
1530 for (int i = 0; i < num_chars; ++i) {
1531 UInt32 unicode_code_point;
1533 if (str[i] == L'\0') {
1535 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1536 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1540 unicode_code_point = static_cast<UInt32>(str[i]);
1543 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1544 stream << CodePointToUtf8(unicode_code_point, buffer);
1546 return StrStreamToString(&stream);
1549 // Converts a wide C string to a String using the UTF-8 encoding.
1550 // NULL will be converted to "(null)".
1551 String String::ShowWideCString(const wchar_t * wide_c_str) {
1552 if (wide_c_str == NULL) return String("(null)");
1554 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1557 // Similar to ShowWideCString(), except that this function encloses
1558 // the converted string in double quotes.
1559 String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1560 if (wide_c_str == NULL) return String("(null)");
1562 return String::Format("L\"%s\"",
1563 String::ShowWideCString(wide_c_str).c_str());
1566 // Compares two wide C strings. Returns true iff they have the same
1569 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1570 // C string is considered different to any non-NULL C string,
1571 // including the empty string.
1572 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1573 if (lhs == NULL) return rhs == NULL;
1575 if (rhs == NULL) return false;
1577 return wcscmp(lhs, rhs) == 0;
1580 // Helper function for *_STREQ on wide strings.
1581 AssertionResult CmpHelperSTREQ(const char* expected_expression,
1582 const char* actual_expression,
1583 const wchar_t* expected,
1584 const wchar_t* actual) {
1585 if (String::WideCStringEquals(expected, actual)) {
1586 return AssertionSuccess();
1589 return EqFailure(expected_expression,
1591 String::ShowWideCStringQuoted(expected),
1592 String::ShowWideCStringQuoted(actual),
1596 // Helper function for *_STRNE on wide strings.
1597 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1598 const char* s2_expression,
1600 const wchar_t* s2) {
1601 if (!String::WideCStringEquals(s1, s2)) {
1602 return AssertionSuccess();
1606 msg << "Expected: (" << s1_expression << ") != ("
1607 << s2_expression << "), actual: "
1608 << String::ShowWideCStringQuoted(s1)
1609 << " vs " << String::ShowWideCStringQuoted(s2);
1610 return AssertionFailure(msg);
1613 // Compares two C strings, ignoring case. Returns true iff they have
1614 // the same content.
1616 // Unlike strcasecmp(), this function can handle NULL argument(s). A
1617 // NULL C string is considered different to any non-NULL C string,
1618 // including the empty string.
1619 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1624 return posix::StrCaseCmp(lhs, rhs) == 0;
1627 // Compares two wide C strings, ignoring case. Returns true iff they
1628 // have the same content.
1630 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1631 // A NULL C string is considered different to any non-NULL wide C string,
1632 // including the empty string.
1633 // NB: The implementations on different platforms slightly differ.
1634 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1635 // environment variable. On GNU platform this method uses wcscasecmp
1636 // which compares according to LC_CTYPE category of the current locale.
1637 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1639 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1640 const wchar_t* rhs) {
1641 if ( lhs == NULL ) return rhs == NULL;
1643 if ( rhs == NULL ) return false;
1645 #if GTEST_OS_WINDOWS
1646 return _wcsicmp(lhs, rhs) == 0;
1647 #elif GTEST_OS_LINUX
1648 return wcscasecmp(lhs, rhs) == 0;
1650 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1651 // may not define it either.
1654 left = towlower(*lhs++);
1655 right = towlower(*rhs++);
1656 } while (left && left == right);
1657 return left == right;
1658 #endif // OS selector
1661 // Compares this with another String.
1662 // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1663 // if this is greater than rhs.
1664 int String::Compare(const String & rhs) const {
1665 const char* const lhs_c_str = c_str();
1666 const char* const rhs_c_str = rhs.c_str();
1668 if (lhs_c_str == NULL) {
1669 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1670 } else if (rhs_c_str == NULL) {
1674 const size_t shorter_str_len =
1675 length() <= rhs.length() ? length() : rhs.length();
1676 for (size_t i = 0; i != shorter_str_len; i++) {
1677 if (lhs_c_str[i] < rhs_c_str[i]) {
1679 } else if (lhs_c_str[i] > rhs_c_str[i]) {
1683 return (length() < rhs.length()) ? -1 :
1684 (length() > rhs.length()) ? 1 : 0;
1687 // Returns true iff this String ends with the given suffix. *Any*
1688 // String is considered to end with a NULL or empty suffix.
1689 bool String::EndsWith(const char* suffix) const {
1690 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1692 if (c_str() == NULL) return false;
1694 const size_t this_len = strlen(c_str());
1695 const size_t suffix_len = strlen(suffix);
1696 return (this_len >= suffix_len) &&
1697 CStringEquals(c_str() + this_len - suffix_len, suffix);
1700 // Returns true iff this String ends with the given suffix, ignoring case.
1701 // Any String is considered to end with a NULL or empty suffix.
1702 bool String::EndsWithCaseInsensitive(const char* suffix) const {
1703 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1705 if (c_str() == NULL) return false;
1707 const size_t this_len = strlen(c_str());
1708 const size_t suffix_len = strlen(suffix);
1709 return (this_len >= suffix_len) &&
1710 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1713 // Formats a list of arguments to a String, using the same format
1714 // spec string as for printf.
1716 // We do not use the StringPrintf class as it is not universally
1719 // The result is limited to 4096 characters (including the tailing 0).
1720 // If 4096 characters are not enough to format the input, or if
1721 // there's an error, "<formatting error or buffer exceeded>" is
1723 String String::Format(const char * format, ...) {
1725 va_start(args, format);
1728 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1730 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1731 // 4996 (deprecated function) there.
1732 #ifdef _MSC_VER // We are using MSVC.
1733 #pragma warning(push) // Saves the current warning state.
1734 #pragma warning(disable:4996) // Temporarily disables warning 4996.
1735 const int size = vsnprintf(buffer, kBufferSize, format, args);
1736 #pragma warning(pop) // Restores the warning state.
1737 #else // We are not using MSVC.
1738 const int size = vsnprintf(buffer, kBufferSize, format, args);
1742 // vsnprintf()'s behavior is not portable. When the buffer is not
1743 // big enough, it returns a negative value in MSVC, and returns the
1744 // needed buffer size on Linux. When there is an output error, it
1745 // always returns a negative value. For simplicity, we lump the two
1746 // error cases together.
1747 if (size < 0 || size >= kBufferSize) {
1748 return String("<formatting error or buffer exceeded>");
1750 return String(buffer, size);
1754 // Converts the buffer in a StrStream to a String, converting NUL
1755 // bytes to "\\0" along the way.
1756 String StrStreamToString(StrStream* ss) {
1757 const ::std::string& str = ss->str();
1758 const char* const start = str.c_str();
1759 const char* const end = start + str.length();
1761 // We need to use a helper StrStream to do this transformation
1762 // because String doesn't support push_back().
1764 for (const char* ch = start; ch != end; ++ch) {
1766 helper << "\\0"; // Replaces NUL with "\\0";
1772 return String(helper.str().c_str());
1775 // Appends the user-supplied message to the Google-Test-generated message.
1776 String AppendUserMessage(const String& gtest_msg,
1777 const Message& user_msg) {
1778 // Appends the user message if it's non-empty.
1779 const String user_msg_string = user_msg.GetString();
1780 if (user_msg_string.empty()) {
1785 msg << gtest_msg << "\n" << user_msg_string;
1787 return msg.GetString();
1790 } // namespace internal
1794 // Creates an empty TestResult.
1795 TestResult::TestResult()
1796 : death_test_count_(0),
1801 TestResult::~TestResult() {
1804 // Returns the i-th test part result among all the results. i can
1805 // range from 0 to total_part_count() - 1. If i is not in that range,
1806 // aborts the program.
1807 const TestPartResult& TestResult::GetTestPartResult(int i) const {
1808 if (i < 0 || i >= total_part_count())
1809 internal::posix::Abort();
1810 return test_part_results_.at(i);
1813 // Returns the i-th test property. i can range from 0 to
1814 // test_property_count() - 1. If i is not in that range, aborts the
1816 const TestProperty& TestResult::GetTestProperty(int i) const {
1817 if (i < 0 || i >= test_property_count())
1818 internal::posix::Abort();
1819 return test_properties_.at(i);
1822 // Clears the test part results.
1823 void TestResult::ClearTestPartResults() {
1824 test_part_results_.clear();
1827 // Adds a test part result to the list.
1828 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1829 test_part_results_.push_back(test_part_result);
1832 // Adds a test property to the list. If a property with the same key as the
1833 // supplied property is already represented, the value of this test_property
1834 // replaces the old value for that key.
1835 void TestResult::RecordProperty(const TestProperty& test_property) {
1836 if (!ValidateTestProperty(test_property)) {
1839 internal::MutexLock lock(&test_properites_mutex_);
1840 const std::vector<TestProperty>::iterator property_with_matching_key =
1841 std::find_if(test_properties_.begin(), test_properties_.end(),
1842 internal::TestPropertyKeyIs(test_property.key()));
1843 if (property_with_matching_key == test_properties_.end()) {
1844 test_properties_.push_back(test_property);
1847 property_with_matching_key->SetValue(test_property.value());
1850 // Adds a failure if the key is a reserved attribute of Google Test
1851 // testcase tags. Returns true if the property is valid.
1852 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1853 internal::String key(test_property.key());
1854 if (key == "name" || key == "status" || key == "time" || key == "classname") {
1856 << "Reserved key used in RecordProperty(): "
1858 << " ('name', 'status', 'time', and 'classname' are reserved by "
1859 << GTEST_NAME_ << ")";
1865 // Clears the object.
1866 void TestResult::Clear() {
1867 test_part_results_.clear();
1868 test_properties_.clear();
1869 death_test_count_ = 0;
1873 // Returns true iff the test failed.
1874 bool TestResult::Failed() const {
1875 for (int i = 0; i < total_part_count(); ++i) {
1876 if (GetTestPartResult(i).failed())
1882 // Returns true iff the test part fatally failed.
1883 static bool TestPartFatallyFailed(const TestPartResult& result) {
1884 return result.fatally_failed();
1887 // Returns true iff the test fatally failed.
1888 bool TestResult::HasFatalFailure() const {
1889 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
1892 // Returns true iff the test part non-fatally failed.
1893 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1894 return result.nonfatally_failed();
1897 // Returns true iff the test has a non-fatal failure.
1898 bool TestResult::HasNonfatalFailure() const {
1899 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
1902 // Gets the number of all test parts. This is the sum of the number
1903 // of successful test parts and the number of failed test parts.
1904 int TestResult::total_part_count() const {
1905 return static_cast<int>(test_part_results_.size());
1908 // Returns the number of the test properties.
1909 int TestResult::test_property_count() const {
1910 return static_cast<int>(test_properties_.size());
1915 // Creates a Test object.
1917 // The c'tor saves the values of all Google Test flags.
1919 : gtest_flag_saver_(new internal::GTestFlagSaver) {
1922 // The d'tor restores the values of all Google Test flags.
1924 delete gtest_flag_saver_;
1927 // Sets up the test fixture.
1929 // A sub-class may override this.
1930 void Test::SetUp() {
1933 // Tears down the test fixture.
1935 // A sub-class may override this.
1936 void Test::TearDown() {
1939 // Allows user supplied key value pairs to be recorded for later output.
1940 void Test::RecordProperty(const char* key, const char* value) {
1941 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1944 // Allows user supplied key value pairs to be recorded for later output.
1945 void Test::RecordProperty(const char* key, int value) {
1946 Message value_message;
1947 value_message << value;
1948 RecordProperty(key, value_message.GetString().c_str());
1951 namespace internal {
1953 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1954 const String& message) {
1955 // This function is a friend of UnitTest and as such has access to
1956 // AddTestPartResult.
1957 UnitTest::GetInstance()->AddTestPartResult(
1959 NULL, // No info about the source file where the exception occurred.
1960 -1, // We have no info on which line caused the exception.
1962 String()); // No stack trace, either.
1965 } // namespace internal
1968 // We are on Windows with SEH.
1970 // Adds an "exception thrown" fatal failure to the current test.
1971 static void AddExceptionThrownFailure(DWORD exception_code,
1972 const char* location) {
1974 message << "Exception thrown with code 0x" << std::setbase(16) <<
1975 exception_code << std::setbase(10) << " in " << location << ".";
1977 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1978 message.GetString());
1981 #endif // GTEST_HAS_SEH
1983 // Google Test requires all tests in the same test case to use the same test
1984 // fixture class. This function checks if the current test has the
1985 // same fixture class as the first test in the current test case. If
1986 // yes, it returns true; otherwise it generates a Google Test failure and
1988 bool Test::HasSameFixtureClass() {
1989 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1990 const TestCase* const test_case = impl->current_test_case();
1992 // Info about the first test in the current test case.
1993 const internal::TestInfoImpl* const first_test_info =
1994 test_case->test_info_list()[0]->impl();
1995 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1996 const char* const first_test_name = first_test_info->name();
1998 // Info about the current test.
1999 const internal::TestInfoImpl* const this_test_info =
2000 impl->current_test_info()->impl();
2001 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
2002 const char* const this_test_name = this_test_info->name();
2004 if (this_fixture_id != first_fixture_id) {
2005 // Is the first test defined using TEST?
2006 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2007 // Is this test defined using TEST?
2008 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2010 if (first_is_TEST || this_is_TEST) {
2011 // The user mixed TEST and TEST_F in this test case - we'll tell
2012 // him/her how to fix it.
2014 // Gets the name of the TEST and the name of the TEST_F. Note
2015 // that first_is_TEST and this_is_TEST cannot both be true, as
2016 // the fixture IDs are different for the two tests.
2017 const char* const TEST_name =
2018 first_is_TEST ? first_test_name : this_test_name;
2019 const char* const TEST_F_name =
2020 first_is_TEST ? this_test_name : first_test_name;
2023 << "All tests in the same test case must use the same test fixture\n"
2024 << "class, so mixing TEST_F and TEST in the same test case is\n"
2025 << "illegal. In test case " << this_test_info->test_case_name()
2027 << "test " << TEST_F_name << " is defined using TEST_F but\n"
2028 << "test " << TEST_name << " is defined using TEST. You probably\n"
2029 << "want to change the TEST to TEST_F or move it to another test\n"
2032 // The user defined two fixture classes with the same name in
2033 // two namespaces - we'll tell him/her how to fix it.
2035 << "All tests in the same test case must use the same test fixture\n"
2036 << "class. However, in test case "
2037 << this_test_info->test_case_name() << ",\n"
2038 << "you defined test " << first_test_name
2039 << " and test " << this_test_name << "\n"
2040 << "using two different test fixture classes. This can happen if\n"
2041 << "the two classes are from different namespaces or translation\n"
2042 << "units and have the same name. You should probably rename one\n"
2043 << "of the classes to put the tests into different test cases.";
2051 // Runs the test and updates the test result.
2053 if (!HasSameFixtureClass()) return;
2055 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2057 // Catch SEH-style exceptions.
2058 impl->os_stack_trace_getter()->UponLeavingGTest();
2061 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2062 GetExceptionCode())) {
2063 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2066 // We will run the test only if SetUp() had no fatal failure.
2067 if (!HasFatalFailure()) {
2068 impl->os_stack_trace_getter()->UponLeavingGTest();
2071 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2072 GetExceptionCode())) {
2073 AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2077 // However, we want to clean up as much as possible. Hence we will
2078 // always call TearDown(), even if SetUp() or the test body has
2080 impl->os_stack_trace_getter()->UponLeavingGTest();
2083 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2084 GetExceptionCode())) {
2085 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2088 #else // We are on a compiler or platform that doesn't support SEH.
2089 impl->os_stack_trace_getter()->UponLeavingGTest();
2092 // We will run the test only if SetUp() was successful.
2093 if (!HasFatalFailure()) {
2094 impl->os_stack_trace_getter()->UponLeavingGTest();
2098 // However, we want to clean up as much as possible. Hence we will
2099 // always call TearDown(), even if SetUp() or the test body has
2101 impl->os_stack_trace_getter()->UponLeavingGTest();
2103 #endif // GTEST_HAS_SEH
2107 // Returns true iff the current test has a fatal failure.
2108 bool Test::HasFatalFailure() {
2109 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2112 // Returns true iff the current test has a non-fatal failure.
2113 bool Test::HasNonfatalFailure() {
2114 return internal::GetUnitTestImpl()->current_test_result()->
2115 HasNonfatalFailure();
2120 // Constructs a TestInfo object. It assumes ownership of the test factory
2121 // object via impl_.
2122 TestInfo::TestInfo(const char* a_test_case_name,
2124 const char* a_test_case_comment,
2125 const char* a_comment,
2126 internal::TypeId fixture_class_id,
2127 internal::TestFactoryBase* factory) {
2128 impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name,
2129 a_test_case_comment, a_comment,
2130 fixture_class_id, factory);
2133 // Destructs a TestInfo object.
2134 TestInfo::~TestInfo() {
2138 namespace internal {
2140 // Creates a new TestInfo object and registers it with Google Test;
2141 // returns the created object.
2145 // test_case_name: name of the test case
2146 // name: name of the test
2147 // test_case_comment: a comment on the test case that will be included in
2149 // comment: a comment on the test that will be included in the
2151 // fixture_class_id: ID of the test fixture class
2152 // set_up_tc: pointer to the function that sets up the test case
2153 // tear_down_tc: pointer to the function that tears down the test case
2154 // factory: pointer to the factory that creates a test object.
2155 // The newly created TestInfo instance will assume
2156 // ownership of the factory object.
2157 TestInfo* MakeAndRegisterTestInfo(
2158 const char* test_case_name, const char* name,
2159 const char* test_case_comment, const char* comment,
2160 TypeId fixture_class_id,
2161 SetUpTestCaseFunc set_up_tc,
2162 TearDownTestCaseFunc tear_down_tc,
2163 TestFactoryBase* factory) {
2164 TestInfo* const test_info =
2165 new TestInfo(test_case_name, name, test_case_comment, comment,
2166 fixture_class_id, factory);
2167 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2171 #if GTEST_HAS_PARAM_TEST
2172 void ReportInvalidTestCaseType(const char* test_case_name,
2173 const char* file, int line) {
2176 << "Attempted redefinition of test case " << test_case_name << ".\n"
2177 << "All tests in the same test case must use the same test fixture\n"
2178 << "class. However, in test case " << test_case_name << ", you tried\n"
2179 << "to define a test using a fixture class different from the one\n"
2180 << "used earlier. This can happen if the two fixture classes are\n"
2181 << "from different namespaces and have the same name. You should\n"
2182 << "probably rename one of the classes to put the tests into different\n"
2185 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2186 errors.GetString().c_str());
2188 #endif // GTEST_HAS_PARAM_TEST
2190 } // namespace internal
2192 // Returns the test case name.
2193 const char* TestInfo::test_case_name() const {
2194 return impl_->test_case_name();
2197 // Returns the test name.
2198 const char* TestInfo::name() const {
2199 return impl_->name();
2202 // Returns the test case comment.
2203 const char* TestInfo::test_case_comment() const {
2204 return impl_->test_case_comment();
2207 // Returns the test comment.
2208 const char* TestInfo::comment() const {
2209 return impl_->comment();
2212 // Returns true if this test should run.
2213 bool TestInfo::should_run() const { return impl_->should_run(); }
2215 // Returns true if this test matches the user-specified filter.
2216 bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2218 // Returns the result of the test.
2219 const TestResult* TestInfo::result() const { return impl_->result(); }
2221 // Increments the number of death tests encountered in this test so
2223 int TestInfo::increment_death_test_count() {
2224 return impl_->result()->increment_death_test_count();
2227 namespace internal {
2229 // This method expands all parameterized tests registered with macros TEST_P
2230 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2231 // This will be done just once during the program runtime.
2232 void UnitTestImpl::RegisterParameterizedTests() {
2233 #if GTEST_HAS_PARAM_TEST
2234 if (!parameterized_tests_registered_) {
2235 parameterized_test_registry_.RegisterTests();
2236 parameterized_tests_registered_ = true;
2241 // Creates the test object, runs it, records its result, and then
2243 void TestInfoImpl::Run() {
2244 if (!should_run_) return;
2246 // Tells UnitTest where to store test result.
2247 UnitTestImpl* const impl = internal::GetUnitTestImpl();
2248 impl->set_current_test_info(parent_);
2250 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2252 // Notifies the unit test event listeners that a test is about to start.
2253 repeater->OnTestStart(*parent_);
2255 const TimeInMillis start = GetTimeInMillis();
2257 impl->os_stack_trace_getter()->UponLeavingGTest();
2259 // Catch SEH-style exceptions.
2263 // Creates the test object.
2264 test = factory_->CreateTest();
2265 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2266 GetExceptionCode())) {
2267 AddExceptionThrownFailure(GetExceptionCode(),
2268 "the test fixture's constructor");
2271 #else // We are on a compiler or platform that doesn't support SEH.
2273 // TODO(wan): If test->Run() throws, test won't be deleted. This is
2274 // not a problem now as we don't use exceptions. If we were to
2275 // enable exceptions, we should revise the following to be
2278 // Creates the test object.
2279 Test* test = factory_->CreateTest();
2280 #endif // GTEST_HAS_SEH
2282 // Runs the test only if the constructor of the test fixture didn't
2283 // generate a fatal failure.
2284 if (!Test::HasFatalFailure()) {
2288 // Deletes the test object.
2289 impl->os_stack_trace_getter()->UponLeavingGTest();
2293 result_.set_elapsed_time(GetTimeInMillis() - start);
2295 // Notifies the unit test event listener that a test has just finished.
2296 repeater->OnTestEnd(*parent_);
2298 // Tells UnitTest to stop associating assertion results to this
2300 impl->set_current_test_info(NULL);
2303 } // namespace internal
2307 // Gets the number of successful tests in this test case.
2308 int TestCase::successful_test_count() const {
2309 return CountIf(test_info_list_, TestPassed);
2312 // Gets the number of failed tests in this test case.
2313 int TestCase::failed_test_count() const {
2314 return CountIf(test_info_list_, TestFailed);
2317 int TestCase::disabled_test_count() const {
2318 return CountIf(test_info_list_, TestDisabled);
2321 // Get the number of tests in this test case that should run.
2322 int TestCase::test_to_run_count() const {
2323 return CountIf(test_info_list_, ShouldRunTest);
2326 // Gets the number of all tests.
2327 int TestCase::total_test_count() const {
2328 return static_cast<int>(test_info_list_.size());
2331 // Creates a TestCase with the given name.
2335 // name: name of the test case
2336 // set_up_tc: pointer to the function that sets up the test case
2337 // tear_down_tc: pointer to the function that tears down the test case
2338 TestCase::TestCase(const char* a_name, const char* a_comment,
2339 Test::SetUpTestCaseFunc set_up_tc,
2340 Test::TearDownTestCaseFunc tear_down_tc)
2342 comment_(a_comment),
2343 set_up_tc_(set_up_tc),
2344 tear_down_tc_(tear_down_tc),
2349 // Destructor of TestCase.
2350 TestCase::~TestCase() {
2351 // Deletes every Test in the collection.
2352 ForEach(test_info_list_, internal::Delete<TestInfo>);
2355 // Returns the i-th test among all the tests. i can range from 0 to
2356 // total_test_count() - 1. If i is not in that range, returns NULL.
2357 const TestInfo* TestCase::GetTestInfo(int i) const {
2358 const int index = GetElementOr(test_indices_, i, -1);
2359 return index < 0 ? NULL : test_info_list_[index];
2362 // Returns the i-th test among all the tests. i can range from 0 to
2363 // total_test_count() - 1. If i is not in that range, returns NULL.
2364 TestInfo* TestCase::GetMutableTestInfo(int i) {
2365 const int index = GetElementOr(test_indices_, i, -1);
2366 return index < 0 ? NULL : test_info_list_[index];
2369 // Adds a test to this test case. Will delete the test upon
2370 // destruction of the TestCase object.
2371 void TestCase::AddTestInfo(TestInfo * test_info) {
2372 test_info_list_.push_back(test_info);
2373 test_indices_.push_back(static_cast<int>(test_indices_.size()));
2376 // Runs every test in this TestCase.
2377 void TestCase::Run() {
2378 if (!should_run_) return;
2380 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2381 impl->set_current_test_case(this);
2383 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2385 repeater->OnTestCaseStart(*this);
2386 impl->os_stack_trace_getter()->UponLeavingGTest();
2389 const internal::TimeInMillis start = internal::GetTimeInMillis();
2390 for (int i = 0; i < total_test_count(); i++) {
2391 GetMutableTestInfo(i)->impl()->Run();
2393 elapsed_time_ = internal::GetTimeInMillis() - start;
2395 impl->os_stack_trace_getter()->UponLeavingGTest();
2397 repeater->OnTestCaseEnd(*this);
2398 impl->set_current_test_case(NULL);
2401 // Clears the results of all tests in this test case.
2402 void TestCase::ClearResult() {
2403 ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult);
2406 // Returns true iff test passed.
2407 bool TestCase::TestPassed(const TestInfo * test_info) {
2408 const internal::TestInfoImpl* const impl = test_info->impl();
2409 return impl->should_run() && impl->result()->Passed();
2412 // Returns true iff test failed.
2413 bool TestCase::TestFailed(const TestInfo * test_info) {
2414 const internal::TestInfoImpl* const impl = test_info->impl();
2415 return impl->should_run() && impl->result()->Failed();
2418 // Returns true iff test is disabled.
2419 bool TestCase::TestDisabled(const TestInfo * test_info) {
2420 return test_info->impl()->is_disabled();
2423 // Returns true if the given test should run.
2424 bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2425 return test_info->impl()->should_run();
2428 // Shuffles the tests in this test case.
2429 void TestCase::ShuffleTests(internal::Random* random) {
2430 Shuffle(random, &test_indices_);
2433 // Restores the test order to before the first shuffle.
2434 void TestCase::UnshuffleTests() {
2435 for (size_t i = 0; i < test_indices_.size(); i++) {
2436 test_indices_[i] = static_cast<int>(i);
2440 // Formats a countable noun. Depending on its quantity, either the
2441 // singular form or the plural form is used. e.g.
2443 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2444 // FormatCountableNoun(5, "book", "books") returns "5 books".
2445 static internal::String FormatCountableNoun(int count,
2446 const char * singular_form,
2447 const char * plural_form) {
2448 return internal::String::Format("%d %s", count,
2449 count == 1 ? singular_form : plural_form);
2452 // Formats the count of tests.
2453 static internal::String FormatTestCount(int test_count) {
2454 return FormatCountableNoun(test_count, "test", "tests");
2457 // Formats the count of test cases.
2458 static internal::String FormatTestCaseCount(int test_case_count) {
2459 return FormatCountableNoun(test_case_count, "test case", "test cases");
2462 // Converts a TestPartResult::Type enum to human-friendly string
2463 // representation. Both kNonFatalFailure and kFatalFailure are translated
2464 // to "Failure", as the user usually doesn't care about the difference
2465 // between the two when viewing the test result.
2466 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2468 case TestPartResult::kSuccess:
2471 case TestPartResult::kNonFatalFailure:
2472 case TestPartResult::kFatalFailure:
2480 return "Unknown result type";
2483 // Prints a TestPartResult to a String.
2484 static internal::String PrintTestPartResultToString(
2485 const TestPartResult& test_part_result) {
2487 << internal::FormatFileLocation(test_part_result.file_name(),
2488 test_part_result.line_number())
2489 << " " << TestPartResultTypeToString(test_part_result.type())
2490 << test_part_result.message()).GetString();
2493 // Prints a TestPartResult.
2494 static void PrintTestPartResult(const TestPartResult& test_part_result) {
2495 const internal::String& result =
2496 PrintTestPartResultToString(test_part_result);
2497 printf("%s\n", result.c_str());
2499 // If the test program runs in Visual Studio or a debugger, the
2500 // following statements add the test part result message to the Output
2501 // window such that the user can double-click on it to jump to the
2502 // corresponding source code location; otherwise they do nothing.
2503 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2504 // We don't call OutputDebugString*() on Windows Mobile, as printing
2505 // to stdout is done by OutputDebugString() there already - we don't
2506 // want the same message printed twice.
2507 ::OutputDebugStringA(result.c_str());
2508 ::OutputDebugStringA("\n");
2512 // class PrettyUnitTestResultPrinter
2514 namespace internal {
2523 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2525 // Returns the character attribute for the given color.
2526 WORD GetColorAttribute(GTestColor color) {
2528 case COLOR_RED: return FOREGROUND_RED;
2529 case COLOR_GREEN: return FOREGROUND_GREEN;
2530 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2537 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
2538 // an invalid input.
2539 const char* GetAnsiColorCode(GTestColor color) {
2541 case COLOR_RED: return "1";
2542 case COLOR_GREEN: return "2";
2543 case COLOR_YELLOW: return "3";
2544 default: return NULL;
2548 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2550 // Returns true iff Google Test should use colors in the output.
2551 bool ShouldUseColor(bool stdout_is_tty) {
2552 const char* const gtest_color = GTEST_FLAG(color).c_str();
2554 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2555 #if GTEST_OS_WINDOWS
2556 // On Windows the TERM variable is usually not set, but the
2557 // console there does support colors.
2558 return stdout_is_tty;
2560 // On non-Windows platforms, we rely on the TERM variable.
2561 const char* const term = posix::GetEnv("TERM");
2562 const bool term_supports_color =
2563 String::CStringEquals(term, "xterm") ||
2564 String::CStringEquals(term, "xterm-color") ||
2565 String::CStringEquals(term, "xterm-256color") ||
2566 String::CStringEquals(term, "linux") ||
2567 String::CStringEquals(term, "cygwin");
2568 return stdout_is_tty && term_supports_color;
2569 #endif // GTEST_OS_WINDOWS
2572 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2573 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2574 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2575 String::CStringEquals(gtest_color, "1");
2576 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2577 // value is neither one of these nor "auto", we treat it as "no" to
2581 // Helpers for printing colored strings to stdout. Note that on Windows, we
2582 // cannot simply emit special characters and have the terminal change colors.
2583 // This routine must actually emit the characters rather than return a string
2584 // that would be colored when printed, as can be done on Linux.
2585 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2587 va_start(args, fmt);
2589 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2590 const bool use_color = false;
2592 static const bool in_color_mode =
2593 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2594 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2595 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2596 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2604 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2605 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2607 // Gets the current text color.
2608 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2609 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2610 const WORD old_color_attrs = buffer_info.wAttributes;
2612 // We need to flush the stream buffers into the console before each
2613 // SetConsoleTextAttribute call lest it affect the text that is already
2614 // printed but has not yet reached the console.
2616 SetConsoleTextAttribute(stdout_handle,
2617 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2621 // Restores the text color.
2622 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2624 printf("\033[0;3%sm", GetAnsiColorCode(color));
2626 printf("\033[m"); // Resets the terminal to default.
2627 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2631 // This class implements the TestEventListener interface.
2633 // Class PrettyUnitTestResultPrinter is copyable.
2634 class PrettyUnitTestResultPrinter : public TestEventListener {
2636 PrettyUnitTestResultPrinter() {}
2637 static void PrintTestName(const char * test_case, const char * test) {
2638 printf("%s.%s", test_case, test);
2641 // The following methods override what's in the TestEventListener class.
2642 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2643 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2644 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2645 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2646 virtual void OnTestCaseStart(const TestCase& test_case);
2647 virtual void OnTestStart(const TestInfo& test_info);
2648 virtual void OnTestPartResult(const TestPartResult& result);
2649 virtual void OnTestEnd(const TestInfo& test_info);
2650 virtual void OnTestCaseEnd(const TestCase& test_case);
2651 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2652 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2653 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2654 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
2657 static void PrintFailedTests(const UnitTest& unit_test);
2659 internal::String test_case_name_;
2662 // Fired before each iteration of tests starts.
2663 void PrettyUnitTestResultPrinter::OnTestIterationStart(
2664 const UnitTest& unit_test, int iteration) {
2665 if (GTEST_FLAG(repeat) != 1)
2666 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2668 const char* const filter = GTEST_FLAG(filter).c_str();
2670 // Prints the filter if it's not *. This reminds the user that some
2671 // tests may be skipped.
2672 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2673 ColoredPrintf(COLOR_YELLOW,
2674 "Note: %s filter = %s\n", GTEST_NAME_, filter);
2677 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2678 ColoredPrintf(COLOR_YELLOW,
2679 "Note: This is test shard %s of %s.\n",
2680 internal::posix::GetEnv(kTestShardIndex),
2681 internal::posix::GetEnv(kTestTotalShards));
2684 if (GTEST_FLAG(shuffle)) {
2685 ColoredPrintf(COLOR_YELLOW,
2686 "Note: Randomizing tests' orders with a seed of %d .\n",
2687 unit_test.random_seed());
2690 ColoredPrintf(COLOR_GREEN, "[==========] ");
2691 printf("Running %s from %s.\n",
2692 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2693 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2697 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2698 const UnitTest& /*unit_test*/) {
2699 ColoredPrintf(COLOR_GREEN, "[----------] ");
2700 printf("Global test environment set-up.\n");
2704 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2705 test_case_name_ = test_case.name();
2706 const internal::String counts =
2707 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2708 ColoredPrintf(COLOR_GREEN, "[----------] ");
2709 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2710 if (test_case.comment()[0] == '\0') {
2713 printf(", where %s\n", test_case.comment());
2718 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2719 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2720 PrintTestName(test_case_name_.c_str(), test_info.name());
2721 if (test_info.comment()[0] == '\0') {
2724 printf(", where %s\n", test_info.comment());
2729 // Called after an assertion failure.
2730 void PrettyUnitTestResultPrinter::OnTestPartResult(
2731 const TestPartResult& result) {
2732 // If the test part succeeded, we don't need to do anything.
2733 if (result.type() == TestPartResult::kSuccess)
2736 // Print failure message from the assertion (e.g. expected this and got that).
2737 PrintTestPartResult(result);
2741 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2742 if (test_info.result()->Passed()) {
2743 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2745 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2747 PrintTestName(test_case_name_.c_str(), test_info.name());
2748 if (GTEST_FLAG(print_time)) {
2749 printf(" (%s ms)\n", internal::StreamableToString(
2750 test_info.result()->elapsed_time()).c_str());
2757 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2758 if (!GTEST_FLAG(print_time)) return;
2760 test_case_name_ = test_case.name();
2761 const internal::String counts =
2762 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2763 ColoredPrintf(COLOR_GREEN, "[----------] ");
2764 printf("%s from %s (%s ms total)\n\n",
2765 counts.c_str(), test_case_name_.c_str(),
2766 internal::StreamableToString(test_case.elapsed_time()).c_str());
2770 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2771 const UnitTest& /*unit_test*/) {
2772 ColoredPrintf(COLOR_GREEN, "[----------] ");
2773 printf("Global test environment tear-down\n");
2777 // Internal helper for printing the list of failed tests.
2778 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2779 const int failed_test_count = unit_test.failed_test_count();
2780 if (failed_test_count == 0) {
2784 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2785 const TestCase& test_case = *unit_test.GetTestCase(i);
2786 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
2789 for (int j = 0; j < test_case.total_test_count(); ++j) {
2790 const TestInfo& test_info = *test_case.GetTestInfo(j);
2791 if (!test_info.should_run() || test_info.result()->Passed()) {
2794 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2795 printf("%s.%s", test_case.name(), test_info.name());
2796 if (test_case.comment()[0] != '\0' ||
2797 test_info.comment()[0] != '\0') {
2798 printf(", where %s", test_case.comment());
2799 if (test_case.comment()[0] != '\0' &&
2800 test_info.comment()[0] != '\0') {
2804 printf("%s\n", test_info.comment());
2809 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2810 int /*iteration*/) {
2811 ColoredPrintf(COLOR_GREEN, "[==========] ");
2812 printf("%s from %s ran.",
2813 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2814 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2815 if (GTEST_FLAG(print_time)) {
2816 printf(" (%s ms total)",
2817 internal::StreamableToString(unit_test.elapsed_time()).c_str());
2820 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2821 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
2823 int num_failures = unit_test.failed_test_count();
2824 if (!unit_test.Passed()) {
2825 const int failed_test_count = unit_test.failed_test_count();
2826 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2827 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2828 PrintFailedTests(unit_test);
2829 printf("\n%2d FAILED %s\n", num_failures,
2830 num_failures == 1 ? "TEST" : "TESTS");
2833 int num_disabled = unit_test.disabled_test_count();
2834 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
2835 if (!num_failures) {
2836 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2838 ColoredPrintf(COLOR_YELLOW,
2839 " YOU HAVE %d DISABLED %s\n\n",
2841 num_disabled == 1 ? "TEST" : "TESTS");
2843 // Ensure that Google Test output is printed before, e.g., heapchecker output.
2847 // End PrettyUnitTestResultPrinter
2849 // class TestEventRepeater
2851 // This class forwards events to other event listeners.
2852 class TestEventRepeater : public TestEventListener {
2854 TestEventRepeater() : forwarding_enabled_(true) {}
2855 virtual ~TestEventRepeater();
2856 void Append(TestEventListener *listener);
2857 TestEventListener* Release(TestEventListener* listener);
2859 // Controls whether events will be forwarded to listeners_. Set to false
2860 // in death test child processes.
2861 bool forwarding_enabled() const { return forwarding_enabled_; }
2862 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2864 virtual void OnTestProgramStart(const UnitTest& unit_test);
2865 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2866 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2867 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2868 virtual void OnTestCaseStart(const TestCase& test_case);
2869 virtual void OnTestStart(const TestInfo& test_info);
2870 virtual void OnTestPartResult(const TestPartResult& result);
2871 virtual void OnTestEnd(const TestInfo& test_info);
2872 virtual void OnTestCaseEnd(const TestCase& test_case);
2873 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2874 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2875 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2876 virtual void OnTestProgramEnd(const UnitTest& unit_test);
2879 // Controls whether events will be forwarded to listeners_. Set to false
2880 // in death test child processes.
2881 bool forwarding_enabled_;
2882 // The list of listeners that receive events.
2883 std::vector<TestEventListener*> listeners_;
2885 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
2888 TestEventRepeater::~TestEventRepeater() {
2889 ForEach(listeners_, Delete<TestEventListener>);
2892 void TestEventRepeater::Append(TestEventListener *listener) {
2893 listeners_.push_back(listener);
2896 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2897 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
2898 for (size_t i = 0; i < listeners_.size(); ++i) {
2899 if (listeners_[i] == listener) {
2900 listeners_.erase(listeners_.begin() + i);
2908 // Since most methods are very similar, use macros to reduce boilerplate.
2909 // This defines a member that forwards the call to all listeners.
2910 #define GTEST_REPEATER_METHOD_(Name, Type) \
2911 void TestEventRepeater::Name(const Type& parameter) { \
2912 if (forwarding_enabled_) { \
2913 for (size_t i = 0; i < listeners_.size(); i++) { \
2914 listeners_[i]->Name(parameter); \
2918 // This defines a member that forwards the call to all listeners in reverse
2920 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2921 void TestEventRepeater::Name(const Type& parameter) { \
2922 if (forwarding_enabled_) { \
2923 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
2924 listeners_[i]->Name(parameter); \
2929 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2930 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
2931 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2932 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2933 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2934 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2935 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2936 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2937 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2938 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2939 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
2941 #undef GTEST_REPEATER_METHOD_
2942 #undef GTEST_REVERSE_REPEATER_METHOD_
2944 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2946 if (forwarding_enabled_) {
2947 for (size_t i = 0; i < listeners_.size(); i++) {
2948 listeners_[i]->OnTestIterationStart(unit_test, iteration);
2953 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2955 if (forwarding_enabled_) {
2956 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
2957 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
2962 // End TestEventRepeater
2964 // This class generates an XML output file.
2965 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
2967 explicit XmlUnitTestResultPrinter(const char* output_file);
2969 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2972 // Is c a whitespace character that is normalized to a space character
2973 // when it appears in an XML attribute value?
2974 static bool IsNormalizableWhitespace(char c) {
2975 return c == 0x9 || c == 0xA || c == 0xD;
2978 // May c appear in a well-formed XML document?
2979 static bool IsValidXmlCharacter(char c) {
2980 return IsNormalizableWhitespace(c) || c >= 0x20;
2983 // Returns an XML-escaped copy of the input string str. If
2984 // is_attribute is true, the text is meant to appear as an attribute
2985 // value, and normalizable whitespace is preserved by replacing it
2986 // with character references.
2987 static String EscapeXml(const char* str, bool is_attribute);
2989 // Returns the given string with all characters invalid in XML removed.
2990 static String RemoveInvalidXmlCharacters(const char* str);
2992 // Convenience wrapper around EscapeXml when str is an attribute value.
2993 static String EscapeXmlAttribute(const char* str) {
2994 return EscapeXml(str, true);
2997 // Convenience wrapper around EscapeXml when str is not an attribute value.
2998 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
3000 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3001 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3003 // Streams an XML representation of a TestInfo object.
3004 static void OutputXmlTestInfo(::std::ostream* stream,
3005 const char* test_case_name,
3006 const TestInfo& test_info);
3008 // Prints an XML representation of a TestCase object
3009 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
3011 // Prints an XML summary of unit_test to output stream out.
3012 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
3014 // Produces a string representing the test properties in a result as space
3015 // delimited XML attributes based on the property key="value" pairs.
3016 // When the String is not empty, it includes a space at the beginning,
3017 // to delimit this attribute from prior attributes.
3018 static String TestPropertiesAsXmlAttributes(const TestResult& result);
3021 const String output_file_;
3023 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3026 // Creates a new XmlUnitTestResultPrinter.
3027 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3028 : output_file_(output_file) {
3029 if (output_file_.c_str() == NULL || output_file_.empty()) {
3030 fprintf(stderr, "XML output file may not be null\n");
3036 // Called after the unit test ends.
3037 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3038 int /*iteration*/) {
3039 FILE* xmlout = NULL;
3040 FilePath output_file(output_file_);
3041 FilePath output_dir(output_file.RemoveFileName());
3043 if (output_dir.CreateDirectoriesRecursively()) {
3044 xmlout = posix::FOpen(output_file_.c_str(), "w");
3046 if (xmlout == NULL) {
3047 // TODO(wan): report the reason of the failure.
3049 // We don't do it for now as:
3051 // 1. There is no urgent need for it.
3052 // 2. It's a bit involved to make the errno variable thread-safe on
3053 // all three operating systems (Linux, Windows, and Mac OS).
3054 // 3. To interpret the meaning of errno in a thread-safe way,
3055 // we need the strerror_r() function, which is not available on
3058 "Unable to open file \"%s\"\n",
3059 output_file_.c_str());
3063 PrintXmlUnitTest(xmlout, unit_test);
3067 // Returns an XML-escaped copy of the input string str. If is_attribute
3068 // is true, the text is meant to appear as an attribute value, and
3069 // normalizable whitespace is preserved by replacing it with character
3072 // Invalid XML characters in str, if any, are stripped from the output.
3073 // It is expected that most, if not all, of the text processed by this
3074 // module will consist of ordinary English text.
3075 // If this module is ever modified to produce version 1.1 XML output,
3076 // most invalid characters can be retained using character references.
3077 // TODO(wan): It might be nice to have a minimally invasive, human-readable
3078 // escaping scheme for invalid characters, rather than dropping them.
3079 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
3083 for (const char* src = str; *src; ++src) {
3107 if (IsValidXmlCharacter(*src)) {
3108 if (is_attribute && IsNormalizableWhitespace(*src))
3109 m << String::Format("&#x%02X;", unsigned(*src));
3118 return m.GetString();
3121 // Returns the given string with all characters invalid in XML removed.
3122 // Currently invalid characters are dropped from the string. An
3123 // alternative is to replace them with certain characters such as . or ?.
3124 String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3125 char* const output = new char[strlen(str) + 1];
3126 char* appender = output;
3127 for (char ch = *str; ch != '\0'; ch = *++str)
3128 if (IsValidXmlCharacter(ch))
3132 String ret_value(output);
3137 // The following routines generate an XML representation of a UnitTest
3140 // This is how Google Test concepts map to the DTD:
3142 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3143 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3144 // <testcase name="test-name"> <-- corresponds to a TestInfo object
3145 // <failure message="...">...</failure>
3146 // <failure message="...">...</failure>
3147 // <failure message="...">...</failure>
3148 // <-- individual assertion failures
3153 // Formats the given time in milliseconds as seconds.
3154 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3155 ::std::stringstream ss;
3160 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3161 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3163 const char* segment = data;
3164 *stream << "<![CDATA[";
3166 const char* const next_segment = strstr(segment, "]]>");
3167 if (next_segment != NULL) {
3169 segment, static_cast<std::streamsize>(next_segment - segment));
3170 *stream << "]]>]]><![CDATA[";
3171 segment = next_segment + strlen("]]>");
3180 // Prints an XML representation of a TestInfo object.
3181 // TODO(wan): There is also value in printing properties with the plain printer.
3182 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3183 const char* test_case_name,
3184 const TestInfo& test_info) {
3185 const TestResult& result = *test_info.result();
3186 *stream << " <testcase name=\""
3187 << EscapeXmlAttribute(test_info.name()).c_str()
3189 << (test_info.should_run() ? "run" : "notrun")
3191 << FormatTimeInMillisAsSeconds(result.elapsed_time())
3192 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3193 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
3196 for (int i = 0; i < result.total_part_count(); ++i) {
3197 const TestPartResult& part = result.GetTestPartResult(i);
3198 if (part.failed()) {
3199 if (++failures == 1)
3201 *stream << " <failure message=\""
3202 << EscapeXmlAttribute(part.summary()).c_str()
3204 const String message = RemoveInvalidXmlCharacters(String::Format(
3206 part.file_name(), part.line_number(),
3207 part.message()).c_str());
3208 OutputXmlCDataSection(stream, message.c_str());
3209 *stream << "</failure>\n";
3216 *stream << " </testcase>\n";
3219 // Prints an XML representation of a TestCase object
3220 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3221 const TestCase& test_case) {
3223 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3225 EscapeXmlAttribute(test_case.name()).c_str(),
3226 test_case.total_test_count(),
3227 test_case.failed_test_count(),
3228 test_case.disabled_test_count());
3230 "errors=\"0\" time=\"%s\">\n",
3231 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
3232 for (int i = 0; i < test_case.total_test_count(); ++i) {
3234 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3235 fprintf(out, "%s", StrStreamToString(&stream).c_str());
3237 fprintf(out, " </testsuite>\n");
3240 // Prints an XML summary of unit_test to output stream out.
3241 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3242 const UnitTest& unit_test) {
3243 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3245 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3246 "errors=\"0\" time=\"%s\" ",
3247 unit_test.total_test_count(),
3248 unit_test.failed_test_count(),
3249 unit_test.disabled_test_count(),
3250 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
3251 if (GTEST_FLAG(shuffle)) {
3252 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3254 fprintf(out, "name=\"AllTests\">\n");
3255 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3256 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3257 fprintf(out, "</testsuites>\n");
3260 // Produces a string representing the test properties in a result as space
3261 // delimited XML attributes based on the property key="value" pairs.
3262 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3263 const TestResult& result) {
3265 for (int i = 0; i < result.test_property_count(); ++i) {
3266 const TestProperty& property = result.GetTestProperty(i);
3267 attributes << " " << property.key() << "="
3268 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3270 return attributes.GetString();
3273 // End XmlUnitTestResultPrinter
3275 // Class ScopedTrace
3277 // Pushes the given source file location and message onto a per-thread
3278 // trace stack maintained by Google Test.
3279 // L < UnitTest::mutex_
3280 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3284 trace.message = message.GetString();
3286 UnitTest::GetInstance()->PushGTestTrace(trace);
3289 // Pops the info pushed by the c'tor.
3290 // L < UnitTest::mutex_
3291 ScopedTrace::~ScopedTrace() {
3292 UnitTest::GetInstance()->PopGTestTrace();
3296 // class OsStackTraceGetter
3298 // Returns the current OS stack trace as a String. Parameters:
3300 // max_depth - the maximum number of stack frames to be included
3302 // skip_count - the number of top frames to be skipped; doesn't count
3303 // against max_depth.
3306 // We use "L < mutex_" to denote that the function may acquire mutex_.
3307 String OsStackTraceGetter::CurrentStackTrace(int, int) {
3312 void OsStackTraceGetter::UponLeavingGTest() {
3316 OsStackTraceGetter::kElidedFramesMarker =
3317 "... " GTEST_NAME_ " internal frames ...";
3319 } // namespace internal
3321 // class TestEventListeners
3323 TestEventListeners::TestEventListeners()
3324 : repeater_(new internal::TestEventRepeater()),
3325 default_result_printer_(NULL),
3326 default_xml_generator_(NULL) {
3329 TestEventListeners::~TestEventListeners() { delete repeater_; }
3331 // Returns the standard listener responsible for the default console
3332 // output. Can be removed from the listeners list to shut down default
3333 // console output. Note that removing this object from the listener list
3334 // with Release transfers its ownership to the user.
3335 void TestEventListeners::Append(TestEventListener* listener) {
3336 repeater_->Append(listener);
3339 // Removes the given event listener from the list and returns it. It then
3340 // becomes the caller's responsibility to delete the listener. Returns
3341 // NULL if the listener is not found in the list.
3342 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3343 if (listener == default_result_printer_)
3344 default_result_printer_ = NULL;
3345 else if (listener == default_xml_generator_)
3346 default_xml_generator_ = NULL;
3347 return repeater_->Release(listener);
3350 // Returns repeater that broadcasts the TestEventListener events to all
3352 TestEventListener* TestEventListeners::repeater() { return repeater_; }
3354 // Sets the default_result_printer attribute to the provided listener.
3355 // The listener is also added to the listener list and previous
3356 // default_result_printer is removed from it and deleted. The listener can
3357 // also be NULL in which case it will not be added to the list. Does
3358 // nothing if the previous and the current listener objects are the same.
3359 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3360 if (default_result_printer_ != listener) {
3361 // It is an error to pass this method a listener that is already in the
3363 delete Release(default_result_printer_);
3364 default_result_printer_ = listener;
3365 if (listener != NULL)
3370 // Sets the default_xml_generator attribute to the provided listener. The
3371 // listener is also added to the listener list and previous
3372 // default_xml_generator is removed from it and deleted. The listener can
3373 // also be NULL in which case it will not be added to the list. Does
3374 // nothing if the previous and the current listener objects are the same.
3375 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3376 if (default_xml_generator_ != listener) {
3377 // It is an error to pass this method a listener that is already in the
3379 delete Release(default_xml_generator_);
3380 default_xml_generator_ = listener;
3381 if (listener != NULL)
3386 // Controls whether events will be forwarded by the repeater to the
3387 // listeners in the list.
3388 bool TestEventListeners::EventForwardingEnabled() const {
3389 return repeater_->forwarding_enabled();
3392 void TestEventListeners::SuppressEventForwarding() {
3393 repeater_->set_forwarding_enabled(false);
3398 // Gets the singleton UnitTest object. The first time this method is
3399 // called, a UnitTest object is constructed and returned. Consecutive
3400 // calls will return the same object.
3402 // We don't protect this under mutex_ as a user is not supposed to
3403 // call this before main() starts, from which point on the return
3404 // value will never change.
3405 UnitTest * UnitTest::GetInstance() {
3406 // When compiled with MSVC 7.1 in optimized mode, destroying the
3407 // UnitTest object upon exiting the program messes up the exit code,
3408 // causing successful tests to appear failed. We have to use a
3409 // different implementation in this case to bypass the compiler bug.
3410 // This implementation makes the compiler happy, at the cost of
3411 // leaking the UnitTest object.
3413 // CodeGear C++Builder insists on a public destructor for the
3414 // default implementation. Use this implementation to keep good OO
3415 // design with private destructor.
3417 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3418 static UnitTest* const instance = new UnitTest;
3421 static UnitTest instance;
3423 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3426 // Gets the number of successful test cases.
3427 int UnitTest::successful_test_case_count() const {
3428 return impl()->successful_test_case_count();
3431 // Gets the number of failed test cases.
3432 int UnitTest::failed_test_case_count() const {
3433 return impl()->failed_test_case_count();
3436 // Gets the number of all test cases.
3437 int UnitTest::total_test_case_count() const {
3438 return impl()->total_test_case_count();
3441 // Gets the number of all test cases that contain at least one test
3443 int UnitTest::test_case_to_run_count() const {
3444 return impl()->test_case_to_run_count();
3447 // Gets the number of successful tests.
3448 int UnitTest::successful_test_count() const {
3449 return impl()->successful_test_count();
3452 // Gets the number of failed tests.
3453 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3455 // Gets the number of disabled tests.
3456 int UnitTest::disabled_test_count() const {
3457 return impl()->disabled_test_count();
3460 // Gets the number of all tests.
3461 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3463 // Gets the number of tests that should run.
3464 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3466 // Gets the elapsed time, in milliseconds.
3467 internal::TimeInMillis UnitTest::elapsed_time() const {
3468 return impl()->elapsed_time();
3471 // Returns true iff the unit test passed (i.e. all test cases passed).
3472 bool UnitTest::Passed() const { return impl()->Passed(); }
3474 // Returns true iff the unit test failed (i.e. some test case failed
3475 // or something outside of all tests failed).
3476 bool UnitTest::Failed() const { return impl()->Failed(); }
3478 // Gets the i-th test case among all the test cases. i can range from 0 to
3479 // total_test_case_count() - 1. If i is not in that range, returns NULL.
3480 const TestCase* UnitTest::GetTestCase(int i) const {
3481 return impl()->GetTestCase(i);
3484 // Gets the i-th test case among all the test cases. i can range from 0 to
3485 // total_test_case_count() - 1. If i is not in that range, returns NULL.
3486 TestCase* UnitTest::GetMutableTestCase(int i) {
3487 return impl()->GetMutableTestCase(i);
3490 // Returns the list of event listeners that can be used to track events
3491 // inside Google Test.
3492 TestEventListeners& UnitTest::listeners() {
3493 return *impl()->listeners();
3496 // Registers and returns a global test environment. When a test
3497 // program is run, all global test environments will be set-up in the
3498 // order they were registered. After all tests in the program have
3499 // finished, all global test environments will be torn-down in the
3500 // *reverse* order they were registered.
3502 // The UnitTest object takes ownership of the given environment.
3504 // We don't protect this under mutex_, as we only support calling it
3505 // from the main thread.
3506 Environment* UnitTest::AddEnvironment(Environment* env) {
3511 impl_->environments().push_back(env);
3515 #if GTEST_HAS_EXCEPTIONS
3516 // A failed Google Test assertion will throw an exception of this type
3517 // when exceptions are enabled. We derive it from std::runtime_error,
3518 // which is for errors presumably detectable only at run time. Since
3519 // std::runtime_error inherits from std::exception, many testing
3520 // frameworks know how to extract and print the message inside it.
3521 class GoogleTestFailureException : public ::std::runtime_error {
3523 explicit GoogleTestFailureException(const TestPartResult& failure)
3524 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3528 // Adds a TestPartResult to the current TestResult object. All Google Test
3529 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3530 // this to report their results. The user code should use the
3531 // assertion macros instead of calling this directly.
3533 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3534 const char* file_name,
3536 const internal::String& message,
3537 const internal::String& os_stack_trace) {
3541 internal::MutexLock lock(&mutex_);
3542 if (impl_->gtest_trace_stack().size() > 0) {
3543 msg << "\n" << GTEST_NAME_ << " trace:";
3545 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
3547 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
3548 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3549 << " " << trace.message;
3553 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3554 msg << internal::kStackTraceMarker << os_stack_trace;
3557 const TestPartResult result =
3558 TestPartResult(result_type, file_name, line_number,
3559 msg.GetString().c_str());
3560 impl_->GetTestPartResultReporterForCurrentThread()->
3561 ReportTestPartResult(result);
3563 if (result_type != TestPartResult::kSuccess) {
3564 // gtest_break_on_failure takes precedence over
3565 // gtest_throw_on_failure. This allows a user to set the latter
3566 // in the code (perhaps in order to use Google Test assertions
3567 // with another testing framework) and specify the former on the
3568 // command line for debugging.
3569 if (GTEST_FLAG(break_on_failure)) {
3570 #if GTEST_OS_WINDOWS
3571 // Using DebugBreak on Windows allows gtest to still break into a debugger
3572 // when a failure happens and both the --gtest_break_on_failure and
3573 // the --gtest_catch_exceptions flags are specified.
3577 #endif // GTEST_OS_WINDOWS
3578 } else if (GTEST_FLAG(throw_on_failure)) {
3579 #if GTEST_HAS_EXCEPTIONS
3580 throw GoogleTestFailureException(result);
3582 // We cannot call abort() as it generates a pop-up in debug mode
3583 // that cannot be suppressed in VC 7.1 or below.
3590 // Creates and adds a property to the current TestResult. If a property matching
3591 // the supplied value already exists, updates its value instead.
3592 void UnitTest::RecordPropertyForCurrentTest(const char* key,
3593 const char* value) {
3594 const TestProperty test_property(key, value);
3595 impl_->current_test_result()->RecordProperty(test_property);
3598 // Runs all tests in this UnitTest object and prints the result.
3599 // Returns 0 if successful, or 1 otherwise.
3601 // We don't protect this under mutex_, as we only support calling it
3602 // from the main thread.
3603 int UnitTest::Run() {
3605 // Catch SEH-style exceptions.
3607 const bool in_death_test_child_process =
3608 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3610 // Either the user wants Google Test to catch exceptions thrown by the
3611 // tests or this is executing in the context of death test child
3612 // process. In either case the user does not want to see pop-up dialogs
3613 // about crashes - they are expected..
3614 if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3615 #if !GTEST_OS_WINDOWS_MOBILE
3616 // SetErrorMode doesn't exist on CE.
3617 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3618 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3619 #endif // !GTEST_OS_WINDOWS_MOBILE
3621 #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3622 // Death test children can be terminated with _abort(). On Windows,
3623 // _abort() can show a dialog with a warning message. This forces the
3624 // abort message to go to stderr instead.
3625 _set_error_mode(_OUT_TO_STDERR);
3628 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3629 // In the debug version, Visual Studio pops up a separate dialog
3630 // offering a choice to debug the aborted program. We need to suppress
3631 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3632 // executed. Google Test will notify the user of any unexpected
3633 // failure via stderr.
3635 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3636 // Users of prior VC versions shall suffer the agony and pain of
3637 // clicking through the countless debug dialogs.
3638 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3639 // debug mode when compiled with VC 7.1 or lower.
3640 if (!GTEST_FLAG(break_on_failure))
3641 _set_abort_behavior(
3642 0x0, // Clear the following flags:
3643 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
3648 return impl_->RunAllTests();
3649 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3650 GetExceptionCode())) {
3651 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3656 #else // We are on a compiler or platform that doesn't support SEH.
3658 return impl_->RunAllTests();
3659 #endif // GTEST_HAS_SEH
3662 // Returns the working directory when the first TEST() or TEST_F() was
3664 const char* UnitTest::original_working_dir() const {
3665 return impl_->original_working_dir_.c_str();
3668 // Returns the TestCase object for the test that's currently running,
3669 // or NULL if no test is running.
3671 const TestCase* UnitTest::current_test_case() const {
3672 internal::MutexLock lock(&mutex_);
3673 return impl_->current_test_case();
3676 // Returns the TestInfo object for the test that's currently running,
3677 // or NULL if no test is running.
3679 const TestInfo* UnitTest::current_test_info() const {
3680 internal::MutexLock lock(&mutex_);
3681 return impl_->current_test_info();
3684 // Returns the random seed used at the start of the current test run.
3685 int UnitTest::random_seed() const { return impl_->random_seed(); }
3687 #if GTEST_HAS_PARAM_TEST
3688 // Returns ParameterizedTestCaseRegistry object used to keep track of
3689 // value-parameterized tests and instantiate and register them.
3691 internal::ParameterizedTestCaseRegistry&
3692 UnitTest::parameterized_test_registry() {
3693 return impl_->parameterized_test_registry();
3695 #endif // GTEST_HAS_PARAM_TEST
3697 // Creates an empty UnitTest.
3698 UnitTest::UnitTest() {
3699 impl_ = new internal::UnitTestImpl(this);
3702 // Destructor of UnitTest.
3703 UnitTest::~UnitTest() {
3707 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3708 // Google Test trace stack.
3710 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3711 internal::MutexLock lock(&mutex_);
3712 impl_->gtest_trace_stack().push_back(trace);
3715 // Pops a trace from the per-thread Google Test trace stack.
3717 void UnitTest::PopGTestTrace() {
3718 internal::MutexLock lock(&mutex_);
3719 impl_->gtest_trace_stack().pop_back();
3722 namespace internal {
3724 UnitTestImpl::UnitTestImpl(UnitTest* parent)
3727 #pragma warning(push) // Saves the current warning state.
3728 #pragma warning(disable:4355) // Temporarily disables warning 4355
3729 // (using this in initializer).
3730 default_global_test_part_result_reporter_(this),
3731 default_per_thread_test_part_result_reporter_(this),
3732 #pragma warning(pop) // Restores the warning state again.
3734 default_global_test_part_result_reporter_(this),
3735 default_per_thread_test_part_result_reporter_(this),
3737 global_test_part_result_repoter_(
3738 &default_global_test_part_result_reporter_),
3739 per_thread_test_part_result_reporter_(
3740 &default_per_thread_test_part_result_reporter_),
3741 #if GTEST_HAS_PARAM_TEST
3742 parameterized_test_registry_(),
3743 parameterized_tests_registered_(false),
3744 #endif // GTEST_HAS_PARAM_TEST
3745 last_death_test_case_(-1),
3746 current_test_case_(NULL),
3747 current_test_info_(NULL),
3748 ad_hoc_test_result_(),
3749 os_stack_trace_getter_(NULL),
3750 post_flag_parse_init_performed_(false),
3751 random_seed_(0), // Will be overridden by the flag before first use.
3752 random_(0), // Will be reseeded before first use.
3753 #if GTEST_HAS_DEATH_TEST
3755 internal_run_death_test_flag_(NULL),
3756 death_test_factory_(new DefaultDeathTestFactory) {
3759 #endif // GTEST_HAS_DEATH_TEST
3760 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
3763 UnitTestImpl::~UnitTestImpl() {
3764 // Deletes every TestCase.
3765 ForEach(test_cases_, internal::Delete<TestCase>);
3767 // Deletes every Environment.
3768 ForEach(environments_, internal::Delete<Environment>);
3770 delete os_stack_trace_getter_;
3773 #if GTEST_HAS_DEATH_TEST
3774 // Disables event forwarding if the control is currently in a death test
3775 // subprocess. Must not be called before InitGoogleTest.
3776 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3777 if (internal_run_death_test_flag_.get() != NULL)
3778 listeners()->SuppressEventForwarding();
3780 #endif // GTEST_HAS_DEATH_TEST
3782 // Initializes event listeners performing XML output as specified by
3783 // UnitTestOptions. Must not be called before InitGoogleTest.
3784 void UnitTestImpl::ConfigureXmlOutput() {
3785 const String& output_format = UnitTestOptions::GetOutputFormat();
3786 if (output_format == "xml") {
3787 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3788 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3789 } else if (output_format != "") {
3790 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3791 output_format.c_str());
3796 // Performs initialization dependent upon flag values obtained in
3797 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
3798 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
3799 // this function is also called from RunAllTests. Since this function can be
3800 // called more than once, it has to be idempotent.
3801 void UnitTestImpl::PostFlagParsingInit() {
3802 // Ensures that this function does not execute more than once.
3803 if (!post_flag_parse_init_performed_) {
3804 post_flag_parse_init_performed_ = true;
3806 #if GTEST_HAS_DEATH_TEST
3807 InitDeathTestSubprocessControlInfo();
3808 SuppressTestEventsIfInSubprocess();
3809 #endif // GTEST_HAS_DEATH_TEST
3811 // Registers parameterized tests. This makes parameterized tests
3812 // available to the UnitTest reflection API without running
3814 RegisterParameterizedTests();
3816 // Configures listeners for XML output. This makes it possible for users
3817 // to shut down the default XML output before invoking RUN_ALL_TESTS.
3818 ConfigureXmlOutput();
3822 // A predicate that checks the name of a TestCase against a known
3825 // This is used for implementation of the UnitTest class only. We put
3826 // it in the anonymous namespace to prevent polluting the outer
3829 // TestCaseNameIs is copyable.
3830 class TestCaseNameIs {
3833 explicit TestCaseNameIs(const String& name)
3836 // Returns true iff the name of test_case matches name_.
3837 bool operator()(const TestCase* test_case) const {
3838 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3845 // Finds and returns a TestCase with the given name. If one doesn't
3846 // exist, creates one and returns it. It's the CALLER'S
3847 // RESPONSIBILITY to ensure that this function is only called WHEN THE
3848 // TESTS ARE NOT SHUFFLED.
3852 // test_case_name: name of the test case
3853 // set_up_tc: pointer to the function that sets up the test case
3854 // tear_down_tc: pointer to the function that tears down the test case
3855 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3856 const char* comment,
3857 Test::SetUpTestCaseFunc set_up_tc,
3858 Test::TearDownTestCaseFunc tear_down_tc) {
3859 // Can we find a TestCase with the given name?
3860 const std::vector<TestCase*>::const_iterator test_case =
3861 std::find_if(test_cases_.begin(), test_cases_.end(),
3862 TestCaseNameIs(test_case_name));
3864 if (test_case != test_cases_.end())
3867 // No. Let's create one.
3868 TestCase* const new_test_case =
3869 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3871 // Is this a death test case?
3872 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3873 kDeathTestCaseFilter)) {
3874 // Yes. Inserts the test case after the last death test case
3875 // defined so far. This only works when the test cases haven't
3876 // been shuffled. Otherwise we may end up running a death test
3877 // after a non-death test.
3878 ++last_death_test_case_;
3879 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
3882 // No. Appends to the end of the list.
3883 test_cases_.push_back(new_test_case);
3886 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
3887 return new_test_case;
3890 // Helpers for setting up / tearing down the given environment. They
3891 // are for use in the ForEach() function.
3892 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3893 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3895 // Runs all tests in this UnitTest object, prints the result, and
3896 // returns 0 if all tests are successful, or 1 otherwise. If any
3897 // exception is thrown during a test on Windows, this test is
3898 // considered to be failed, but the rest of the tests will still be
3899 // run. (We disable exceptions on Linux and Mac OS X, so the issue
3900 // doesn't apply there.)
3901 // When parameterized tests are enabled, it expands and registers
3902 // parameterized tests first in RegisterParameterizedTests().
3903 // All other functions called from RunAllTests() may safely assume that
3904 // parameterized tests are ready to be counted and run.
3905 int UnitTestImpl::RunAllTests() {
3906 // Makes sure InitGoogleTest() was called.
3907 if (!GTestIsInitialized()) {
3909 "\nThis test program did NOT call ::testing::InitGoogleTest "
3910 "before calling RUN_ALL_TESTS(). Please fix it.\n");
3914 // Do not run any test if the --help flag was specified.
3918 // Repeats the call to the post-flag parsing initialization in case the
3919 // user didn't call InitGoogleTest.
3920 PostFlagParsingInit();
3922 // Even if sharding is not on, test runners may want to use the
3923 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3925 internal::WriteToShardStatusFileIfNeeded();
3927 // True iff we are in a subprocess for running a thread-safe-style
3929 bool in_subprocess_for_death_test = false;
3931 #if GTEST_HAS_DEATH_TEST
3932 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3933 #endif // GTEST_HAS_DEATH_TEST
3935 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3936 in_subprocess_for_death_test);
3938 // Compares the full test names with the filter to decide which
3940 const bool has_tests_to_run = FilterTests(should_shard
3941 ? HONOR_SHARDING_PROTOCOL
3942 : IGNORE_SHARDING_PROTOCOL) > 0;
3944 // Lists the tests and exits if the --gtest_list_tests flag was specified.
3945 if (GTEST_FLAG(list_tests)) {
3946 // This must be called *after* FilterTests() has been called.
3947 ListTestsMatchingFilter();
3951 random_seed_ = GTEST_FLAG(shuffle) ?
3952 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3954 // True iff at least one test has failed.
3955 bool failed = false;
3957 TestEventListener* repeater = listeners()->repeater();
3959 repeater->OnTestProgramStart(*parent_);
3961 // How many times to repeat the tests? We don't want to repeat them
3962 // when we are inside the subprocess of a death test.
3963 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3964 // Repeats forever if the repeat count is negative.
3965 const bool forever = repeat < 0;
3966 for (int i = 0; forever || i != repeat; i++) {
3969 const TimeInMillis start = GetTimeInMillis();
3971 // Shuffles test cases and tests if requested.
3972 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
3973 random()->Reseed(random_seed_);
3974 // This should be done before calling OnTestIterationStart(),
3975 // such that a test event listener can see the actual test order
3980 // Tells the unit test event listeners that the tests are about to start.
3981 repeater->OnTestIterationStart(*parent_, i);
3983 // Runs each test case if there is at least one test to run.
3984 if (has_tests_to_run) {
3985 // Sets up all environments beforehand.
3986 repeater->OnEnvironmentsSetUpStart(*parent_);
3987 ForEach(environments_, SetUpEnvironment);
3988 repeater->OnEnvironmentsSetUpEnd(*parent_);
3990 // Runs the tests only if there was no fatal failure during global
3992 if (!Test::HasFatalFailure()) {
3993 for (int test_index = 0; test_index < total_test_case_count();
3995 GetMutableTestCase(test_index)->Run();
3999 // Tears down all environments in reverse order afterwards.
4000 repeater->OnEnvironmentsTearDownStart(*parent_);
4001 std::for_each(environments_.rbegin(), environments_.rend(),
4002 TearDownEnvironment);
4003 repeater->OnEnvironmentsTearDownEnd(*parent_);
4006 elapsed_time_ = GetTimeInMillis() - start;
4008 // Tells the unit test event listener that the tests have just finished.
4009 repeater->OnTestIterationEnd(*parent_, i);
4011 // Gets the result and clears it.
4016 // Restores the original test order after the iteration. This
4017 // allows the user to quickly repro a failure that happens in the
4018 // N-th iteration without repeating the first (N - 1) iterations.
4019 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4020 // case the user somehow changes the value of the flag somewhere
4021 // (it's always safe to unshuffle the tests).
4024 if (GTEST_FLAG(shuffle)) {
4025 // Picks a new random seed for each iteration.
4026 random_seed_ = GetNextRandomSeed(random_seed_);
4030 repeater->OnTestProgramEnd(*parent_);
4032 // Returns 0 if all tests passed, or 1 other wise.
4033 return failed ? 1 : 0;
4036 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4037 // if the variable is present. If a file already exists at this location, this
4038 // function will write over it. If the variable is present, but the file cannot
4039 // be created, prints an error and exits.
4040 void WriteToShardStatusFileIfNeeded() {
4041 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4042 if (test_shard_file != NULL) {
4043 FILE* const file = posix::FOpen(test_shard_file, "w");
4045 ColoredPrintf(COLOR_RED,
4046 "Could not write to the test shard status file \"%s\" "
4047 "specified by the %s environment variable.\n",
4048 test_shard_file, kTestShardStatusFile);
4056 // Checks whether sharding is enabled by examining the relevant
4057 // environment variable values. If the variables are present,
4058 // but inconsistent (i.e., shard_index >= total_shards), prints
4059 // an error and exits. If in_subprocess_for_death_test, sharding is
4060 // disabled because it must only be applied to the original test
4061 // process. Otherwise, we could filter out death tests we intended to execute.
4062 bool ShouldShard(const char* total_shards_env,
4063 const char* shard_index_env,
4064 bool in_subprocess_for_death_test) {
4065 if (in_subprocess_for_death_test) {
4069 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4070 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4072 if (total_shards == -1 && shard_index == -1) {
4074 } else if (total_shards == -1 && shard_index != -1) {
4075 const Message msg = Message()
4076 << "Invalid environment variables: you have "
4077 << kTestShardIndex << " = " << shard_index
4078 << ", but have left " << kTestTotalShards << " unset.\n";
4079 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4082 } else if (total_shards != -1 && shard_index == -1) {
4083 const Message msg = Message()
4084 << "Invalid environment variables: you have "
4085 << kTestTotalShards << " = " << total_shards
4086 << ", but have left " << kTestShardIndex << " unset.\n";
4087 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4090 } else if (shard_index < 0 || shard_index >= total_shards) {
4091 const Message msg = Message()
4092 << "Invalid environment variables: we require 0 <= "
4093 << kTestShardIndex << " < " << kTestTotalShards
4094 << ", but you have " << kTestShardIndex << "=" << shard_index
4095 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4096 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4101 return total_shards > 1;
4104 // Parses the environment variable var as an Int32. If it is unset,
4105 // returns default_val. If it is not an Int32, prints an error
4107 Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
4108 const char* str_val = posix::GetEnv(var);
4109 if (str_val == NULL) {
4114 if (!ParseInt32(Message() << "The value of environment variable " << var,
4115 str_val, &result)) {
4121 // Given the total number of shards, the shard index, and the test id,
4122 // returns true iff the test should be run on this shard. The test id is
4123 // some arbitrary but unique non-negative integer assigned to each test
4124 // method. Assumes that 0 <= shard_index < total_shards.
4125 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4126 return (test_id % total_shards) == shard_index;
4129 // Compares the name of each test with the user-specified filter to
4130 // decide whether the test should be run, then records the result in
4131 // each TestCase and TestInfo object.
4132 // If shard_tests == true, further filters tests based on sharding
4133 // variables in the environment - see
4134 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4135 // Returns the number of tests that should run.
4136 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4137 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4138 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4139 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4140 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4142 // num_runnable_tests are the number of tests that will
4143 // run across all shards (i.e., match filter and are not disabled).
4144 // num_selected_tests are the number of tests to be run on
4146 int num_runnable_tests = 0;
4147 int num_selected_tests = 0;
4148 for (size_t i = 0; i < test_cases_.size(); i++) {
4149 TestCase* const test_case = test_cases_[i];
4150 const String &test_case_name = test_case->name();
4151 test_case->set_should_run(false);
4153 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4154 TestInfo* const test_info = test_case->test_info_list()[j];
4155 const String test_name(test_info->name());
4156 // A test is disabled if test case name or test name matches
4157 // kDisableTestFilter.
4158 const bool is_disabled =
4159 internal::UnitTestOptions::MatchesFilter(test_case_name,
4160 kDisableTestFilter) ||
4161 internal::UnitTestOptions::MatchesFilter(test_name,
4162 kDisableTestFilter);
4163 test_info->impl()->set_is_disabled(is_disabled);
4165 const bool matches_filter =
4166 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4168 test_info->impl()->set_matches_filter(matches_filter);
4170 const bool is_runnable =
4171 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4174 const bool is_selected = is_runnable &&
4175 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4176 ShouldRunTestOnShard(total_shards, shard_index,
4177 num_runnable_tests));
4179 num_runnable_tests += is_runnable;
4180 num_selected_tests += is_selected;
4182 test_info->impl()->set_should_run(is_selected);
4183 test_case->set_should_run(test_case->should_run() || is_selected);
4186 return num_selected_tests;
4189 // Prints the names of the tests matching the user-specified filter flag.
4190 void UnitTestImpl::ListTestsMatchingFilter() {
4191 for (size_t i = 0; i < test_cases_.size(); i++) {
4192 const TestCase* const test_case = test_cases_[i];
4193 bool printed_test_case_name = false;
4195 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4196 const TestInfo* const test_info =
4197 test_case->test_info_list()[j];
4198 if (test_info->matches_filter()) {
4199 if (!printed_test_case_name) {
4200 printed_test_case_name = true;
4201 printf("%s.\n", test_case->name());
4203 printf(" %s\n", test_info->name());
4210 // Sets the OS stack trace getter.
4212 // Does nothing if the input and the current OS stack trace getter are
4213 // the same; otherwise, deletes the old getter and makes the input the
4215 void UnitTestImpl::set_os_stack_trace_getter(
4216 OsStackTraceGetterInterface* getter) {
4217 if (os_stack_trace_getter_ != getter) {
4218 delete os_stack_trace_getter_;
4219 os_stack_trace_getter_ = getter;
4223 // Returns the current OS stack trace getter if it is not NULL;
4224 // otherwise, creates an OsStackTraceGetter, makes it the current
4225 // getter, and returns it.
4226 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4227 if (os_stack_trace_getter_ == NULL) {
4228 os_stack_trace_getter_ = new OsStackTraceGetter;
4231 return os_stack_trace_getter_;
4234 // Returns the TestResult for the test that's currently running, or
4235 // the TestResult for the ad hoc test if no test is running.
4236 TestResult* UnitTestImpl::current_test_result() {
4237 return current_test_info_ ?
4238 current_test_info_->impl()->result() : &ad_hoc_test_result_;
4241 // Shuffles all test cases, and the tests within each test case,
4242 // making sure that death tests are still run first.
4243 void UnitTestImpl::ShuffleTests() {
4244 // Shuffles the death test cases.
4245 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4247 // Shuffles the non-death test cases.
4248 ShuffleRange(random(), last_death_test_case_ + 1,
4249 static_cast<int>(test_cases_.size()), &test_case_indices_);
4251 // Shuffles the tests inside each test case.
4252 for (size_t i = 0; i < test_cases_.size(); i++) {
4253 test_cases_[i]->ShuffleTests(random());
4257 // Restores the test cases and tests to their order before the first shuffle.
4258 void UnitTestImpl::UnshuffleTests() {
4259 for (size_t i = 0; i < test_cases_.size(); i++) {
4260 // Unshuffles the tests in each test case.
4261 test_cases_[i]->UnshuffleTests();
4262 // Resets the index of each test case.
4263 test_case_indices_[i] = static_cast<int>(i);
4267 // TestInfoImpl constructor. The new instance assumes ownership of the test
4269 TestInfoImpl::TestInfoImpl(TestInfo* parent,
4270 const char* a_test_case_name,
4272 const char* a_test_case_comment,
4273 const char* a_comment,
4274 TypeId a_fixture_class_id,
4275 internal::TestFactoryBase* factory) :
4277 test_case_name_(String(a_test_case_name)),
4278 name_(String(a_name)),
4279 test_case_comment_(String(a_test_case_comment)),
4280 comment_(String(a_comment)),
4281 fixture_class_id_(a_fixture_class_id),
4283 is_disabled_(false),
4284 matches_filter_(false),
4288 // TestInfoImpl destructor.
4289 TestInfoImpl::~TestInfoImpl() {
4293 // Returns the current OS stack trace as a String.
4295 // The maximum number of stack frames to be included is specified by
4296 // the gtest_stack_trace_depth flag. The skip_count parameter
4297 // specifies the number of top frames to be skipped, which doesn't
4298 // count against the number of frames to be included.
4300 // For example, if Foo() calls Bar(), which in turn calls
4301 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4302 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4303 String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4305 // We pass skip_count + 1 to skip this wrapper function in addition
4306 // to what the user really wants to skip.
4307 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4310 // Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4313 class ClassUniqueToAlwaysTrue {};
4316 bool IsTrue(bool condition) { return condition; }
4319 #if GTEST_HAS_EXCEPTIONS
4320 // This condition is always false so AlwaysTrue() never actually throws,
4321 // but it makes the compiler think that it may throw.
4323 throw ClassUniqueToAlwaysTrue();
4324 #endif // GTEST_HAS_EXCEPTIONS
4328 // If *pstr starts with the given prefix, modifies *pstr to be right
4329 // past the prefix and returns true; otherwise leaves *pstr unchanged
4330 // and returns false. None of pstr, *pstr, and prefix can be NULL.
4331 bool SkipPrefix(const char* prefix, const char** pstr) {
4332 const size_t prefix_len = strlen(prefix);
4333 if (strncmp(*pstr, prefix, prefix_len) == 0) {
4334 *pstr += prefix_len;
4340 // Parses a string as a command line flag. The string should have
4341 // the format "--flag=value". When def_optional is true, the "=value"
4342 // part can be omitted.
4344 // Returns the value of the flag, or NULL if the parsing failed.
4345 const char* ParseFlagValue(const char* str,
4347 bool def_optional) {
4348 // str and flag must not be NULL.
4349 if (str == NULL || flag == NULL) return NULL;
4351 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4352 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
4353 const size_t flag_len = flag_str.length();
4354 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4356 // Skips the flag name.
4357 const char* flag_end = str + flag_len;
4359 // When def_optional is true, it's OK to not have a "=value" part.
4360 if (def_optional && (flag_end[0] == '\0')) {
4364 // If def_optional is true and there are more characters after the
4365 // flag name, or if def_optional is false, there must be a '=' after
4367 if (flag_end[0] != '=') return NULL;
4369 // Returns the string after "=".
4370 return flag_end + 1;
4373 // Parses a string for a bool flag, in the form of either
4374 // "--flag=value" or "--flag".
4376 // In the former case, the value is taken as true as long as it does
4377 // not start with '0', 'f', or 'F'.
4379 // In the latter case, the value is taken as true.
4381 // On success, stores the value of the flag in *value, and returns
4382 // true. On failure, returns false without changing *value.
4383 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4384 // Gets the value of the flag as a string.
4385 const char* const value_str = ParseFlagValue(str, flag, true);
4387 // Aborts if the parsing failed.
4388 if (value_str == NULL) return false;
4390 // Converts the string value to a bool.
4391 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4395 // Parses a string for an Int32 flag, in the form of
4398 // On success, stores the value of the flag in *value, and returns
4399 // true. On failure, returns false without changing *value.
4400 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4401 // Gets the value of the flag as a string.
4402 const char* const value_str = ParseFlagValue(str, flag, false);
4404 // Aborts if the parsing failed.
4405 if (value_str == NULL) return false;
4407 // Sets *value to the value of the flag.
4408 return ParseInt32(Message() << "The value of flag --" << flag,
4412 // Parses a string for a string flag, in the form of
4415 // On success, stores the value of the flag in *value, and returns
4416 // true. On failure, returns false without changing *value.
4417 bool ParseStringFlag(const char* str, const char* flag, String* value) {
4418 // Gets the value of the flag as a string.
4419 const char* const value_str = ParseFlagValue(str, flag, false);
4421 // Aborts if the parsing failed.
4422 if (value_str == NULL) return false;
4424 // Sets *value to the value of the flag.
4429 // Determines whether a string has a prefix that Google Test uses for its
4430 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
4431 // If Google Test detects that a command line flag has its prefix but is not
4432 // recognized, it will print its help message. Flags starting with
4433 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
4434 // internal flags and do not trigger the help message.
4435 static bool HasGoogleTestFlagPrefix(const char* str) {
4436 return (SkipPrefix("--", &str) ||
4437 SkipPrefix("-", &str) ||
4438 SkipPrefix("/", &str)) &&
4439 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
4440 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
4441 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
4444 // Prints a string containing code-encoded text. The following escape
4445 // sequences can be used in the string to control the text color:
4447 // @@ prints a single '@' character.
4448 // @R changes the color to red.
4449 // @G changes the color to green.
4450 // @Y changes the color to yellow.
4451 // @D changes to the default terminal text color.
4453 // TODO(wan@google.com): Write tests for this once we add stdout
4454 // capturing to Google Test.
4455 static void PrintColorEncoded(const char* str) {
4456 GTestColor color = COLOR_DEFAULT; // The current color.
4458 // Conceptually, we split the string into segments divided by escape
4459 // sequences. Then we print one segment at a time. At the end of
4460 // each iteration, the str pointer advances to the beginning of the
4463 const char* p = strchr(str, '@');
4465 ColoredPrintf(color, "%s", str);
4469 ColoredPrintf(color, "%s", String(str, p - str).c_str());
4471 const char ch = p[1];
4474 ColoredPrintf(color, "@");
4475 } else if (ch == 'D') {
4476 color = COLOR_DEFAULT;
4477 } else if (ch == 'R') {
4479 } else if (ch == 'G') {
4480 color = COLOR_GREEN;
4481 } else if (ch == 'Y') {
4482 color = COLOR_YELLOW;
4489 static const char kColorEncodedHelpMessage[] =
4490 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4491 "following command line flags to control its behavior:\n"
4494 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4495 " List the names of all tests instead of running them. The name of\n"
4496 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
4497 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4498 "[@G-@YNEGATIVE_PATTERNS]@D\n"
4499 " Run only the tests whose name matches one of the positive patterns but\n"
4500 " none of the negative patterns. '?' matches any single character; '*'\n"
4501 " matches any substring; ':' separates two patterns.\n"
4502 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4503 " Run all disabled tests too.\n"
4506 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4507 " Run the tests repeatedly; use a negative count to repeat forever.\n"
4508 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4509 " Randomize tests' orders on every iteration.\n"
4510 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4511 " Random number seed to use for shuffling test orders (between 1 and\n"
4512 " 99999, or 0 to use a seed based on the current time).\n"
4515 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4516 " Enable/disable colored output. The default is @Gauto@D.\n"
4517 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4518 " Don't print the elapsed time of each test.\n"
4519 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4520 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4521 " Generate an XML report in the given directory or with the given file\n"
4522 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4524 "Assertion Behavior:\n"
4525 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4526 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4527 " Set the default death test style.\n"
4528 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4529 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4530 " Turn assertion failures into debugger break-points.\n"
4531 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4532 " Turn assertion failures into C++ exceptions.\n"
4533 #if GTEST_OS_WINDOWS
4534 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4535 " Suppress pop-ups caused by exceptions.\n"
4536 #endif // GTEST_OS_WINDOWS
4538 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4539 "the corresponding\n"
4540 "environment variable of a flag (all letters in upper-case). For example, to\n"
4541 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4542 "color=no@D or set\n"
4543 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
4545 "For more information, please read the " GTEST_NAME_ " documentation at\n"
4546 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4547 "(not one in your own code or tests), please report it to\n"
4548 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4550 // Parses the command line for Google Test flags, without initializing
4551 // other parts of Google Test. The type parameter CharType can be
4552 // instantiated to either char or wchar_t.
4553 template <typename CharType>
4554 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4555 for (int i = 1; i < *argc; i++) {
4556 const String arg_string = StreamableToString(argv[i]);
4557 const char* const arg = arg_string.c_str();
4559 using internal::ParseBoolFlag;
4560 using internal::ParseInt32Flag;
4561 using internal::ParseStringFlag;
4563 // Do we see a Google Test flag?
4564 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4565 >EST_FLAG(also_run_disabled_tests)) ||
4566 ParseBoolFlag(arg, kBreakOnFailureFlag,
4567 >EST_FLAG(break_on_failure)) ||
4568 ParseBoolFlag(arg, kCatchExceptionsFlag,
4569 >EST_FLAG(catch_exceptions)) ||
4570 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
4571 ParseStringFlag(arg, kDeathTestStyleFlag,
4572 >EST_FLAG(death_test_style)) ||
4573 ParseBoolFlag(arg, kDeathTestUseFork,
4574 >EST_FLAG(death_test_use_fork)) ||
4575 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
4576 ParseStringFlag(arg, kInternalRunDeathTestFlag,
4577 >EST_FLAG(internal_run_death_test)) ||
4578 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
4579 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
4580 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
4581 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
4582 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
4583 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
4584 ParseInt32Flag(arg, kStackTraceDepthFlag,
4585 >EST_FLAG(stack_trace_depth)) ||
4586 ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure))
4588 // Yes. Shift the remainder of the argv list left by one. Note
4589 // that argv has (*argc + 1) elements, the last one always being
4590 // NULL. The following loop moves the trailing NULL element as
4592 for (int j = i; j != *argc; j++) {
4593 argv[j] = argv[j + 1];
4596 // Decrements the argument count.
4599 // We also need to decrement the iterator as we just removed
4602 } else if (arg_string == "--help" || arg_string == "-h" ||
4603 arg_string == "-?" || arg_string == "/?" ||
4604 HasGoogleTestFlagPrefix(arg)) {
4605 // Both help flag and unrecognized Google Test flags (excluding
4606 // internal ones) trigger help display.
4612 // We print the help here instead of in RUN_ALL_TESTS(), as the
4613 // latter may not be called at all if the user is using Google
4614 // Test with another testing framework.
4615 PrintColorEncoded(kColorEncodedHelpMessage);
4619 // Parses the command line for Google Test flags, without initializing
4620 // other parts of Google Test.
4621 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4622 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4624 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4625 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4628 // The internal implementation of InitGoogleTest().
4630 // The type parameter CharType can be instantiated to either char or
4632 template <typename CharType>
4633 void InitGoogleTestImpl(int* argc, CharType** argv) {
4634 g_init_gtest_count++;
4636 // We don't want to run the initialization code twice.
4637 if (g_init_gtest_count != 1) return;
4639 if (*argc <= 0) return;
4641 internal::g_executable_path = internal::StreamableToString(argv[0]);
4643 #if GTEST_HAS_DEATH_TEST
4645 for (int i = 0; i != *argc; i++) {
4646 g_argvs.push_back(StreamableToString(argv[i]));
4648 #endif // GTEST_HAS_DEATH_TEST
4650 ParseGoogleTestFlagsOnly(argc, argv);
4651 GetUnitTestImpl()->PostFlagParsingInit();
4654 } // namespace internal
4656 // Initializes Google Test. This must be called before calling
4657 // RUN_ALL_TESTS(). In particular, it parses a command line for the
4658 // flags that Google Test recognizes. Whenever a Google Test flag is
4659 // seen, it is removed from argv, and *argc is decremented.
4661 // No value is returned. Instead, the Google Test flag variables are
4664 // Calling the function for the second time has no user-visible effect.
4665 void InitGoogleTest(int* argc, char** argv) {
4666 internal::InitGoogleTestImpl(argc, argv);
4669 // This overloaded version can be used in Windows programs compiled in
4671 void InitGoogleTest(int* argc, wchar_t** argv) {
4672 internal::InitGoogleTestImpl(argc, argv);
4675 } // namespace testing