michael@0: // Copyright 2005, Google Inc. michael@0: // All rights reserved. michael@0: // michael@0: // Redistribution and use in source and binary forms, with or without michael@0: // modification, are permitted provided that the following conditions are michael@0: // met: michael@0: // michael@0: // * Redistributions of source code must retain the above copyright michael@0: // notice, this list of conditions and the following disclaimer. michael@0: // * Redistributions in binary form must reproduce the above michael@0: // copyright notice, this list of conditions and the following disclaimer michael@0: // in the documentation and/or other materials provided with the michael@0: // distribution. michael@0: // * Neither the name of Google Inc. nor the names of its michael@0: // contributors may be used to endorse or promote products derived from michael@0: // this software without specific prior written permission. michael@0: // michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: // michael@0: // Author: wan@google.com (Zhanyong Wan) michael@0: // michael@0: // The Google C++ Testing Framework (Google Test) michael@0: michael@0: #include "gtest/gtest.h" michael@0: #include "gtest/gtest-spi.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include // NOLINT michael@0: #include michael@0: #include michael@0: michael@0: #if GTEST_OS_LINUX michael@0: michael@0: // TODO(kenton@google.com): Use autoconf to detect availability of michael@0: // gettimeofday(). michael@0: # define GTEST_HAS_GETTIMEOFDAY_ 1 michael@0: michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: // Declares vsnprintf(). This header is not available on Windows. michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include michael@0: michael@0: #elif GTEST_OS_SYMBIAN michael@0: # define GTEST_HAS_GETTIMEOFDAY_ 1 michael@0: # include // NOLINT michael@0: michael@0: #elif GTEST_OS_ZOS michael@0: # define GTEST_HAS_GETTIMEOFDAY_ 1 michael@0: # include // NOLINT michael@0: michael@0: // On z/OS we additionally need strings.h for strcasecmp. michael@0: # include // NOLINT michael@0: michael@0: #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. michael@0: michael@0: # include // NOLINT michael@0: michael@0: #elif GTEST_OS_WINDOWS // We are on Windows proper. michael@0: michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: michael@0: # if GTEST_OS_WINDOWS_MINGW michael@0: // MinGW has gettimeofday() but not _ftime64(). michael@0: // TODO(kenton@google.com): Use autoconf to detect availability of michael@0: // gettimeofday(). michael@0: // TODO(kenton@google.com): There are other ways to get the time on michael@0: // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW michael@0: // supports these. consider using them instead. michael@0: # define GTEST_HAS_GETTIMEOFDAY_ 1 michael@0: # include // NOLINT michael@0: # endif // GTEST_OS_WINDOWS_MINGW michael@0: michael@0: // cpplint thinks that the header is already included, so we want to michael@0: // silence it. michael@0: # include // NOLINT michael@0: michael@0: #else michael@0: michael@0: // Assume other platforms have gettimeofday(). michael@0: // TODO(kenton@google.com): Use autoconf to detect availability of michael@0: // gettimeofday(). michael@0: # define GTEST_HAS_GETTIMEOFDAY_ 1 michael@0: michael@0: // cpplint thinks that the header is already included, so we want to michael@0: // silence it. michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: michael@0: #endif // GTEST_OS_LINUX michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: # include michael@0: #endif michael@0: michael@0: #if GTEST_CAN_STREAM_RESULTS_ michael@0: # include // NOLINT michael@0: # include // NOLINT michael@0: #endif michael@0: michael@0: // Indicates that this translation unit is part of Google Test's michael@0: // implementation. It must come before gtest-internal-inl.h is michael@0: // included, or there will be a compiler error. This trick is to michael@0: // prevent a user from accidentally including gtest-internal-inl.h in michael@0: // his code. michael@0: #define GTEST_IMPLEMENTATION_ 1 michael@0: #include "src/gtest-internal-inl.h" michael@0: #undef GTEST_IMPLEMENTATION_ michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: # define vsnprintf _vsnprintf michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: namespace testing { michael@0: michael@0: using internal::CountIf; michael@0: using internal::ForEach; michael@0: using internal::GetElementOr; michael@0: using internal::Shuffle; michael@0: michael@0: // Constants. michael@0: michael@0: // A test whose test case name or test name matches this filter is michael@0: // disabled and not run. michael@0: static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; michael@0: michael@0: // A test case whose name matches this filter is considered a death michael@0: // test case and will be run before test cases whose name doesn't michael@0: // match this filter. michael@0: static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; michael@0: michael@0: // A test filter that matches everything. michael@0: static const char kUniversalFilter[] = "*"; michael@0: michael@0: // The default output file for XML output. michael@0: static const char kDefaultOutputFile[] = "test_detail.xml"; michael@0: michael@0: // The environment variable name for the test shard index. michael@0: static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; michael@0: // The environment variable name for the total number of test shards. michael@0: static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; michael@0: // The environment variable name for the test shard status file. michael@0: static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; michael@0: michael@0: namespace internal { michael@0: michael@0: // The text used in failure messages to indicate the start of the michael@0: // stack trace. michael@0: const char kStackTraceMarker[] = "\nStack trace:\n"; michael@0: michael@0: // g_help_flag is true iff the --help flag or an equivalent form is michael@0: // specified on the command line. michael@0: bool g_help_flag = false; michael@0: michael@0: } // namespace internal michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: also_run_disabled_tests, michael@0: internal::BoolFromGTestEnv("also_run_disabled_tests", false), michael@0: "Run disabled tests too, in addition to the tests normally being run."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: break_on_failure, michael@0: internal::BoolFromGTestEnv("break_on_failure", false), michael@0: "True iff a failed assertion should be a debugger break-point."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: catch_exceptions, michael@0: internal::BoolFromGTestEnv("catch_exceptions", true), michael@0: "True iff " GTEST_NAME_ michael@0: " should catch exceptions and treat them as test failures."); michael@0: michael@0: GTEST_DEFINE_string_( michael@0: color, michael@0: internal::StringFromGTestEnv("color", "auto"), michael@0: "Whether to use colors in the output. Valid values: yes, no, " michael@0: "and auto. 'auto' means to use colors if the output is " michael@0: "being sent to a terminal and the TERM environment variable " michael@0: "is set to xterm, xterm-color, xterm-256color, linux or cygwin."); michael@0: michael@0: GTEST_DEFINE_string_( michael@0: filter, michael@0: internal::StringFromGTestEnv("filter", kUniversalFilter), michael@0: "A colon-separated list of glob (not regex) patterns " michael@0: "for filtering the tests to run, optionally followed by a " michael@0: "'-' and a : separated list of negative patterns (tests to " michael@0: "exclude). A test is run if it matches one of the positive " michael@0: "patterns and does not match any of the negative patterns."); michael@0: michael@0: GTEST_DEFINE_bool_(list_tests, false, michael@0: "List all tests without running them."); michael@0: michael@0: GTEST_DEFINE_string_( michael@0: output, michael@0: internal::StringFromGTestEnv("output", ""), michael@0: "A format (currently must be \"xml\"), optionally followed " michael@0: "by a colon and an output file name or directory. A directory " michael@0: "is indicated by a trailing pathname separator. " michael@0: "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " michael@0: "If a directory is specified, output files will be created " michael@0: "within that directory, with file-names based on the test " michael@0: "executable's name and, if necessary, made unique by adding " michael@0: "digits."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: print_time, michael@0: internal::BoolFromGTestEnv("print_time", true), michael@0: "True iff " GTEST_NAME_ michael@0: " should display elapsed time in text output."); michael@0: michael@0: GTEST_DEFINE_int32_( michael@0: random_seed, michael@0: internal::Int32FromGTestEnv("random_seed", 0), michael@0: "Random number seed to use when shuffling test orders. Must be in range " michael@0: "[1, 99999], or 0 to use a seed based on the current time."); michael@0: michael@0: GTEST_DEFINE_int32_( michael@0: repeat, michael@0: internal::Int32FromGTestEnv("repeat", 1), michael@0: "How many times to repeat each test. Specify a negative number " michael@0: "for repeating forever. Useful for shaking out flaky tests."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: show_internal_stack_frames, false, michael@0: "True iff " GTEST_NAME_ " should include internal stack frames when " michael@0: "printing test failure stack traces."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: shuffle, michael@0: internal::BoolFromGTestEnv("shuffle", false), michael@0: "True iff " GTEST_NAME_ michael@0: " should randomize tests' order on every run."); michael@0: michael@0: GTEST_DEFINE_int32_( michael@0: stack_trace_depth, michael@0: internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), michael@0: "The maximum number of stack frames to print when an " michael@0: "assertion fails. The valid range is 0 through 100, inclusive."); michael@0: michael@0: GTEST_DEFINE_string_( michael@0: stream_result_to, michael@0: internal::StringFromGTestEnv("stream_result_to", ""), michael@0: "This flag specifies the host name and the port number on which to stream " michael@0: "test results. Example: \"localhost:555\". The flag is effective only on " michael@0: "Linux."); michael@0: michael@0: GTEST_DEFINE_bool_( michael@0: throw_on_failure, michael@0: internal::BoolFromGTestEnv("throw_on_failure", false), michael@0: "When this flag is specified, a failed assertion will throw an exception " michael@0: "if exceptions are enabled or exit the program with a non-zero code " michael@0: "otherwise."); michael@0: michael@0: namespace internal { michael@0: michael@0: // Generates a random number from [0, range), using a Linear michael@0: // Congruential Generator (LCG). Crashes if 'range' is 0 or greater michael@0: // than kMaxRange. michael@0: UInt32 Random::Generate(UInt32 range) { michael@0: // These constants are the same as are used in glibc's rand(3). michael@0: state_ = (1103515245U*state_ + 12345U) % kMaxRange; michael@0: michael@0: GTEST_CHECK_(range > 0) michael@0: << "Cannot generate a number in the range [0, 0)."; michael@0: GTEST_CHECK_(range <= kMaxRange) michael@0: << "Generation of a number in [0, " << range << ") was requested, " michael@0: << "but this can only generate numbers in [0, " << kMaxRange << ")."; michael@0: michael@0: // Converting via modulus introduces a bit of downward bias, but michael@0: // it's simple, and a linear congruential generator isn't too good michael@0: // to begin with. michael@0: return state_ % range; michael@0: } michael@0: michael@0: // GTestIsInitialized() returns true iff the user has initialized michael@0: // Google Test. Useful for catching the user mistake of not initializing michael@0: // Google Test before calling RUN_ALL_TESTS(). michael@0: // michael@0: // A user must call testing::InitGoogleTest() to initialize Google michael@0: // Test. g_init_gtest_count is set to the number of times michael@0: // InitGoogleTest() has been called. We don't protect this variable michael@0: // under a mutex as it is only accessed in the main thread. michael@0: GTEST_API_ int g_init_gtest_count = 0; michael@0: static bool GTestIsInitialized() { return g_init_gtest_count != 0; } michael@0: michael@0: // Iterates over a vector of TestCases, keeping a running sum of the michael@0: // results of calling a given int-returning method on each. michael@0: // Returns the sum. michael@0: static int SumOverTestCaseList(const std::vector& case_list, michael@0: int (TestCase::*method)() const) { michael@0: int sum = 0; michael@0: for (size_t i = 0; i < case_list.size(); i++) { michael@0: sum += (case_list[i]->*method)(); michael@0: } michael@0: return sum; michael@0: } michael@0: michael@0: // Returns true iff the test case passed. michael@0: static bool TestCasePassed(const TestCase* test_case) { michael@0: return test_case->should_run() && test_case->Passed(); michael@0: } michael@0: michael@0: // Returns true iff the test case failed. michael@0: static bool TestCaseFailed(const TestCase* test_case) { michael@0: return test_case->should_run() && test_case->Failed(); michael@0: } michael@0: michael@0: // Returns true iff test_case contains at least one test that should michael@0: // run. michael@0: static bool ShouldRunTestCase(const TestCase* test_case) { michael@0: return test_case->should_run(); michael@0: } michael@0: michael@0: // AssertHelper constructor. michael@0: AssertHelper::AssertHelper(TestPartResult::Type type, michael@0: const char* file, michael@0: int line, michael@0: const char* message) michael@0: : data_(new AssertHelperData(type, file, line, message)) { michael@0: } michael@0: michael@0: AssertHelper::~AssertHelper() { michael@0: delete data_; michael@0: } michael@0: michael@0: // Message assignment, for assertion streaming support. michael@0: void AssertHelper::operator=(const Message& message) const { michael@0: UnitTest::GetInstance()-> michael@0: AddTestPartResult(data_->type, data_->file, data_->line, michael@0: AppendUserMessage(data_->message, message), michael@0: UnitTest::GetInstance()->impl() michael@0: ->CurrentOsStackTraceExceptTop(1) michael@0: // Skips the stack frame for this function itself. michael@0: ); // NOLINT michael@0: } michael@0: michael@0: // Mutex for linked pointers. michael@0: GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); michael@0: michael@0: // Application pathname gotten in InitGoogleTest. michael@0: String g_executable_path; michael@0: michael@0: // Returns the current application's name, removing directory path if that michael@0: // is present. michael@0: FilePath GetCurrentExecutableName() { michael@0: FilePath result; michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: result.Set(FilePath(g_executable_path).RemoveExtension("exe")); michael@0: #else michael@0: result.Set(FilePath(g_executable_path)); michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: return result.RemoveDirectoryName(); michael@0: } michael@0: michael@0: // Functions for processing the gtest_output flag. michael@0: michael@0: // Returns the output format, or "" for normal printed output. michael@0: String UnitTestOptions::GetOutputFormat() { michael@0: const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); michael@0: if (gtest_output_flag == NULL) return String(""); michael@0: michael@0: const char* const colon = strchr(gtest_output_flag, ':'); michael@0: return (colon == NULL) ? michael@0: String(gtest_output_flag) : michael@0: String(gtest_output_flag, colon - gtest_output_flag); michael@0: } michael@0: michael@0: // Returns the name of the requested output file, or the default if none michael@0: // was explicitly specified. michael@0: String UnitTestOptions::GetAbsolutePathToOutputFile() { michael@0: const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); michael@0: if (gtest_output_flag == NULL) michael@0: return String(""); michael@0: michael@0: const char* const colon = strchr(gtest_output_flag, ':'); michael@0: if (colon == NULL) michael@0: return String(internal::FilePath::ConcatPaths( michael@0: internal::FilePath( michael@0: UnitTest::GetInstance()->original_working_dir()), michael@0: internal::FilePath(kDefaultOutputFile)).ToString() ); michael@0: michael@0: internal::FilePath output_name(colon + 1); michael@0: if (!output_name.IsAbsolutePath()) michael@0: // TODO(wan@google.com): on Windows \some\path is not an absolute michael@0: // path (as its meaning depends on the current drive), yet the michael@0: // following logic for turning it into an absolute path is wrong. michael@0: // Fix it. michael@0: output_name = internal::FilePath::ConcatPaths( michael@0: internal::FilePath(UnitTest::GetInstance()->original_working_dir()), michael@0: internal::FilePath(colon + 1)); michael@0: michael@0: if (!output_name.IsDirectory()) michael@0: return output_name.ToString(); michael@0: michael@0: internal::FilePath result(internal::FilePath::GenerateUniqueFileName( michael@0: output_name, internal::GetCurrentExecutableName(), michael@0: GetOutputFormat().c_str())); michael@0: return result.ToString(); michael@0: } michael@0: michael@0: // Returns true iff the wildcard pattern matches the string. The michael@0: // first ':' or '\0' character in pattern marks the end of it. michael@0: // michael@0: // This recursive algorithm isn't very efficient, but is clear and michael@0: // works well enough for matching test names, which are short. michael@0: bool UnitTestOptions::PatternMatchesString(const char *pattern, michael@0: const char *str) { michael@0: switch (*pattern) { michael@0: case '\0': michael@0: case ':': // Either ':' or '\0' marks the end of the pattern. michael@0: return *str == '\0'; michael@0: case '?': // Matches any single character. michael@0: return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); michael@0: case '*': // Matches any string (possibly empty) of characters. michael@0: return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || michael@0: PatternMatchesString(pattern + 1, str); michael@0: default: // Non-special character. Matches itself. michael@0: return *pattern == *str && michael@0: PatternMatchesString(pattern + 1, str + 1); michael@0: } michael@0: } michael@0: michael@0: bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { michael@0: const char *cur_pattern = filter; michael@0: for (;;) { michael@0: if (PatternMatchesString(cur_pattern, name.c_str())) { michael@0: return true; michael@0: } michael@0: michael@0: // Finds the next pattern in the filter. michael@0: cur_pattern = strchr(cur_pattern, ':'); michael@0: michael@0: // Returns if no more pattern can be found. michael@0: if (cur_pattern == NULL) { michael@0: return false; michael@0: } michael@0: michael@0: // Skips the pattern separater (the ':' character). michael@0: cur_pattern++; michael@0: } michael@0: } michael@0: michael@0: // TODO(keithray): move String function implementations to gtest-string.cc. michael@0: michael@0: // Returns true iff the user-specified filter matches the test case michael@0: // name and the test name. michael@0: bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, michael@0: const String &test_name) { michael@0: const String& full_name = String::Format("%s.%s", michael@0: test_case_name.c_str(), michael@0: test_name.c_str()); michael@0: michael@0: // Split --gtest_filter at '-', if there is one, to separate into michael@0: // positive filter and negative filter portions michael@0: const char* const p = GTEST_FLAG(filter).c_str(); michael@0: const char* const dash = strchr(p, '-'); michael@0: String positive; michael@0: String negative; michael@0: if (dash == NULL) { michael@0: positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter michael@0: negative = String(""); michael@0: } else { michael@0: positive = String(p, dash - p); // Everything up to the dash michael@0: negative = String(dash+1); // Everything after the dash michael@0: if (positive.empty()) { michael@0: // Treat '-test1' as the same as '*-test1' michael@0: positive = kUniversalFilter; michael@0: } michael@0: } michael@0: michael@0: // A filter is a colon-separated list of patterns. It matches a michael@0: // test if any pattern in it matches the test. michael@0: return (MatchesFilter(full_name, positive.c_str()) && michael@0: !MatchesFilter(full_name, negative.c_str())); michael@0: } michael@0: michael@0: #if GTEST_HAS_SEH michael@0: // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the michael@0: // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. michael@0: // This function is useful as an __except condition. michael@0: int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { michael@0: // Google Test should handle a SEH exception if: michael@0: // 1. the user wants it to, AND michael@0: // 2. this is not a breakpoint exception, AND michael@0: // 3. this is not a C++ exception (VC++ implements them via SEH, michael@0: // apparently). michael@0: // michael@0: // SEH exception code for C++ exceptions. michael@0: // (see http://support.microsoft.com/kb/185294 for more information). michael@0: const DWORD kCxxExceptionCode = 0xe06d7363; michael@0: michael@0: bool should_handle = true; michael@0: michael@0: if (!GTEST_FLAG(catch_exceptions)) michael@0: should_handle = false; michael@0: else if (exception_code == EXCEPTION_BREAKPOINT) michael@0: should_handle = false; michael@0: else if (exception_code == kCxxExceptionCode) michael@0: should_handle = false; michael@0: michael@0: return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; michael@0: } michael@0: #endif // GTEST_HAS_SEH michael@0: michael@0: } // namespace internal michael@0: michael@0: // The c'tor sets this object as the test part result reporter used by michael@0: // Google Test. The 'result' parameter specifies where to report the michael@0: // results. Intercepts only failures from the current thread. michael@0: ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( michael@0: TestPartResultArray* result) michael@0: : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), michael@0: result_(result) { michael@0: Init(); michael@0: } michael@0: michael@0: // The c'tor sets this object as the test part result reporter used by michael@0: // Google Test. The 'result' parameter specifies where to report the michael@0: // results. michael@0: ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( michael@0: InterceptMode intercept_mode, TestPartResultArray* result) michael@0: : intercept_mode_(intercept_mode), michael@0: result_(result) { michael@0: Init(); michael@0: } michael@0: michael@0: void ScopedFakeTestPartResultReporter::Init() { michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: if (intercept_mode_ == INTERCEPT_ALL_THREADS) { michael@0: old_reporter_ = impl->GetGlobalTestPartResultReporter(); michael@0: impl->SetGlobalTestPartResultReporter(this); michael@0: } else { michael@0: old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); michael@0: impl->SetTestPartResultReporterForCurrentThread(this); michael@0: } michael@0: } michael@0: michael@0: // The d'tor restores the test part result reporter used by Google Test michael@0: // before. michael@0: ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: if (intercept_mode_ == INTERCEPT_ALL_THREADS) { michael@0: impl->SetGlobalTestPartResultReporter(old_reporter_); michael@0: } else { michael@0: impl->SetTestPartResultReporterForCurrentThread(old_reporter_); michael@0: } michael@0: } michael@0: michael@0: // Increments the test part result count and remembers the result. michael@0: // This method is from the TestPartResultReporterInterface interface. michael@0: void ScopedFakeTestPartResultReporter::ReportTestPartResult( michael@0: const TestPartResult& result) { michael@0: result_->Append(result); michael@0: } michael@0: michael@0: namespace internal { michael@0: michael@0: // Returns the type ID of ::testing::Test. We should always call this michael@0: // instead of GetTypeId< ::testing::Test>() to get the type ID of michael@0: // testing::Test. This is to work around a suspected linker bug when michael@0: // using Google Test as a framework on Mac OS X. The bug causes michael@0: // GetTypeId< ::testing::Test>() to return different values depending michael@0: // on whether the call is from the Google Test framework itself or michael@0: // from user test code. GetTestTypeId() is guaranteed to always michael@0: // return the same value, as it always calls GetTypeId<>() from the michael@0: // gtest.cc, which is within the Google Test framework. michael@0: TypeId GetTestTypeId() { michael@0: return GetTypeId(); michael@0: } michael@0: michael@0: // The value of GetTestTypeId() as seen from within the Google Test michael@0: // library. This is solely for testing GetTestTypeId(). michael@0: extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); michael@0: michael@0: // This predicate-formatter checks that 'results' contains a test part michael@0: // failure of the given type and that the failure message contains the michael@0: // given substring. michael@0: AssertionResult HasOneFailure(const char* /* results_expr */, michael@0: const char* /* type_expr */, michael@0: const char* /* substr_expr */, michael@0: const TestPartResultArray& results, michael@0: TestPartResult::Type type, michael@0: const string& substr) { michael@0: const String expected(type == TestPartResult::kFatalFailure ? michael@0: "1 fatal failure" : michael@0: "1 non-fatal failure"); michael@0: Message msg; michael@0: if (results.size() != 1) { michael@0: msg << "Expected: " << expected << "\n" michael@0: << " Actual: " << results.size() << " failures"; michael@0: for (int i = 0; i < results.size(); i++) { michael@0: msg << "\n" << results.GetTestPartResult(i); michael@0: } michael@0: return AssertionFailure() << msg; michael@0: } michael@0: michael@0: const TestPartResult& r = results.GetTestPartResult(0); michael@0: if (r.type() != type) { michael@0: return AssertionFailure() << "Expected: " << expected << "\n" michael@0: << " Actual:\n" michael@0: << r; michael@0: } michael@0: michael@0: if (strstr(r.message(), substr.c_str()) == NULL) { michael@0: return AssertionFailure() << "Expected: " << expected << " containing \"" michael@0: << substr << "\"\n" michael@0: << " Actual:\n" michael@0: << r; michael@0: } michael@0: michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: // The constructor of SingleFailureChecker remembers where to look up michael@0: // test part results, what type of failure we expect, and what michael@0: // substring the failure message should contain. michael@0: SingleFailureChecker:: SingleFailureChecker( michael@0: const TestPartResultArray* results, michael@0: TestPartResult::Type type, michael@0: const string& substr) michael@0: : results_(results), michael@0: type_(type), michael@0: substr_(substr) {} michael@0: michael@0: // The destructor of SingleFailureChecker verifies that the given michael@0: // TestPartResultArray contains exactly one failure that has the given michael@0: // type and contains the given substring. If that's not the case, a michael@0: // non-fatal failure will be generated. michael@0: SingleFailureChecker::~SingleFailureChecker() { michael@0: EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); michael@0: } michael@0: michael@0: DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( michael@0: UnitTestImpl* unit_test) : unit_test_(unit_test) {} michael@0: michael@0: void DefaultGlobalTestPartResultReporter::ReportTestPartResult( michael@0: const TestPartResult& result) { michael@0: unit_test_->current_test_result()->AddTestPartResult(result); michael@0: unit_test_->listeners()->repeater()->OnTestPartResult(result); michael@0: } michael@0: michael@0: DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( michael@0: UnitTestImpl* unit_test) : unit_test_(unit_test) {} michael@0: michael@0: void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( michael@0: const TestPartResult& result) { michael@0: unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); michael@0: } michael@0: michael@0: // Returns the global test part result reporter. michael@0: TestPartResultReporterInterface* michael@0: UnitTestImpl::GetGlobalTestPartResultReporter() { michael@0: internal::MutexLock lock(&global_test_part_result_reporter_mutex_); michael@0: return global_test_part_result_repoter_; michael@0: } michael@0: michael@0: // Sets the global test part result reporter. michael@0: void UnitTestImpl::SetGlobalTestPartResultReporter( michael@0: TestPartResultReporterInterface* reporter) { michael@0: internal::MutexLock lock(&global_test_part_result_reporter_mutex_); michael@0: global_test_part_result_repoter_ = reporter; michael@0: } michael@0: michael@0: // Returns the test part result reporter for the current thread. michael@0: TestPartResultReporterInterface* michael@0: UnitTestImpl::GetTestPartResultReporterForCurrentThread() { michael@0: return per_thread_test_part_result_reporter_.get(); michael@0: } michael@0: michael@0: // Sets the test part result reporter for the current thread. michael@0: void UnitTestImpl::SetTestPartResultReporterForCurrentThread( michael@0: TestPartResultReporterInterface* reporter) { michael@0: per_thread_test_part_result_reporter_.set(reporter); michael@0: } michael@0: michael@0: // Gets the number of successful test cases. michael@0: int UnitTestImpl::successful_test_case_count() const { michael@0: return CountIf(test_cases_, TestCasePassed); michael@0: } michael@0: michael@0: // Gets the number of failed test cases. michael@0: int UnitTestImpl::failed_test_case_count() const { michael@0: return CountIf(test_cases_, TestCaseFailed); michael@0: } michael@0: michael@0: // Gets the number of all test cases. michael@0: int UnitTestImpl::total_test_case_count() const { michael@0: return static_cast(test_cases_.size()); michael@0: } michael@0: michael@0: // Gets the number of all test cases that contain at least one test michael@0: // that should run. michael@0: int UnitTestImpl::test_case_to_run_count() const { michael@0: return CountIf(test_cases_, ShouldRunTestCase); michael@0: } michael@0: michael@0: // Gets the number of successful tests. michael@0: int UnitTestImpl::successful_test_count() const { michael@0: return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); michael@0: } michael@0: michael@0: // Gets the number of failed tests. michael@0: int UnitTestImpl::failed_test_count() const { michael@0: return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); michael@0: } michael@0: michael@0: // Gets the number of disabled tests. michael@0: int UnitTestImpl::disabled_test_count() const { michael@0: return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); michael@0: } michael@0: michael@0: // Gets the number of all tests. michael@0: int UnitTestImpl::total_test_count() const { michael@0: return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); michael@0: } michael@0: michael@0: // Gets the number of tests that should run. michael@0: int UnitTestImpl::test_to_run_count() const { michael@0: return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); michael@0: } michael@0: michael@0: // Returns the current OS stack trace as a String. michael@0: // michael@0: // The maximum number of stack frames to be included is specified by michael@0: // the gtest_stack_trace_depth flag. The skip_count parameter michael@0: // specifies the number of top frames to be skipped, which doesn't michael@0: // count against the number of frames to be included. michael@0: // michael@0: // For example, if Foo() calls Bar(), which in turn calls michael@0: // CurrentOsStackTraceExceptTop(1), Foo() will be included in the michael@0: // trace but Bar() and CurrentOsStackTraceExceptTop() won't. michael@0: String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { michael@0: (void)skip_count; michael@0: return String(""); michael@0: } michael@0: michael@0: // Returns the current time in milliseconds. michael@0: TimeInMillis GetTimeInMillis() { michael@0: #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) michael@0: // Difference between 1970-01-01 and 1601-01-01 in milliseconds. michael@0: // http://analogous.blogspot.com/2005/04/epoch.html michael@0: const TimeInMillis kJavaEpochToWinFileTimeDelta = michael@0: static_cast(116444736UL) * 100000UL; michael@0: const DWORD kTenthMicrosInMilliSecond = 10000; michael@0: michael@0: SYSTEMTIME now_systime; michael@0: FILETIME now_filetime; michael@0: ULARGE_INTEGER now_int64; michael@0: // TODO(kenton@google.com): Shouldn't this just use michael@0: // GetSystemTimeAsFileTime()? michael@0: GetSystemTime(&now_systime); michael@0: if (SystemTimeToFileTime(&now_systime, &now_filetime)) { michael@0: now_int64.LowPart = now_filetime.dwLowDateTime; michael@0: now_int64.HighPart = now_filetime.dwHighDateTime; michael@0: now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - michael@0: kJavaEpochToWinFileTimeDelta; michael@0: return now_int64.QuadPart; michael@0: } michael@0: return 0; michael@0: #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ michael@0: __timeb64 now; michael@0: michael@0: # ifdef _MSC_VER michael@0: michael@0: // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 michael@0: // (deprecated function) there. michael@0: // TODO(kenton@google.com): Use GetTickCount()? Or use michael@0: // SystemTimeToFileTime() michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4996) // Temporarily disables warning 4996. michael@0: _ftime64(&now); michael@0: # pragma warning(pop) // Restores the warning state. michael@0: # else michael@0: michael@0: _ftime64(&now); michael@0: michael@0: # endif // _MSC_VER michael@0: michael@0: return static_cast(now.time) * 1000 + now.millitm; michael@0: #elif GTEST_HAS_GETTIMEOFDAY_ michael@0: struct timeval now; michael@0: gettimeofday(&now, NULL); michael@0: return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; michael@0: #else michael@0: # error "Don't know how to get the current time on your system." michael@0: #endif michael@0: } michael@0: michael@0: // Utilities michael@0: michael@0: // class String michael@0: michael@0: // Copies at most length characters from str into a newly-allocated michael@0: // piece of memory of size length+1. The memory is allocated with new[]. michael@0: // A terminating null byte is written to the memory, and a pointer to it michael@0: // is returned. If str is NULL, NULL is returned. michael@0: static char* CloneString(const char* str, size_t length) { michael@0: if (str == NULL) { michael@0: return NULL; michael@0: } else { michael@0: char* const clone = new char[length + 1]; michael@0: posix::StrNCpy(clone, str, length); michael@0: clone[length] = '\0'; michael@0: return clone; michael@0: } michael@0: } michael@0: michael@0: // Clones a 0-terminated C string, allocating memory using new. The michael@0: // caller is responsible for deleting[] the return value. Returns the michael@0: // cloned string, or NULL if the input is NULL. michael@0: const char * String::CloneCString(const char* c_str) { michael@0: return (c_str == NULL) ? michael@0: NULL : CloneString(c_str, strlen(c_str)); michael@0: } michael@0: michael@0: #if GTEST_OS_WINDOWS_MOBILE michael@0: // Creates a UTF-16 wide string from the given ANSI string, allocating michael@0: // memory using new. The caller is responsible for deleting the return michael@0: // value using delete[]. Returns the wide string, or NULL if the michael@0: // input is NULL. michael@0: LPCWSTR String::AnsiToUtf16(const char* ansi) { michael@0: if (!ansi) return NULL; michael@0: const int length = strlen(ansi); michael@0: const int unicode_length = michael@0: MultiByteToWideChar(CP_ACP, 0, ansi, length, michael@0: NULL, 0); michael@0: WCHAR* unicode = new WCHAR[unicode_length + 1]; michael@0: MultiByteToWideChar(CP_ACP, 0, ansi, length, michael@0: unicode, unicode_length); michael@0: unicode[unicode_length] = 0; michael@0: return unicode; michael@0: } michael@0: michael@0: // Creates an ANSI string from the given wide string, allocating michael@0: // memory using new. The caller is responsible for deleting the return michael@0: // value using delete[]. Returns the ANSI string, or NULL if the michael@0: // input is NULL. michael@0: const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { michael@0: if (!utf16_str) return NULL; michael@0: const int ansi_length = michael@0: WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, michael@0: NULL, 0, NULL, NULL); michael@0: char* ansi = new char[ansi_length + 1]; michael@0: WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, michael@0: ansi, ansi_length, NULL, NULL); michael@0: ansi[ansi_length] = 0; michael@0: return ansi; michael@0: } michael@0: michael@0: #endif // GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Compares two C strings. Returns true iff they have the same content. michael@0: // michael@0: // Unlike strcmp(), this function can handle NULL argument(s). A NULL michael@0: // C string is considered different to any non-NULL C string, michael@0: // including the empty string. michael@0: bool String::CStringEquals(const char * lhs, const char * rhs) { michael@0: if ( lhs == NULL ) return rhs == NULL; michael@0: michael@0: if ( rhs == NULL ) return false; michael@0: michael@0: return strcmp(lhs, rhs) == 0; michael@0: } michael@0: michael@0: #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING michael@0: michael@0: // Converts an array of wide chars to a narrow string using the UTF-8 michael@0: // encoding, and streams the result to the given Message object. michael@0: static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, michael@0: Message* msg) { michael@0: // TODO(wan): consider allowing a testing::String object to michael@0: // contain '\0'. This will make it behave more like std::string, michael@0: // and will allow ToUtf8String() to return the correct encoding michael@0: // for '\0' s.t. we can get rid of the conditional here (and in michael@0: // several other places). michael@0: for (size_t i = 0; i != length; ) { // NOLINT michael@0: if (wstr[i] != L'\0') { michael@0: *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); michael@0: while (i != length && wstr[i] != L'\0') michael@0: i++; michael@0: } else { michael@0: *msg << '\0'; michael@0: i++; michael@0: } michael@0: } michael@0: } michael@0: michael@0: #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING michael@0: michael@0: } // namespace internal michael@0: michael@0: #if GTEST_HAS_STD_WSTRING michael@0: // Converts the given wide string to a narrow string using the UTF-8 michael@0: // encoding, and streams the result to this Message object. michael@0: Message& Message::operator <<(const ::std::wstring& wstr) { michael@0: internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); michael@0: return *this; michael@0: } michael@0: #endif // GTEST_HAS_STD_WSTRING michael@0: michael@0: #if GTEST_HAS_GLOBAL_WSTRING michael@0: // Converts the given wide string to a narrow string using the UTF-8 michael@0: // encoding, and streams the result to this Message object. michael@0: Message& Message::operator <<(const ::wstring& wstr) { michael@0: internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); michael@0: return *this; michael@0: } michael@0: #endif // GTEST_HAS_GLOBAL_WSTRING michael@0: michael@0: // AssertionResult constructors. michael@0: // Used in EXPECT_TRUE/FALSE(assertion_result). michael@0: AssertionResult::AssertionResult(const AssertionResult& other) michael@0: : success_(other.success_), michael@0: message_(other.message_.get() != NULL ? michael@0: new ::std::string(*other.message_) : michael@0: static_cast< ::std::string*>(NULL)) { michael@0: } michael@0: michael@0: // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. michael@0: AssertionResult AssertionResult::operator!() const { michael@0: AssertionResult negation(!success_); michael@0: if (message_.get() != NULL) michael@0: negation << *message_; michael@0: return negation; michael@0: } michael@0: michael@0: // Makes a successful assertion result. michael@0: AssertionResult AssertionSuccess() { michael@0: return AssertionResult(true); michael@0: } michael@0: michael@0: // Makes a failed assertion result. michael@0: AssertionResult AssertionFailure() { michael@0: return AssertionResult(false); michael@0: } michael@0: michael@0: // Makes a failed assertion result with the given failure message. michael@0: // Deprecated; use AssertionFailure() << message. michael@0: AssertionResult AssertionFailure(const Message& message) { michael@0: return AssertionFailure() << message; michael@0: } michael@0: michael@0: namespace internal { michael@0: michael@0: // Constructs and returns the message for an equality assertion michael@0: // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. michael@0: // michael@0: // The first four parameters are the expressions used in the assertion michael@0: // and their values, as strings. For example, for ASSERT_EQ(foo, bar) michael@0: // where foo is 5 and bar is 6, we have: michael@0: // michael@0: // expected_expression: "foo" michael@0: // actual_expression: "bar" michael@0: // expected_value: "5" michael@0: // actual_value: "6" michael@0: // michael@0: // The ignoring_case parameter is true iff the assertion is a michael@0: // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will michael@0: // be inserted into the message. michael@0: AssertionResult EqFailure(const char* expected_expression, michael@0: const char* actual_expression, michael@0: const String& expected_value, michael@0: const String& actual_value, michael@0: bool ignoring_case) { michael@0: Message msg; michael@0: msg << "Value of: " << actual_expression; michael@0: if (actual_value != actual_expression) { michael@0: msg << "\n Actual: " << actual_value; michael@0: } michael@0: michael@0: msg << "\nExpected: " << expected_expression; michael@0: if (ignoring_case) { michael@0: msg << " (ignoring case)"; michael@0: } michael@0: if (expected_value != expected_expression) { michael@0: msg << "\nWhich is: " << expected_value; michael@0: } michael@0: michael@0: return AssertionFailure() << msg; michael@0: } michael@0: michael@0: // Constructs and returns the message for an equality assertion michael@0: // (e.g. ASSERT_NE, EXPECT_NE, etc) failure. michael@0: // michael@0: // The first four parameters are the expressions used in the assertion michael@0: // and their values, as strings. For example, for ASSERT_NE(foo, bar) michael@0: // where foo is 5 and bar is 6, we have: michael@0: // michael@0: // expected_expression: "foo" michael@0: // actual_expression: "bar" michael@0: // expected_value: "5" michael@0: // actual_value: "6" michael@0: // michael@0: // The ignoring_case parameter is true iff the assertion is a michael@0: // *_STRCASENE*. When it's true, the string " (ignoring case)" will michael@0: // be inserted into the message. michael@0: AssertionResult NeFailure(const char* expected_expression, michael@0: const char* actual_expression, michael@0: const String& expected_value, michael@0: const String& actual_value, michael@0: bool ignoring_case) { michael@0: Message msg; michael@0: msg << "Value of: " << actual_expression; michael@0: if (actual_value != actual_expression) { michael@0: msg << "\n Actual: " << actual_value; michael@0: } michael@0: michael@0: msg << "\nExpected: " << expected_expression; michael@0: if (ignoring_case) { michael@0: msg << " (ignoring case)"; michael@0: } michael@0: if (expected_value != expected_expression) { michael@0: msg << "\nWhich is: " << expected_value; michael@0: } michael@0: michael@0: return AssertionFailure() << msg; michael@0: } michael@0: michael@0: // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. michael@0: String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, michael@0: const char* expression_text, michael@0: const char* actual_predicate_value, michael@0: const char* expected_predicate_value) { michael@0: const char* actual_message = assertion_result.message(); michael@0: Message msg; michael@0: msg << "Value of: " << expression_text michael@0: << "\n Actual: " << actual_predicate_value; michael@0: if (actual_message[0] != '\0') michael@0: msg << " (" << actual_message << ")"; michael@0: msg << "\nExpected: " << expected_predicate_value; michael@0: return msg.GetString(); michael@0: } michael@0: michael@0: // Helper function for implementing ASSERT_NEAR. michael@0: AssertionResult DoubleNearPredFormat(const char* expr1, michael@0: const char* expr2, michael@0: const char* abs_error_expr, michael@0: double val1, michael@0: double val2, michael@0: double abs_error) { michael@0: const double diff = fabs(val1 - val2); michael@0: if (diff <= abs_error) return AssertionSuccess(); michael@0: michael@0: // TODO(wan): do not print the value of an expression if it's michael@0: // already a literal. michael@0: return AssertionFailure() michael@0: << "The difference between " << expr1 << " and " << expr2 michael@0: << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" michael@0: << expr1 << " evaluates to " << val1 << ",\n" michael@0: << expr2 << " evaluates to " << val2 << ", and\n" michael@0: << abs_error_expr << " evaluates to " << abs_error << "."; michael@0: } michael@0: michael@0: michael@0: // Helper template for implementing FloatLE() and DoubleLE(). michael@0: template michael@0: AssertionResult FloatingPointLE(const char* expr1, michael@0: const char* expr2, michael@0: RawType val1, michael@0: RawType val2) { michael@0: // Returns success if val1 is less than val2, michael@0: if (val1 < val2) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: // or if val1 is almost equal to val2. michael@0: const FloatingPoint lhs(val1), rhs(val2); michael@0: if (lhs.AlmostEquals(rhs)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: // Note that the above two checks will both fail if either val1 or michael@0: // val2 is NaN, as the IEEE floating-point standard requires that michael@0: // any predicate involving a NaN must return false. michael@0: michael@0: ::std::stringstream val1_ss; michael@0: val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) michael@0: << val1; michael@0: michael@0: ::std::stringstream val2_ss; michael@0: val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) michael@0: << val2; michael@0: michael@0: return AssertionFailure() michael@0: << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" michael@0: << " Actual: " << StringStreamToString(&val1_ss) << " vs " michael@0: << StringStreamToString(&val2_ss); michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // Asserts that val1 is less than, or almost equal to, val2. Fails michael@0: // otherwise. In particular, it fails if either val1 or val2 is NaN. michael@0: AssertionResult FloatLE(const char* expr1, const char* expr2, michael@0: float val1, float val2) { michael@0: return internal::FloatingPointLE(expr1, expr2, val1, val2); michael@0: } michael@0: michael@0: // Asserts that val1 is less than, or almost equal to, val2. Fails michael@0: // otherwise. In particular, it fails if either val1 or val2 is NaN. michael@0: AssertionResult DoubleLE(const char* expr1, const char* expr2, michael@0: double val1, double val2) { michael@0: return internal::FloatingPointLE(expr1, expr2, val1, val2); michael@0: } michael@0: michael@0: namespace internal { michael@0: michael@0: // The helper function for {ASSERT|EXPECT}_EQ with int or enum michael@0: // arguments. michael@0: AssertionResult CmpHelperEQ(const char* expected_expression, michael@0: const char* actual_expression, michael@0: BiggestInt expected, michael@0: BiggestInt actual) { michael@0: if (expected == actual) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: return EqFailure(expected_expression, michael@0: actual_expression, michael@0: FormatForComparisonFailureMessage(expected, actual), michael@0: FormatForComparisonFailureMessage(actual, expected), michael@0: false); michael@0: } michael@0: michael@0: // A macro for implementing the helper functions needed to implement michael@0: // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here michael@0: // just to avoid copy-and-paste of similar code. michael@0: #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ michael@0: AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ michael@0: BiggestInt val1, BiggestInt val2) {\ michael@0: if (val1 op val2) {\ michael@0: return AssertionSuccess();\ michael@0: } else {\ michael@0: return AssertionFailure() \ michael@0: << "Expected: (" << expr1 << ") " #op " (" << expr2\ michael@0: << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ michael@0: << " vs " << FormatForComparisonFailureMessage(val2, val1);\ michael@0: }\ michael@0: } michael@0: michael@0: // Implements the helper function for {ASSERT|EXPECT}_NE with int or michael@0: // enum arguments. michael@0: GTEST_IMPL_CMP_HELPER_(NE, !=) michael@0: // Implements the helper function for {ASSERT|EXPECT}_LE with int or michael@0: // enum arguments. michael@0: GTEST_IMPL_CMP_HELPER_(LE, <=) michael@0: // Implements the helper function for {ASSERT|EXPECT}_LT with int or michael@0: // enum arguments. michael@0: GTEST_IMPL_CMP_HELPER_(LT, < ) michael@0: // Implements the helper function for {ASSERT|EXPECT}_GE with int or michael@0: // enum arguments. michael@0: GTEST_IMPL_CMP_HELPER_(GE, >=) michael@0: // Implements the helper function for {ASSERT|EXPECT}_GT with int or michael@0: // enum arguments. michael@0: GTEST_IMPL_CMP_HELPER_(GT, > ) michael@0: michael@0: #undef GTEST_IMPL_CMP_HELPER_ michael@0: michael@0: // The helper function for {ASSERT|EXPECT}_STREQ. michael@0: AssertionResult CmpHelperSTREQ(const char* expected_expression, michael@0: const char* actual_expression, michael@0: const char* expected, michael@0: const char* actual) { michael@0: if (String::CStringEquals(expected, actual)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: return EqFailure(expected_expression, michael@0: actual_expression, michael@0: PrintToString(expected), michael@0: PrintToString(actual), michael@0: false); michael@0: } michael@0: michael@0: // The helper function for {ASSERT|EXPECT}_STRCASEEQ. michael@0: AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, michael@0: const char* actual_expression, michael@0: const char* expected, michael@0: const char* actual) { michael@0: if (String::CaseInsensitiveCStringEquals(expected, actual)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: return EqFailure(expected_expression, michael@0: actual_expression, michael@0: PrintToString(expected), michael@0: PrintToString(actual), michael@0: true); michael@0: } michael@0: michael@0: // The helper function for {ASSERT|EXPECT}_STRNE. michael@0: AssertionResult CmpHelperSTRNE(const char* s1_expression, michael@0: const char* s2_expression, michael@0: const char* s1, michael@0: const char* s2) { michael@0: if (!String::CStringEquals(s1, s2)) { michael@0: return AssertionSuccess(); michael@0: } else { michael@0: return AssertionFailure() << "Expected: (" << s1_expression << ") != (" michael@0: << s2_expression << "), actual: \"" michael@0: << s1 << "\" vs \"" << s2 << "\""; michael@0: } michael@0: } michael@0: michael@0: // The helper function for {ASSERT|EXPECT}_STRCASENE. michael@0: AssertionResult CmpHelperSTRCASENE(const char* s1_expression, michael@0: const char* s2_expression, michael@0: const char* s1, michael@0: const char* s2) { michael@0: if (!String::CaseInsensitiveCStringEquals(s1, s2)) { michael@0: return AssertionSuccess(); michael@0: } else { michael@0: return AssertionFailure() michael@0: << "Expected: (" << s1_expression << ") != (" michael@0: << s2_expression << ") (ignoring case), actual: \"" michael@0: << s1 << "\" vs \"" << s2 << "\""; michael@0: } michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: namespace { michael@0: michael@0: // Helper functions for implementing IsSubString() and IsNotSubstring(). michael@0: michael@0: // This group of overloaded functions return true iff needle is a michael@0: // substring of haystack. NULL is considered a substring of itself michael@0: // only. michael@0: michael@0: bool IsSubstringPred(const char* needle, const char* haystack) { michael@0: if (needle == NULL || haystack == NULL) michael@0: return needle == haystack; michael@0: michael@0: return strstr(haystack, needle) != NULL; michael@0: } michael@0: michael@0: bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { michael@0: if (needle == NULL || haystack == NULL) michael@0: return needle == haystack; michael@0: michael@0: return wcsstr(haystack, needle) != NULL; michael@0: } michael@0: michael@0: // StringType here can be either ::std::string or ::std::wstring. michael@0: template michael@0: bool IsSubstringPred(const StringType& needle, michael@0: const StringType& haystack) { michael@0: return haystack.find(needle) != StringType::npos; michael@0: } michael@0: michael@0: // This function implements either IsSubstring() or IsNotSubstring(), michael@0: // depending on the value of the expected_to_be_substring parameter. michael@0: // StringType here can be const char*, const wchar_t*, ::std::string, michael@0: // or ::std::wstring. michael@0: template michael@0: AssertionResult IsSubstringImpl( michael@0: bool expected_to_be_substring, michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const StringType& needle, const StringType& haystack) { michael@0: if (IsSubstringPred(needle, haystack) == expected_to_be_substring) michael@0: return AssertionSuccess(); michael@0: michael@0: const bool is_wide_string = sizeof(needle[0]) > 1; michael@0: const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; michael@0: return AssertionFailure() michael@0: << "Value of: " << needle_expr << "\n" michael@0: << " Actual: " << begin_string_quote << needle << "\"\n" michael@0: << "Expected: " << (expected_to_be_substring ? "" : "not ") michael@0: << "a substring of " << haystack_expr << "\n" michael@0: << "Which is: " << begin_string_quote << haystack << "\""; michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: // IsSubstring() and IsNotSubstring() check whether needle is a michael@0: // substring of haystack (NULL is considered a substring of itself michael@0: // only), and return an appropriate error message when they fail. michael@0: michael@0: AssertionResult IsSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const char* needle, const char* haystack) { michael@0: return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const wchar_t* needle, const wchar_t* haystack) { michael@0: return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsNotSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const char* needle, const char* haystack) { michael@0: return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsNotSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const wchar_t* needle, const wchar_t* haystack) { michael@0: return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const ::std::string& needle, const ::std::string& haystack) { michael@0: return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsNotSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const ::std::string& needle, const ::std::string& haystack) { michael@0: return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: #if GTEST_HAS_STD_WSTRING michael@0: AssertionResult IsSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const ::std::wstring& needle, const ::std::wstring& haystack) { michael@0: return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: michael@0: AssertionResult IsNotSubstring( michael@0: const char* needle_expr, const char* haystack_expr, michael@0: const ::std::wstring& needle, const ::std::wstring& haystack) { michael@0: return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); michael@0: } michael@0: #endif // GTEST_HAS_STD_WSTRING michael@0: michael@0: namespace internal { michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: michael@0: namespace { michael@0: michael@0: // Helper function for IsHRESULT{SuccessFailure} predicates michael@0: AssertionResult HRESULTFailureHelper(const char* expr, michael@0: const char* expected, michael@0: long hr) { // NOLINT michael@0: # if GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Windows CE doesn't support FormatMessage. michael@0: const char error_text[] = ""; michael@0: michael@0: # else michael@0: michael@0: // Looks up the human-readable system message for the HRESULT code michael@0: // and since we're not passing any params to FormatMessage, we don't michael@0: // want inserts expanded. michael@0: const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | michael@0: FORMAT_MESSAGE_IGNORE_INSERTS; michael@0: const DWORD kBufSize = 4096; // String::Format can't exceed this length. michael@0: // Gets the system's human readable message string for this HRESULT. michael@0: char error_text[kBufSize] = { '\0' }; michael@0: DWORD message_length = ::FormatMessageA(kFlags, michael@0: 0, // no source, we're asking system michael@0: hr, // the error michael@0: 0, // no line width restrictions michael@0: error_text, // output buffer michael@0: kBufSize, // buf size michael@0: NULL); // no arguments for inserts michael@0: // Trims tailing white space (FormatMessage leaves a trailing cr-lf) michael@0: for (; message_length && IsSpace(error_text[message_length - 1]); michael@0: --message_length) { michael@0: error_text[message_length - 1] = '\0'; michael@0: } michael@0: michael@0: # endif // GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: const String error_hex(String::Format("0x%08X ", hr)); michael@0: return ::testing::AssertionFailure() michael@0: << "Expected: " << expr << " " << expected << ".\n" michael@0: << " Actual: " << error_hex << error_text << "\n"; michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT michael@0: if (SUCCEEDED(hr)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: return HRESULTFailureHelper(expr, "succeeds", hr); michael@0: } michael@0: michael@0: AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT michael@0: if (FAILED(hr)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: return HRESULTFailureHelper(expr, "fails", hr); michael@0: } michael@0: michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: // Utility functions for encoding Unicode text (wide strings) in michael@0: // UTF-8. michael@0: michael@0: // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 michael@0: // like this: michael@0: // michael@0: // Code-point length Encoding michael@0: // 0 - 7 bits 0xxxxxxx michael@0: // 8 - 11 bits 110xxxxx 10xxxxxx michael@0: // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx michael@0: // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx michael@0: michael@0: // The maximum code-point a one-byte UTF-8 sequence can represent. michael@0: const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; michael@0: michael@0: // The maximum code-point a two-byte UTF-8 sequence can represent. michael@0: const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; michael@0: michael@0: // The maximum code-point a three-byte UTF-8 sequence can represent. michael@0: const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; michael@0: michael@0: // The maximum code-point a four-byte UTF-8 sequence can represent. michael@0: const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; michael@0: michael@0: // Chops off the n lowest bits from a bit pattern. Returns the n michael@0: // lowest bits. As a side effect, the original bit pattern will be michael@0: // shifted to the right by n bits. michael@0: inline UInt32 ChopLowBits(UInt32* bits, int n) { michael@0: const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); michael@0: *bits >>= n; michael@0: return low_bits; michael@0: } michael@0: michael@0: // Converts a Unicode code point to a narrow string in UTF-8 encoding. michael@0: // code_point parameter is of type UInt32 because wchar_t may not be michael@0: // wide enough to contain a code point. michael@0: // The output buffer str must containt at least 32 characters. michael@0: // The function returns the address of the output buffer. michael@0: // If the code_point is not a valid Unicode code point michael@0: // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output michael@0: // as '(Invalid Unicode 0xXXXXXXXX)'. michael@0: char* CodePointToUtf8(UInt32 code_point, char* str) { michael@0: if (code_point <= kMaxCodePoint1) { michael@0: str[1] = '\0'; michael@0: str[0] = static_cast(code_point); // 0xxxxxxx michael@0: } else if (code_point <= kMaxCodePoint2) { michael@0: str[2] = '\0'; michael@0: str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[0] = static_cast(0xC0 | code_point); // 110xxxxx michael@0: } else if (code_point <= kMaxCodePoint3) { michael@0: str[3] = '\0'; michael@0: str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[0] = static_cast(0xE0 | code_point); // 1110xxxx michael@0: } else if (code_point <= kMaxCodePoint4) { michael@0: str[4] = '\0'; michael@0: str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx michael@0: str[0] = static_cast(0xF0 | code_point); // 11110xxx michael@0: } else { michael@0: // The longest string String::Format can produce when invoked michael@0: // with these parameters is 28 character long (not including michael@0: // the terminating nul character). We are asking for 32 character michael@0: // buffer just in case. This is also enough for strncpy to michael@0: // null-terminate the destination string. michael@0: posix::StrNCpy( michael@0: str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32); michael@0: str[31] = '\0'; // Makes sure no change in the format to strncpy leaves michael@0: // the result unterminated. michael@0: } michael@0: return str; michael@0: } michael@0: michael@0: // The following two functions only make sense if the the system michael@0: // uses UTF-16 for wide string encoding. All supported systems michael@0: // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. michael@0: michael@0: // Determines if the arguments constitute UTF-16 surrogate pair michael@0: // and thus should be combined into a single Unicode code point michael@0: // using CreateCodePointFromUtf16SurrogatePair. michael@0: inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { michael@0: return sizeof(wchar_t) == 2 && michael@0: (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; michael@0: } michael@0: michael@0: // Creates a Unicode code point from UTF16 surrogate pair. michael@0: inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, michael@0: wchar_t second) { michael@0: const UInt32 mask = (1 << 10) - 1; michael@0: return (sizeof(wchar_t) == 2) ? michael@0: (((first & mask) << 10) | (second & mask)) + 0x10000 : michael@0: // This function should not be called when the condition is michael@0: // false, but we provide a sensible default in case it is. michael@0: static_cast(first); michael@0: } michael@0: michael@0: // Converts a wide string to a narrow string in UTF-8 encoding. michael@0: // The wide string is assumed to have the following encoding: michael@0: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) michael@0: // UTF-32 if sizeof(wchar_t) == 4 (on Linux) michael@0: // Parameter str points to a null-terminated wide string. michael@0: // Parameter num_chars may additionally limit the number michael@0: // of wchar_t characters processed. -1 is used when the entire string michael@0: // should be processed. michael@0: // If the string contains code points that are not valid Unicode code points michael@0: // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output michael@0: // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding michael@0: // and contains invalid UTF-16 surrogate pairs, values in those pairs michael@0: // will be encoded as individual Unicode characters from Basic Normal Plane. michael@0: String WideStringToUtf8(const wchar_t* str, int num_chars) { michael@0: if (num_chars == -1) michael@0: num_chars = static_cast(wcslen(str)); michael@0: michael@0: ::std::stringstream stream; michael@0: for (int i = 0; i < num_chars; ++i) { michael@0: UInt32 unicode_code_point; michael@0: michael@0: if (str[i] == L'\0') { michael@0: break; michael@0: } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { michael@0: unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], michael@0: str[i + 1]); michael@0: i++; michael@0: } else { michael@0: unicode_code_point = static_cast(str[i]); michael@0: } michael@0: michael@0: char buffer[32]; // CodePointToUtf8 requires a buffer this big. michael@0: stream << CodePointToUtf8(unicode_code_point, buffer); michael@0: } michael@0: return StringStreamToString(&stream); michael@0: } michael@0: michael@0: // Converts a wide C string to a String using the UTF-8 encoding. michael@0: // NULL will be converted to "(null)". michael@0: String String::ShowWideCString(const wchar_t * wide_c_str) { michael@0: if (wide_c_str == NULL) return String("(null)"); michael@0: michael@0: return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); michael@0: } michael@0: michael@0: // Compares two wide C strings. Returns true iff they have the same michael@0: // content. michael@0: // michael@0: // Unlike wcscmp(), this function can handle NULL argument(s). A NULL michael@0: // C string is considered different to any non-NULL C string, michael@0: // including the empty string. michael@0: bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { michael@0: if (lhs == NULL) return rhs == NULL; michael@0: michael@0: if (rhs == NULL) return false; michael@0: michael@0: return wcscmp(lhs, rhs) == 0; michael@0: } michael@0: michael@0: // Helper function for *_STREQ on wide strings. michael@0: AssertionResult CmpHelperSTREQ(const char* expected_expression, michael@0: const char* actual_expression, michael@0: const wchar_t* expected, michael@0: const wchar_t* actual) { michael@0: if (String::WideCStringEquals(expected, actual)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: return EqFailure(expected_expression, michael@0: actual_expression, michael@0: PrintToString(expected), michael@0: PrintToString(actual), michael@0: false); michael@0: } michael@0: michael@0: // Helper function for *_STRNE on wide strings. michael@0: AssertionResult CmpHelperSTRNE(const char* s1_expression, michael@0: const char* s2_expression, michael@0: const wchar_t* s1, michael@0: const wchar_t* s2) { michael@0: if (!String::WideCStringEquals(s1, s2)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: return AssertionFailure() << "Expected: (" << s1_expression << ") != (" michael@0: << s2_expression << "), actual: " michael@0: << PrintToString(s1) michael@0: << " vs " << PrintToString(s2); michael@0: } michael@0: michael@0: // Compares two C strings, ignoring case. Returns true iff they have michael@0: // the same content. michael@0: // michael@0: // Unlike strcasecmp(), this function can handle NULL argument(s). A michael@0: // NULL C string is considered different to any non-NULL C string, michael@0: // including the empty string. michael@0: bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { michael@0: if (lhs == NULL) michael@0: return rhs == NULL; michael@0: if (rhs == NULL) michael@0: return false; michael@0: return posix::StrCaseCmp(lhs, rhs) == 0; michael@0: } michael@0: michael@0: // Compares two wide C strings, ignoring case. Returns true iff they michael@0: // have the same content. michael@0: // michael@0: // Unlike wcscasecmp(), this function can handle NULL argument(s). michael@0: // A NULL C string is considered different to any non-NULL wide C string, michael@0: // including the empty string. michael@0: // NB: The implementations on different platforms slightly differ. michael@0: // On windows, this method uses _wcsicmp which compares according to LC_CTYPE michael@0: // environment variable. On GNU platform this method uses wcscasecmp michael@0: // which compares according to LC_CTYPE category of the current locale. michael@0: // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the michael@0: // current locale. michael@0: bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, michael@0: const wchar_t* rhs) { michael@0: if (lhs == NULL) return rhs == NULL; michael@0: michael@0: if (rhs == NULL) return false; michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: return _wcsicmp(lhs, rhs) == 0; michael@0: #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID michael@0: return wcscasecmp(lhs, rhs) == 0; michael@0: #else michael@0: // Android, Mac OS X and Cygwin don't define wcscasecmp. michael@0: // Other unknown OSes may not define it either. michael@0: wint_t left, right; michael@0: do { michael@0: left = towlower(*lhs++); michael@0: right = towlower(*rhs++); michael@0: } while (left && left == right); michael@0: return left == right; michael@0: #endif // OS selector michael@0: } michael@0: michael@0: // Compares this with another String. michael@0: // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 michael@0: // if this is greater than rhs. michael@0: int String::Compare(const String & rhs) const { michael@0: const char* const lhs_c_str = c_str(); michael@0: const char* const rhs_c_str = rhs.c_str(); michael@0: michael@0: if (lhs_c_str == NULL) { michael@0: return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL michael@0: } else if (rhs_c_str == NULL) { michael@0: return 1; michael@0: } michael@0: michael@0: const size_t shorter_str_len = michael@0: length() <= rhs.length() ? length() : rhs.length(); michael@0: for (size_t i = 0; i != shorter_str_len; i++) { michael@0: if (lhs_c_str[i] < rhs_c_str[i]) { michael@0: return -1; michael@0: } else if (lhs_c_str[i] > rhs_c_str[i]) { michael@0: return 1; michael@0: } michael@0: } michael@0: return (length() < rhs.length()) ? -1 : michael@0: (length() > rhs.length()) ? 1 : 0; michael@0: } michael@0: michael@0: // Returns true iff this String ends with the given suffix. *Any* michael@0: // String is considered to end with a NULL or empty suffix. michael@0: bool String::EndsWith(const char* suffix) const { michael@0: if (suffix == NULL || CStringEquals(suffix, "")) return true; michael@0: michael@0: if (c_str() == NULL) return false; michael@0: michael@0: const size_t this_len = strlen(c_str()); michael@0: const size_t suffix_len = strlen(suffix); michael@0: return (this_len >= suffix_len) && michael@0: CStringEquals(c_str() + this_len - suffix_len, suffix); michael@0: } michael@0: michael@0: // Returns true iff this String ends with the given suffix, ignoring case. michael@0: // Any String is considered to end with a NULL or empty suffix. michael@0: bool String::EndsWithCaseInsensitive(const char* suffix) const { michael@0: if (suffix == NULL || CStringEquals(suffix, "")) return true; michael@0: michael@0: if (c_str() == NULL) return false; michael@0: michael@0: const size_t this_len = strlen(c_str()); michael@0: const size_t suffix_len = strlen(suffix); michael@0: return (this_len >= suffix_len) && michael@0: CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix); michael@0: } michael@0: michael@0: // Formats a list of arguments to a String, using the same format michael@0: // spec string as for printf. michael@0: // michael@0: // We do not use the StringPrintf class as it is not universally michael@0: // available. michael@0: // michael@0: // The result is limited to 4096 characters (including the tailing 0). michael@0: // If 4096 characters are not enough to format the input, or if michael@0: // there's an error, "" is michael@0: // returned. michael@0: String String::Format(const char * format, ...) { michael@0: va_list args; michael@0: va_start(args, format); michael@0: michael@0: char buffer[4096]; michael@0: const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); michael@0: michael@0: // MSVC 8 deprecates vsnprintf(), so we want to suppress warning michael@0: // 4996 (deprecated function) there. michael@0: #ifdef _MSC_VER // We are using MSVC. michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4996) // Temporarily disables warning 4996. michael@0: michael@0: const int size = vsnprintf(buffer, kBufferSize, format, args); michael@0: michael@0: # pragma warning(pop) // Restores the warning state. michael@0: #else // We are not using MSVC. michael@0: const int size = vsnprintf(buffer, kBufferSize, format, args); michael@0: #endif // _MSC_VER michael@0: va_end(args); michael@0: michael@0: // vsnprintf()'s behavior is not portable. When the buffer is not michael@0: // big enough, it returns a negative value in MSVC, and returns the michael@0: // needed buffer size on Linux. When there is an output error, it michael@0: // always returns a negative value. For simplicity, we lump the two michael@0: // error cases together. michael@0: if (size < 0 || size >= kBufferSize) { michael@0: return String(""); michael@0: } else { michael@0: return String(buffer, size); michael@0: } michael@0: } michael@0: michael@0: // Converts the buffer in a stringstream to a String, converting NUL michael@0: // bytes to "\\0" along the way. michael@0: String StringStreamToString(::std::stringstream* ss) { michael@0: const ::std::string& str = ss->str(); michael@0: const char* const start = str.c_str(); michael@0: const char* const end = start + str.length(); michael@0: michael@0: // We need to use a helper stringstream to do this transformation michael@0: // because String doesn't support push_back(). michael@0: ::std::stringstream helper; michael@0: for (const char* ch = start; ch != end; ++ch) { michael@0: if (*ch == '\0') { michael@0: helper << "\\0"; // Replaces NUL with "\\0"; michael@0: } else { michael@0: helper.put(*ch); michael@0: } michael@0: } michael@0: michael@0: return String(helper.str().c_str()); michael@0: } michael@0: michael@0: // Appends the user-supplied message to the Google-Test-generated message. michael@0: String AppendUserMessage(const String& gtest_msg, michael@0: const Message& user_msg) { michael@0: // Appends the user message if it's non-empty. michael@0: const String user_msg_string = user_msg.GetString(); michael@0: if (user_msg_string.empty()) { michael@0: return gtest_msg; michael@0: } michael@0: michael@0: Message msg; michael@0: msg << gtest_msg << "\n" << user_msg_string; michael@0: michael@0: return msg.GetString(); michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // class TestResult michael@0: michael@0: // Creates an empty TestResult. michael@0: TestResult::TestResult() michael@0: : death_test_count_(0), michael@0: elapsed_time_(0) { michael@0: } michael@0: michael@0: // D'tor. michael@0: TestResult::~TestResult() { michael@0: } michael@0: michael@0: // Returns the i-th test part result among all the results. i can michael@0: // range from 0 to total_part_count() - 1. If i is not in that range, michael@0: // aborts the program. michael@0: const TestPartResult& TestResult::GetTestPartResult(int i) const { michael@0: if (i < 0 || i >= total_part_count()) michael@0: internal::posix::Abort(); michael@0: return test_part_results_.at(i); michael@0: } michael@0: michael@0: // Returns the i-th test property. i can range from 0 to michael@0: // test_property_count() - 1. If i is not in that range, aborts the michael@0: // program. michael@0: const TestProperty& TestResult::GetTestProperty(int i) const { michael@0: if (i < 0 || i >= test_property_count()) michael@0: internal::posix::Abort(); michael@0: return test_properties_.at(i); michael@0: } michael@0: michael@0: // Clears the test part results. michael@0: void TestResult::ClearTestPartResults() { michael@0: test_part_results_.clear(); michael@0: } michael@0: michael@0: // Adds a test part result to the list. michael@0: void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { michael@0: test_part_results_.push_back(test_part_result); michael@0: } michael@0: michael@0: // Adds a test property to the list. If a property with the same key as the michael@0: // supplied property is already represented, the value of this test_property michael@0: // replaces the old value for that key. michael@0: void TestResult::RecordProperty(const TestProperty& test_property) { michael@0: if (!ValidateTestProperty(test_property)) { michael@0: return; michael@0: } michael@0: internal::MutexLock lock(&test_properites_mutex_); michael@0: const std::vector::iterator property_with_matching_key = michael@0: std::find_if(test_properties_.begin(), test_properties_.end(), michael@0: internal::TestPropertyKeyIs(test_property.key())); michael@0: if (property_with_matching_key == test_properties_.end()) { michael@0: test_properties_.push_back(test_property); michael@0: return; michael@0: } michael@0: property_with_matching_key->SetValue(test_property.value()); michael@0: } michael@0: michael@0: // Adds a failure if the key is a reserved attribute of Google Test michael@0: // testcase tags. Returns true if the property is valid. michael@0: bool TestResult::ValidateTestProperty(const TestProperty& test_property) { michael@0: internal::String key(test_property.key()); michael@0: if (key == "name" || key == "status" || key == "time" || key == "classname") { michael@0: ADD_FAILURE() michael@0: << "Reserved key used in RecordProperty(): " michael@0: << key michael@0: << " ('name', 'status', 'time', and 'classname' are reserved by " michael@0: << GTEST_NAME_ << ")"; michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: // Clears the object. michael@0: void TestResult::Clear() { michael@0: test_part_results_.clear(); michael@0: test_properties_.clear(); michael@0: death_test_count_ = 0; michael@0: elapsed_time_ = 0; michael@0: } michael@0: michael@0: // Returns true iff the test failed. michael@0: bool TestResult::Failed() const { michael@0: for (int i = 0; i < total_part_count(); ++i) { michael@0: if (GetTestPartResult(i).failed()) michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // Returns true iff the test part fatally failed. michael@0: static bool TestPartFatallyFailed(const TestPartResult& result) { michael@0: return result.fatally_failed(); michael@0: } michael@0: michael@0: // Returns true iff the test fatally failed. michael@0: bool TestResult::HasFatalFailure() const { michael@0: return CountIf(test_part_results_, TestPartFatallyFailed) > 0; michael@0: } michael@0: michael@0: // Returns true iff the test part non-fatally failed. michael@0: static bool TestPartNonfatallyFailed(const TestPartResult& result) { michael@0: return result.nonfatally_failed(); michael@0: } michael@0: michael@0: // Returns true iff the test has a non-fatal failure. michael@0: bool TestResult::HasNonfatalFailure() const { michael@0: return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; michael@0: } michael@0: michael@0: // Gets the number of all test parts. This is the sum of the number michael@0: // of successful test parts and the number of failed test parts. michael@0: int TestResult::total_part_count() const { michael@0: return static_cast(test_part_results_.size()); michael@0: } michael@0: michael@0: // Returns the number of the test properties. michael@0: int TestResult::test_property_count() const { michael@0: return static_cast(test_properties_.size()); michael@0: } michael@0: michael@0: // class Test michael@0: michael@0: // Creates a Test object. michael@0: michael@0: // The c'tor saves the values of all Google Test flags. michael@0: Test::Test() michael@0: : gtest_flag_saver_(new internal::GTestFlagSaver) { michael@0: } michael@0: michael@0: // The d'tor restores the values of all Google Test flags. michael@0: Test::~Test() { michael@0: delete gtest_flag_saver_; michael@0: } michael@0: michael@0: // Sets up the test fixture. michael@0: // michael@0: // A sub-class may override this. michael@0: void Test::SetUp() { michael@0: } michael@0: michael@0: // Tears down the test fixture. michael@0: // michael@0: // A sub-class may override this. michael@0: void Test::TearDown() { michael@0: } michael@0: michael@0: // Allows user supplied key value pairs to be recorded for later output. michael@0: void Test::RecordProperty(const char* key, const char* value) { michael@0: UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); michael@0: } michael@0: michael@0: // Allows user supplied key value pairs to be recorded for later output. michael@0: void Test::RecordProperty(const char* key, int value) { michael@0: Message value_message; michael@0: value_message << value; michael@0: RecordProperty(key, value_message.GetString().c_str()); michael@0: } michael@0: michael@0: namespace internal { michael@0: michael@0: void ReportFailureInUnknownLocation(TestPartResult::Type result_type, michael@0: const String& message) { michael@0: // This function is a friend of UnitTest and as such has access to michael@0: // AddTestPartResult. michael@0: UnitTest::GetInstance()->AddTestPartResult( michael@0: result_type, michael@0: NULL, // No info about the source file where the exception occurred. michael@0: -1, // We have no info on which line caused the exception. michael@0: message, michael@0: String()); // No stack trace, either. michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // Google Test requires all tests in the same test case to use the same test michael@0: // fixture class. This function checks if the current test has the michael@0: // same fixture class as the first test in the current test case. If michael@0: // yes, it returns true; otherwise it generates a Google Test failure and michael@0: // returns false. michael@0: bool Test::HasSameFixtureClass() { michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: const TestCase* const test_case = impl->current_test_case(); michael@0: michael@0: // Info about the first test in the current test case. michael@0: const TestInfo* const first_test_info = test_case->test_info_list()[0]; michael@0: const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; michael@0: const char* const first_test_name = first_test_info->name(); michael@0: michael@0: // Info about the current test. michael@0: const TestInfo* const this_test_info = impl->current_test_info(); michael@0: const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; michael@0: const char* const this_test_name = this_test_info->name(); michael@0: michael@0: if (this_fixture_id != first_fixture_id) { michael@0: // Is the first test defined using TEST? michael@0: const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); michael@0: // Is this test defined using TEST? michael@0: const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); michael@0: michael@0: if (first_is_TEST || this_is_TEST) { michael@0: // The user mixed TEST and TEST_F in this test case - we'll tell michael@0: // him/her how to fix it. michael@0: michael@0: // Gets the name of the TEST and the name of the TEST_F. Note michael@0: // that first_is_TEST and this_is_TEST cannot both be true, as michael@0: // the fixture IDs are different for the two tests. michael@0: const char* const TEST_name = michael@0: first_is_TEST ? first_test_name : this_test_name; michael@0: const char* const TEST_F_name = michael@0: first_is_TEST ? this_test_name : first_test_name; michael@0: michael@0: ADD_FAILURE() michael@0: << "All tests in the same test case must use the same test fixture\n" michael@0: << "class, so mixing TEST_F and TEST in the same test case is\n" michael@0: << "illegal. In test case " << this_test_info->test_case_name() michael@0: << ",\n" michael@0: << "test " << TEST_F_name << " is defined using TEST_F but\n" michael@0: << "test " << TEST_name << " is defined using TEST. You probably\n" michael@0: << "want to change the TEST to TEST_F or move it to another test\n" michael@0: << "case."; michael@0: } else { michael@0: // The user defined two fixture classes with the same name in michael@0: // two namespaces - we'll tell him/her how to fix it. michael@0: ADD_FAILURE() michael@0: << "All tests in the same test case must use the same test fixture\n" michael@0: << "class. However, in test case " michael@0: << this_test_info->test_case_name() << ",\n" michael@0: << "you defined test " << first_test_name michael@0: << " and test " << this_test_name << "\n" michael@0: << "using two different test fixture classes. This can happen if\n" michael@0: << "the two classes are from different namespaces or translation\n" michael@0: << "units and have the same name. You should probably rename one\n" michael@0: << "of the classes to put the tests into different test cases."; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: #if GTEST_HAS_SEH michael@0: michael@0: // Adds an "exception thrown" fatal failure to the current test. This michael@0: // function returns its result via an output parameter pointer because VC++ michael@0: // prohibits creation of objects with destructors on stack in functions michael@0: // using __try (see error C2712). michael@0: static internal::String* FormatSehExceptionMessage(DWORD exception_code, michael@0: const char* location) { michael@0: Message message; michael@0: message << "SEH exception with code 0x" << std::setbase(16) << michael@0: exception_code << std::setbase(10) << " thrown in " << location << "."; michael@0: michael@0: return new internal::String(message.GetString()); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_SEH michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Adds an "exception thrown" fatal failure to the current test. michael@0: static internal::String FormatCxxExceptionMessage(const char* description, michael@0: const char* location) { michael@0: Message message; michael@0: if (description != NULL) { michael@0: message << "C++ exception with description \"" << description << "\""; michael@0: } else { michael@0: message << "Unknown C++ exception"; michael@0: } michael@0: message << " thrown in " << location << "."; michael@0: michael@0: return message.GetString(); michael@0: } michael@0: michael@0: static internal::String PrintTestPartResultToString( michael@0: const TestPartResult& test_part_result); michael@0: michael@0: // A failed Google Test assertion will throw an exception of this type when michael@0: // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We michael@0: // derive it from std::runtime_error, which is for errors presumably michael@0: // detectable only at run time. Since std::runtime_error inherits from michael@0: // std::exception, many testing frameworks know how to extract and print the michael@0: // message inside it. michael@0: class GoogleTestFailureException : public ::std::runtime_error { michael@0: public: michael@0: explicit GoogleTestFailureException(const TestPartResult& failure) michael@0: : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} michael@0: }; michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: namespace internal { michael@0: // We put these helper functions in the internal namespace as IBM's xlC michael@0: // compiler rejects the code if they were declared static. michael@0: michael@0: // Runs the given method and handles SEH exceptions it throws, when michael@0: // SEH is supported; returns the 0-value for type Result in case of an michael@0: // SEH exception. (Microsoft compilers cannot handle SEH and C++ michael@0: // exceptions in the same function. Therefore, we provide a separate michael@0: // wrapper function for handling SEH exceptions.) michael@0: template michael@0: Result HandleSehExceptionsInMethodIfSupported( michael@0: T* object, Result (T::*method)(), const char* location) { michael@0: #if GTEST_HAS_SEH michael@0: __try { michael@0: return (object->*method)(); michael@0: } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT michael@0: GetExceptionCode())) { michael@0: // We create the exception message on the heap because VC++ prohibits michael@0: // creation of objects with destructors on stack in functions using __try michael@0: // (see error C2712). michael@0: internal::String* exception_message = FormatSehExceptionMessage( michael@0: GetExceptionCode(), location); michael@0: internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, michael@0: *exception_message); michael@0: delete exception_message; michael@0: return static_cast(0); michael@0: } michael@0: #else michael@0: (void)location; michael@0: return (object->*method)(); michael@0: #endif // GTEST_HAS_SEH michael@0: } michael@0: michael@0: // Runs the given method and catches and reports C++ and/or SEH-style michael@0: // exceptions, if they are supported; returns the 0-value for type michael@0: // Result in case of an SEH exception. michael@0: template michael@0: Result HandleExceptionsInMethodIfSupported( michael@0: T* object, Result (T::*method)(), const char* location) { michael@0: // NOTE: The user code can affect the way in which Google Test handles michael@0: // exceptions by setting GTEST_FLAG(catch_exceptions), but only before michael@0: // RUN_ALL_TESTS() starts. It is technically possible to check the flag michael@0: // after the exception is caught and either report or re-throw the michael@0: // exception based on the flag's value: michael@0: // michael@0: // try { michael@0: // // Perform the test method. michael@0: // } catch (...) { michael@0: // if (GTEST_FLAG(catch_exceptions)) michael@0: // // Report the exception as failure. michael@0: // else michael@0: // throw; // Re-throws the original exception. michael@0: // } michael@0: // michael@0: // However, the purpose of this flag is to allow the program to drop into michael@0: // the debugger when the exception is thrown. On most platforms, once the michael@0: // control enters the catch block, the exception origin information is michael@0: // lost and the debugger will stop the program at the point of the michael@0: // re-throw in this function -- instead of at the point of the original michael@0: // throw statement in the code under test. For this reason, we perform michael@0: // the check early, sacrificing the ability to affect Google Test's michael@0: // exception handling in the method where the exception is thrown. michael@0: if (internal::GetUnitTestImpl()->catch_exceptions()) { michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: try { michael@0: return HandleSehExceptionsInMethodIfSupported(object, method, location); michael@0: } catch (const GoogleTestFailureException&) { // NOLINT michael@0: // This exception doesn't originate in code under test. It makes no michael@0: // sense to report it as a test failure. michael@0: throw; michael@0: } catch (const std::exception& e) { // NOLINT michael@0: internal::ReportFailureInUnknownLocation( michael@0: TestPartResult::kFatalFailure, michael@0: FormatCxxExceptionMessage(e.what(), location)); michael@0: } catch (...) { // NOLINT michael@0: internal::ReportFailureInUnknownLocation( michael@0: TestPartResult::kFatalFailure, michael@0: FormatCxxExceptionMessage(NULL, location)); michael@0: } michael@0: return static_cast(0); michael@0: #else michael@0: return HandleSehExceptionsInMethodIfSupported(object, method, location); michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: } else { michael@0: return (object->*method)(); michael@0: } michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // Runs the test and updates the test result. michael@0: void Test::Run() { michael@0: if (!HasSameFixtureClass()) return; michael@0: michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); michael@0: // We will run the test only if SetUp() was successful. michael@0: if (!HasFatalFailure()) { michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported( michael@0: this, &Test::TestBody, "the test body"); michael@0: } michael@0: michael@0: // However, we want to clean up as much as possible. Hence we will michael@0: // always call TearDown(), even if SetUp() or the test body has michael@0: // failed. michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported( michael@0: this, &Test::TearDown, "TearDown()"); michael@0: } michael@0: michael@0: // Returns true iff the current test has a fatal failure. michael@0: bool Test::HasFatalFailure() { michael@0: return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); michael@0: } michael@0: michael@0: // Returns true iff the current test has a non-fatal failure. michael@0: bool Test::HasNonfatalFailure() { michael@0: return internal::GetUnitTestImpl()->current_test_result()-> michael@0: HasNonfatalFailure(); michael@0: } michael@0: michael@0: // class TestInfo michael@0: michael@0: // Constructs a TestInfo object. It assumes ownership of the test factory michael@0: // object. michael@0: // TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s michael@0: // to signify they cannot be NULLs. michael@0: TestInfo::TestInfo(const char* a_test_case_name, michael@0: const char* a_name, michael@0: const char* a_type_param, michael@0: const char* a_value_param, michael@0: internal::TypeId fixture_class_id, michael@0: internal::TestFactoryBase* factory) michael@0: : test_case_name_(a_test_case_name), michael@0: name_(a_name), michael@0: type_param_(a_type_param ? new std::string(a_type_param) : NULL), michael@0: value_param_(a_value_param ? new std::string(a_value_param) : NULL), michael@0: fixture_class_id_(fixture_class_id), michael@0: should_run_(false), michael@0: is_disabled_(false), michael@0: matches_filter_(false), michael@0: factory_(factory), michael@0: result_() {} michael@0: michael@0: // Destructs a TestInfo object. michael@0: TestInfo::~TestInfo() { delete factory_; } michael@0: michael@0: namespace internal { michael@0: michael@0: // Creates a new TestInfo object and registers it with Google Test; michael@0: // returns the created object. michael@0: // michael@0: // Arguments: michael@0: // michael@0: // test_case_name: name of the test case michael@0: // name: name of the test michael@0: // type_param: the name of the test's type parameter, or NULL if michael@0: // this is not a typed or a type-parameterized test. michael@0: // value_param: text representation of the test's value parameter, michael@0: // or NULL if this is not a value-parameterized test. michael@0: // fixture_class_id: ID of the test fixture class michael@0: // set_up_tc: pointer to the function that sets up the test case michael@0: // tear_down_tc: pointer to the function that tears down the test case michael@0: // factory: pointer to the factory that creates a test object. michael@0: // The newly created TestInfo instance will assume michael@0: // ownership of the factory object. michael@0: TestInfo* MakeAndRegisterTestInfo( michael@0: const char* test_case_name, const char* name, michael@0: const char* type_param, michael@0: const char* value_param, michael@0: TypeId fixture_class_id, michael@0: SetUpTestCaseFunc set_up_tc, michael@0: TearDownTestCaseFunc tear_down_tc, michael@0: TestFactoryBase* factory) { michael@0: TestInfo* const test_info = michael@0: new TestInfo(test_case_name, name, type_param, value_param, michael@0: fixture_class_id, factory); michael@0: GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); michael@0: return test_info; michael@0: } michael@0: michael@0: #if GTEST_HAS_PARAM_TEST michael@0: void ReportInvalidTestCaseType(const char* test_case_name, michael@0: const char* file, int line) { michael@0: Message errors; michael@0: errors michael@0: << "Attempted redefinition of test case " << test_case_name << ".\n" michael@0: << "All tests in the same test case must use the same test fixture\n" michael@0: << "class. However, in test case " << test_case_name << ", you tried\n" michael@0: << "to define a test using a fixture class different from the one\n" michael@0: << "used earlier. This can happen if the two fixture classes are\n" michael@0: << "from different namespaces and have the same name. You should\n" michael@0: << "probably rename one of the classes to put the tests into different\n" michael@0: << "test cases."; michael@0: michael@0: fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), michael@0: errors.GetString().c_str()); michael@0: } michael@0: #endif // GTEST_HAS_PARAM_TEST michael@0: michael@0: } // namespace internal michael@0: michael@0: namespace { michael@0: michael@0: // A predicate that checks the test name of a TestInfo against a known michael@0: // value. michael@0: // michael@0: // This is used for implementation of the TestCase class only. We put michael@0: // it in the anonymous namespace to prevent polluting the outer michael@0: // namespace. michael@0: // michael@0: // TestNameIs is copyable. michael@0: class TestNameIs { michael@0: public: michael@0: // Constructor. michael@0: // michael@0: // TestNameIs has NO default constructor. michael@0: explicit TestNameIs(const char* name) michael@0: : name_(name) {} michael@0: michael@0: // Returns true iff the test name of test_info matches name_. michael@0: bool operator()(const TestInfo * test_info) const { michael@0: return test_info && internal::String(test_info->name()).Compare(name_) == 0; michael@0: } michael@0: michael@0: private: michael@0: internal::String name_; michael@0: }; michael@0: michael@0: } // namespace michael@0: michael@0: namespace internal { michael@0: michael@0: // This method expands all parameterized tests registered with macros TEST_P michael@0: // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. michael@0: // This will be done just once during the program runtime. michael@0: void UnitTestImpl::RegisterParameterizedTests() { michael@0: #if GTEST_HAS_PARAM_TEST michael@0: if (!parameterized_tests_registered_) { michael@0: parameterized_test_registry_.RegisterTests(); michael@0: parameterized_tests_registered_ = true; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // Creates the test object, runs it, records its result, and then michael@0: // deletes it. michael@0: void TestInfo::Run() { michael@0: if (!should_run_) return; michael@0: michael@0: // Tells UnitTest where to store test result. michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: impl->set_current_test_info(this); michael@0: michael@0: TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); michael@0: michael@0: // Notifies the unit test event listeners that a test is about to start. michael@0: repeater->OnTestStart(*this); michael@0: michael@0: const TimeInMillis start = internal::GetTimeInMillis(); michael@0: michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: michael@0: // Creates the test object. michael@0: Test* const test = internal::HandleExceptionsInMethodIfSupported( michael@0: factory_, &internal::TestFactoryBase::CreateTest, michael@0: "the test fixture's constructor"); michael@0: michael@0: // Runs the test only if the test object was created and its michael@0: // constructor didn't generate a fatal failure. michael@0: if ((test != NULL) && !Test::HasFatalFailure()) { michael@0: // This doesn't throw as all user code that can throw are wrapped into michael@0: // exception handling code. michael@0: test->Run(); michael@0: } michael@0: michael@0: // Deletes the test object. michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported( michael@0: test, &Test::DeleteSelf_, "the test fixture's destructor"); michael@0: michael@0: result_.set_elapsed_time(internal::GetTimeInMillis() - start); michael@0: michael@0: // Notifies the unit test event listener that a test has just finished. michael@0: repeater->OnTestEnd(*this); michael@0: michael@0: // Tells UnitTest to stop associating assertion results to this michael@0: // test. michael@0: impl->set_current_test_info(NULL); michael@0: } michael@0: michael@0: // class TestCase michael@0: michael@0: // Gets the number of successful tests in this test case. michael@0: int TestCase::successful_test_count() const { michael@0: return CountIf(test_info_list_, TestPassed); michael@0: } michael@0: michael@0: // Gets the number of failed tests in this test case. michael@0: int TestCase::failed_test_count() const { michael@0: return CountIf(test_info_list_, TestFailed); michael@0: } michael@0: michael@0: int TestCase::disabled_test_count() const { michael@0: return CountIf(test_info_list_, TestDisabled); michael@0: } michael@0: michael@0: // Get the number of tests in this test case that should run. michael@0: int TestCase::test_to_run_count() const { michael@0: return CountIf(test_info_list_, ShouldRunTest); michael@0: } michael@0: michael@0: // Gets the number of all tests. michael@0: int TestCase::total_test_count() const { michael@0: return static_cast(test_info_list_.size()); michael@0: } michael@0: michael@0: // Creates a TestCase with the given name. michael@0: // michael@0: // Arguments: michael@0: // michael@0: // name: name of the test case michael@0: // a_type_param: the name of the test case's type parameter, or NULL if michael@0: // this is not a typed or a type-parameterized test case. michael@0: // set_up_tc: pointer to the function that sets up the test case michael@0: // tear_down_tc: pointer to the function that tears down the test case michael@0: TestCase::TestCase(const char* a_name, const char* a_type_param, michael@0: Test::SetUpTestCaseFunc set_up_tc, michael@0: Test::TearDownTestCaseFunc tear_down_tc) michael@0: : name_(a_name), michael@0: type_param_(a_type_param ? new std::string(a_type_param) : NULL), michael@0: set_up_tc_(set_up_tc), michael@0: tear_down_tc_(tear_down_tc), michael@0: should_run_(false), michael@0: elapsed_time_(0) { michael@0: } michael@0: michael@0: // Destructor of TestCase. michael@0: TestCase::~TestCase() { michael@0: // Deletes every Test in the collection. michael@0: ForEach(test_info_list_, internal::Delete); michael@0: } michael@0: michael@0: // Returns the i-th test among all the tests. i can range from 0 to michael@0: // total_test_count() - 1. If i is not in that range, returns NULL. michael@0: const TestInfo* TestCase::GetTestInfo(int i) const { michael@0: const int index = GetElementOr(test_indices_, i, -1); michael@0: return index < 0 ? NULL : test_info_list_[index]; michael@0: } michael@0: michael@0: // Returns the i-th test among all the tests. i can range from 0 to michael@0: // total_test_count() - 1. If i is not in that range, returns NULL. michael@0: TestInfo* TestCase::GetMutableTestInfo(int i) { michael@0: const int index = GetElementOr(test_indices_, i, -1); michael@0: return index < 0 ? NULL : test_info_list_[index]; michael@0: } michael@0: michael@0: // Adds a test to this test case. Will delete the test upon michael@0: // destruction of the TestCase object. michael@0: void TestCase::AddTestInfo(TestInfo * test_info) { michael@0: test_info_list_.push_back(test_info); michael@0: test_indices_.push_back(static_cast(test_indices_.size())); michael@0: } michael@0: michael@0: // Runs every test in this TestCase. michael@0: void TestCase::Run() { michael@0: if (!should_run_) return; michael@0: michael@0: internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); michael@0: impl->set_current_test_case(this); michael@0: michael@0: TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); michael@0: michael@0: repeater->OnTestCaseStart(*this); michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported( michael@0: this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); michael@0: michael@0: const internal::TimeInMillis start = internal::GetTimeInMillis(); michael@0: for (int i = 0; i < total_test_count(); i++) { michael@0: GetMutableTestInfo(i)->Run(); michael@0: } michael@0: elapsed_time_ = internal::GetTimeInMillis() - start; michael@0: michael@0: impl->os_stack_trace_getter()->UponLeavingGTest(); michael@0: internal::HandleExceptionsInMethodIfSupported( michael@0: this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); michael@0: michael@0: repeater->OnTestCaseEnd(*this); michael@0: impl->set_current_test_case(NULL); michael@0: } michael@0: michael@0: // Clears the results of all tests in this test case. michael@0: void TestCase::ClearResult() { michael@0: ForEach(test_info_list_, TestInfo::ClearTestResult); michael@0: } michael@0: michael@0: // Shuffles the tests in this test case. michael@0: void TestCase::ShuffleTests(internal::Random* random) { michael@0: Shuffle(random, &test_indices_); michael@0: } michael@0: michael@0: // Restores the test order to before the first shuffle. michael@0: void TestCase::UnshuffleTests() { michael@0: for (size_t i = 0; i < test_indices_.size(); i++) { michael@0: test_indices_[i] = static_cast(i); michael@0: } michael@0: } michael@0: michael@0: // Formats a countable noun. Depending on its quantity, either the michael@0: // singular form or the plural form is used. e.g. michael@0: // michael@0: // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". michael@0: // FormatCountableNoun(5, "book", "books") returns "5 books". michael@0: static internal::String FormatCountableNoun(int count, michael@0: const char * singular_form, michael@0: const char * plural_form) { michael@0: return internal::String::Format("%d %s", count, michael@0: count == 1 ? singular_form : plural_form); michael@0: } michael@0: michael@0: // Formats the count of tests. michael@0: static internal::String FormatTestCount(int test_count) { michael@0: return FormatCountableNoun(test_count, "test", "tests"); michael@0: } michael@0: michael@0: // Formats the count of test cases. michael@0: static internal::String FormatTestCaseCount(int test_case_count) { michael@0: return FormatCountableNoun(test_case_count, "test case", "test cases"); michael@0: } michael@0: michael@0: // Converts a TestPartResult::Type enum to human-friendly string michael@0: // representation. Both kNonFatalFailure and kFatalFailure are translated michael@0: // to "Failure", as the user usually doesn't care about the difference michael@0: // between the two when viewing the test result. michael@0: static const char * TestPartResultTypeToString(TestPartResult::Type type) { michael@0: switch (type) { michael@0: case TestPartResult::kSuccess: michael@0: return "Success"; michael@0: michael@0: case TestPartResult::kNonFatalFailure: michael@0: case TestPartResult::kFatalFailure: michael@0: #ifdef _MSC_VER michael@0: return "error: "; michael@0: #else michael@0: return "Failure\n"; michael@0: #endif michael@0: default: michael@0: return "Unknown result type"; michael@0: } michael@0: } michael@0: michael@0: // Prints a TestPartResult to a String. michael@0: static internal::String PrintTestPartResultToString( michael@0: const TestPartResult& test_part_result) { michael@0: return (Message() michael@0: << internal::FormatFileLocation(test_part_result.file_name(), michael@0: test_part_result.line_number()) michael@0: << " " << TestPartResultTypeToString(test_part_result.type()) michael@0: << test_part_result.message()).GetString(); michael@0: } michael@0: michael@0: // Prints a TestPartResult. michael@0: static void PrintTestPartResult(const TestPartResult& test_part_result) { michael@0: const internal::String& result = michael@0: PrintTestPartResultToString(test_part_result); michael@0: printf("%s\n", result.c_str()); michael@0: fflush(stdout); michael@0: // If the test program runs in Visual Studio or a debugger, the michael@0: // following statements add the test part result message to the Output michael@0: // window such that the user can double-click on it to jump to the michael@0: // corresponding source code location; otherwise they do nothing. michael@0: #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE michael@0: // We don't call OutputDebugString*() on Windows Mobile, as printing michael@0: // to stdout is done by OutputDebugString() there already - we don't michael@0: // want the same message printed twice. michael@0: ::OutputDebugStringA(result.c_str()); michael@0: ::OutputDebugStringA("\n"); michael@0: #endif michael@0: } michael@0: michael@0: // class PrettyUnitTestResultPrinter michael@0: michael@0: namespace internal { michael@0: michael@0: enum GTestColor { michael@0: COLOR_DEFAULT, michael@0: COLOR_RED, michael@0: COLOR_GREEN, michael@0: COLOR_YELLOW michael@0: }; michael@0: michael@0: #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Returns the character attribute for the given color. michael@0: WORD GetColorAttribute(GTestColor color) { michael@0: switch (color) { michael@0: case COLOR_RED: return FOREGROUND_RED; michael@0: case COLOR_GREEN: return FOREGROUND_GREEN; michael@0: case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; michael@0: default: return 0; michael@0: } michael@0: } michael@0: michael@0: #else michael@0: michael@0: // Returns the ANSI color code for the given color. COLOR_DEFAULT is michael@0: // an invalid input. michael@0: const char* GetAnsiColorCode(GTestColor color) { michael@0: switch (color) { michael@0: case COLOR_RED: return "1"; michael@0: case COLOR_GREEN: return "2"; michael@0: case COLOR_YELLOW: return "3"; michael@0: default: return NULL; michael@0: }; michael@0: } michael@0: michael@0: #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Returns true iff Google Test should use colors in the output. michael@0: bool ShouldUseColor(bool stdout_is_tty) { michael@0: const char* const gtest_color = GTEST_FLAG(color).c_str(); michael@0: michael@0: if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { michael@0: #if GTEST_OS_WINDOWS michael@0: // On Windows the TERM variable is usually not set, but the michael@0: // console there does support colors. michael@0: return stdout_is_tty; michael@0: #else michael@0: // On non-Windows platforms, we rely on the TERM variable. michael@0: const char* const term = posix::GetEnv("TERM"); michael@0: const bool term_supports_color = michael@0: String::CStringEquals(term, "xterm") || michael@0: String::CStringEquals(term, "xterm-color") || michael@0: String::CStringEquals(term, "xterm-256color") || michael@0: String::CStringEquals(term, "screen") || michael@0: String::CStringEquals(term, "linux") || michael@0: String::CStringEquals(term, "cygwin"); michael@0: return stdout_is_tty && term_supports_color; michael@0: #endif // GTEST_OS_WINDOWS michael@0: } michael@0: michael@0: return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || michael@0: String::CaseInsensitiveCStringEquals(gtest_color, "true") || michael@0: String::CaseInsensitiveCStringEquals(gtest_color, "t") || michael@0: String::CStringEquals(gtest_color, "1"); michael@0: // We take "yes", "true", "t", and "1" as meaning "yes". If the michael@0: // value is neither one of these nor "auto", we treat it as "no" to michael@0: // be conservative. michael@0: } michael@0: michael@0: // Helpers for printing colored strings to stdout. Note that on Windows, we michael@0: // cannot simply emit special characters and have the terminal change colors. michael@0: // This routine must actually emit the characters rather than return a string michael@0: // that would be colored when printed, as can be done on Linux. michael@0: void ColoredPrintf(GTestColor color, const char* fmt, ...) { michael@0: va_list args; michael@0: va_start(args, fmt); michael@0: michael@0: #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS michael@0: const bool use_color = false; michael@0: #else michael@0: static const bool in_color_mode = michael@0: ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); michael@0: const bool use_color = in_color_mode && (color != COLOR_DEFAULT); michael@0: #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS michael@0: // The '!= 0' comparison is necessary to satisfy MSVC 7.1. michael@0: michael@0: if (!use_color) { michael@0: vprintf(fmt, args); michael@0: va_end(args); michael@0: return; michael@0: } michael@0: michael@0: #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE michael@0: const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); michael@0: michael@0: // Gets the current text color. michael@0: CONSOLE_SCREEN_BUFFER_INFO buffer_info; michael@0: GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); michael@0: const WORD old_color_attrs = buffer_info.wAttributes; michael@0: michael@0: // We need to flush the stream buffers into the console before each michael@0: // SetConsoleTextAttribute call lest it affect the text that is already michael@0: // printed but has not yet reached the console. michael@0: fflush(stdout); michael@0: SetConsoleTextAttribute(stdout_handle, michael@0: GetColorAttribute(color) | FOREGROUND_INTENSITY); michael@0: vprintf(fmt, args); michael@0: michael@0: fflush(stdout); michael@0: // Restores the text color. michael@0: SetConsoleTextAttribute(stdout_handle, old_color_attrs); michael@0: #else michael@0: printf("\033[0;3%sm", GetAnsiColorCode(color)); michael@0: vprintf(fmt, args); michael@0: printf("\033[m"); // Resets the terminal to default. michael@0: #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE michael@0: va_end(args); michael@0: } michael@0: michael@0: void PrintFullTestCommentIfPresent(const TestInfo& test_info) { michael@0: const char* const type_param = test_info.type_param(); michael@0: const char* const value_param = test_info.value_param(); michael@0: michael@0: if (type_param != NULL || value_param != NULL) { michael@0: printf(", where "); michael@0: if (type_param != NULL) { michael@0: printf("TypeParam = %s", type_param); michael@0: if (value_param != NULL) michael@0: printf(" and "); michael@0: } michael@0: if (value_param != NULL) { michael@0: printf("GetParam() = %s", value_param); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // This class implements the TestEventListener interface. michael@0: // michael@0: // Class PrettyUnitTestResultPrinter is copyable. michael@0: class PrettyUnitTestResultPrinter : public TestEventListener { michael@0: public: michael@0: PrettyUnitTestResultPrinter() {} michael@0: static void PrintTestName(const char * test_case, const char * test) { michael@0: printf("%s.%s", test_case, test); michael@0: } michael@0: michael@0: // The following methods override what's in the TestEventListener class. michael@0: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} michael@0: virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); michael@0: virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); michael@0: virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} michael@0: virtual void OnTestCaseStart(const TestCase& test_case); michael@0: virtual void OnTestStart(const TestInfo& test_info); michael@0: virtual void OnTestPartResult(const TestPartResult& result); michael@0: virtual void OnTestEnd(const TestInfo& test_info); michael@0: virtual void OnTestCaseEnd(const TestCase& test_case); michael@0: virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); michael@0: virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} michael@0: virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); michael@0: virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} michael@0: michael@0: private: michael@0: static void PrintFailedTests(const UnitTest& unit_test); michael@0: }; michael@0: michael@0: // Fired before each iteration of tests starts. michael@0: void PrettyUnitTestResultPrinter::OnTestIterationStart( michael@0: const UnitTest& unit_test, int iteration) { michael@0: if (GTEST_FLAG(repeat) != 1) michael@0: printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); michael@0: michael@0: const char* const filter = GTEST_FLAG(filter).c_str(); michael@0: michael@0: // Prints the filter if it's not *. This reminds the user that some michael@0: // tests may be skipped. michael@0: if (!internal::String::CStringEquals(filter, kUniversalFilter)) { michael@0: ColoredPrintf(COLOR_YELLOW, michael@0: "Note: %s filter = %s\n", GTEST_NAME_, filter); michael@0: } michael@0: michael@0: if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { michael@0: const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); michael@0: ColoredPrintf(COLOR_YELLOW, michael@0: "Note: This is test shard %d of %s.\n", michael@0: static_cast(shard_index) + 1, michael@0: internal::posix::GetEnv(kTestTotalShards)); michael@0: } michael@0: michael@0: if (GTEST_FLAG(shuffle)) { michael@0: ColoredPrintf(COLOR_YELLOW, michael@0: "Note: Randomizing tests' orders with a seed of %d .\n", michael@0: unit_test.random_seed()); michael@0: } michael@0: michael@0: ColoredPrintf(COLOR_GREEN, "[==========] "); michael@0: printf("Running %s from %s.\n", michael@0: FormatTestCount(unit_test.test_to_run_count()).c_str(), michael@0: FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( michael@0: const UnitTest& /*unit_test*/) { michael@0: ColoredPrintf(COLOR_GREEN, "[----------] "); michael@0: printf("Global test environment set-up.\n"); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { michael@0: const internal::String counts = michael@0: FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); michael@0: ColoredPrintf(COLOR_GREEN, "[----------] "); michael@0: printf("%s from %s", counts.c_str(), test_case.name()); michael@0: if (test_case.type_param() == NULL) { michael@0: printf("\n"); michael@0: } else { michael@0: printf(", where TypeParam = %s\n", test_case.type_param()); michael@0: } michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { michael@0: ColoredPrintf(COLOR_GREEN, "[ RUN ] "); michael@0: PrintTestName(test_info.test_case_name(), test_info.name()); michael@0: printf("\n"); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: // Called after an assertion failure. michael@0: void PrettyUnitTestResultPrinter::OnTestPartResult( michael@0: const TestPartResult& result) { michael@0: // If the test part succeeded, we don't need to do anything. michael@0: if (result.type() == TestPartResult::kSuccess) michael@0: return; michael@0: michael@0: // Print failure message from the assertion (e.g. expected this and got that). michael@0: PrintTestPartResult(result); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { michael@0: if (test_info.result()->Passed()) { michael@0: ColoredPrintf(COLOR_GREEN, "[ OK ] "); michael@0: } else { michael@0: ColoredPrintf(COLOR_RED, "[ FAILED ] "); michael@0: } michael@0: PrintTestName(test_info.test_case_name(), test_info.name()); michael@0: if (test_info.result()->Failed()) michael@0: PrintFullTestCommentIfPresent(test_info); michael@0: michael@0: if (GTEST_FLAG(print_time)) { michael@0: printf(" (%s ms)\n", internal::StreamableToString( michael@0: test_info.result()->elapsed_time()).c_str()); michael@0: } else { michael@0: printf("\n"); michael@0: } michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { michael@0: if (!GTEST_FLAG(print_time)) return; michael@0: michael@0: const internal::String counts = michael@0: FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); michael@0: ColoredPrintf(COLOR_GREEN, "[----------] "); michael@0: printf("%s from %s (%s ms total)\n\n", michael@0: counts.c_str(), test_case.name(), michael@0: internal::StreamableToString(test_case.elapsed_time()).c_str()); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( michael@0: const UnitTest& /*unit_test*/) { michael@0: ColoredPrintf(COLOR_GREEN, "[----------] "); michael@0: printf("Global test environment tear-down\n"); michael@0: fflush(stdout); michael@0: } michael@0: michael@0: // Internal helper for printing the list of failed tests. michael@0: void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { michael@0: const int failed_test_count = unit_test.failed_test_count(); michael@0: if (failed_test_count == 0) { michael@0: return; michael@0: } michael@0: michael@0: for (int i = 0; i < unit_test.total_test_case_count(); ++i) { michael@0: const TestCase& test_case = *unit_test.GetTestCase(i); michael@0: if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { michael@0: continue; michael@0: } michael@0: for (int j = 0; j < test_case.total_test_count(); ++j) { michael@0: const TestInfo& test_info = *test_case.GetTestInfo(j); michael@0: if (!test_info.should_run() || test_info.result()->Passed()) { michael@0: continue; michael@0: } michael@0: ColoredPrintf(COLOR_RED, "[ FAILED ] "); michael@0: printf("%s.%s", test_case.name(), test_info.name()); michael@0: PrintFullTestCommentIfPresent(test_info); michael@0: printf("\n"); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, michael@0: int /*iteration*/) { michael@0: ColoredPrintf(COLOR_GREEN, "[==========] "); michael@0: printf("%s from %s ran.", michael@0: FormatTestCount(unit_test.test_to_run_count()).c_str(), michael@0: FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); michael@0: if (GTEST_FLAG(print_time)) { michael@0: printf(" (%s ms total)", michael@0: internal::StreamableToString(unit_test.elapsed_time()).c_str()); michael@0: } michael@0: printf("\n"); michael@0: ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); michael@0: printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); michael@0: michael@0: int num_failures = unit_test.failed_test_count(); michael@0: if (!unit_test.Passed()) { michael@0: const int failed_test_count = unit_test.failed_test_count(); michael@0: ColoredPrintf(COLOR_RED, "[ FAILED ] "); michael@0: printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); michael@0: PrintFailedTests(unit_test); michael@0: printf("\n%2d FAILED %s\n", num_failures, michael@0: num_failures == 1 ? "TEST" : "TESTS"); michael@0: } michael@0: michael@0: int num_disabled = unit_test.disabled_test_count(); michael@0: if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { michael@0: if (!num_failures) { michael@0: printf("\n"); // Add a spacer if no FAILURE banner is displayed. michael@0: } michael@0: ColoredPrintf(COLOR_YELLOW, michael@0: " YOU HAVE %d DISABLED %s\n\n", michael@0: num_disabled, michael@0: num_disabled == 1 ? "TEST" : "TESTS"); michael@0: } michael@0: // Ensure that Google Test output is printed before, e.g., heapchecker output. michael@0: fflush(stdout); michael@0: } michael@0: michael@0: // End PrettyUnitTestResultPrinter michael@0: michael@0: // class TestEventRepeater michael@0: // michael@0: // This class forwards events to other event listeners. michael@0: class TestEventRepeater : public TestEventListener { michael@0: public: michael@0: TestEventRepeater() : forwarding_enabled_(true) {} michael@0: virtual ~TestEventRepeater(); michael@0: void Append(TestEventListener *listener); michael@0: TestEventListener* Release(TestEventListener* listener); michael@0: michael@0: // Controls whether events will be forwarded to listeners_. Set to false michael@0: // in death test child processes. michael@0: bool forwarding_enabled() const { return forwarding_enabled_; } michael@0: void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } michael@0: michael@0: virtual void OnTestProgramStart(const UnitTest& unit_test); michael@0: virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); michael@0: virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); michael@0: virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); michael@0: virtual void OnTestCaseStart(const TestCase& test_case); michael@0: virtual void OnTestStart(const TestInfo& test_info); michael@0: virtual void OnTestPartResult(const TestPartResult& result); michael@0: virtual void OnTestEnd(const TestInfo& test_info); michael@0: virtual void OnTestCaseEnd(const TestCase& test_case); michael@0: virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); michael@0: virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); michael@0: virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); michael@0: virtual void OnTestProgramEnd(const UnitTest& unit_test); michael@0: michael@0: private: michael@0: // Controls whether events will be forwarded to listeners_. Set to false michael@0: // in death test child processes. michael@0: bool forwarding_enabled_; michael@0: // The list of listeners that receive events. michael@0: std::vector listeners_; michael@0: michael@0: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); michael@0: }; michael@0: michael@0: TestEventRepeater::~TestEventRepeater() { michael@0: ForEach(listeners_, Delete); michael@0: } michael@0: michael@0: void TestEventRepeater::Append(TestEventListener *listener) { michael@0: listeners_.push_back(listener); michael@0: } michael@0: michael@0: // TODO(vladl@google.com): Factor the search functionality into Vector::Find. michael@0: TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { michael@0: for (size_t i = 0; i < listeners_.size(); ++i) { michael@0: if (listeners_[i] == listener) { michael@0: listeners_.erase(listeners_.begin() + i); michael@0: return listener; michael@0: } michael@0: } michael@0: michael@0: return NULL; michael@0: } michael@0: michael@0: // Since most methods are very similar, use macros to reduce boilerplate. michael@0: // This defines a member that forwards the call to all listeners. michael@0: #define GTEST_REPEATER_METHOD_(Name, Type) \ michael@0: void TestEventRepeater::Name(const Type& parameter) { \ michael@0: if (forwarding_enabled_) { \ michael@0: for (size_t i = 0; i < listeners_.size(); i++) { \ michael@0: listeners_[i]->Name(parameter); \ michael@0: } \ michael@0: } \ michael@0: } michael@0: // This defines a member that forwards the call to all listeners in reverse michael@0: // order. michael@0: #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ michael@0: void TestEventRepeater::Name(const Type& parameter) { \ michael@0: if (forwarding_enabled_) { \ michael@0: for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ michael@0: listeners_[i]->Name(parameter); \ michael@0: } \ michael@0: } \ michael@0: } michael@0: michael@0: GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) michael@0: GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) michael@0: GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) michael@0: GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) michael@0: GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) michael@0: GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) michael@0: GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) michael@0: GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) michael@0: GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) michael@0: GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) michael@0: GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) michael@0: michael@0: #undef GTEST_REPEATER_METHOD_ michael@0: #undef GTEST_REVERSE_REPEATER_METHOD_ michael@0: michael@0: void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, michael@0: int iteration) { michael@0: if (forwarding_enabled_) { michael@0: for (size_t i = 0; i < listeners_.size(); i++) { michael@0: listeners_[i]->OnTestIterationStart(unit_test, iteration); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, michael@0: int iteration) { michael@0: if (forwarding_enabled_) { michael@0: for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { michael@0: listeners_[i]->OnTestIterationEnd(unit_test, iteration); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // End TestEventRepeater michael@0: michael@0: // This class generates an XML output file. michael@0: class XmlUnitTestResultPrinter : public EmptyTestEventListener { michael@0: public: michael@0: explicit XmlUnitTestResultPrinter(const char* output_file); michael@0: michael@0: virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); michael@0: michael@0: private: michael@0: // Is c a whitespace character that is normalized to a space character michael@0: // when it appears in an XML attribute value? michael@0: static bool IsNormalizableWhitespace(char c) { michael@0: return c == 0x9 || c == 0xA || c == 0xD; michael@0: } michael@0: michael@0: // May c appear in a well-formed XML document? michael@0: static bool IsValidXmlCharacter(char c) { michael@0: return IsNormalizableWhitespace(c) || c >= 0x20; michael@0: } michael@0: michael@0: // Returns an XML-escaped copy of the input string str. If michael@0: // is_attribute is true, the text is meant to appear as an attribute michael@0: // value, and normalizable whitespace is preserved by replacing it michael@0: // with character references. michael@0: static String EscapeXml(const char* str, bool is_attribute); michael@0: michael@0: // Returns the given string with all characters invalid in XML removed. michael@0: static string RemoveInvalidXmlCharacters(const string& str); michael@0: michael@0: // Convenience wrapper around EscapeXml when str is an attribute value. michael@0: static String EscapeXmlAttribute(const char* str) { michael@0: return EscapeXml(str, true); michael@0: } michael@0: michael@0: // Convenience wrapper around EscapeXml when str is not an attribute value. michael@0: static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } michael@0: michael@0: // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. michael@0: static void OutputXmlCDataSection(::std::ostream* stream, const char* data); michael@0: michael@0: // Streams an XML representation of a TestInfo object. michael@0: static void OutputXmlTestInfo(::std::ostream* stream, michael@0: const char* test_case_name, michael@0: const TestInfo& test_info); michael@0: michael@0: // Prints an XML representation of a TestCase object michael@0: static void PrintXmlTestCase(FILE* out, const TestCase& test_case); michael@0: michael@0: // Prints an XML summary of unit_test to output stream out. michael@0: static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test); michael@0: michael@0: // Produces a string representing the test properties in a result as space michael@0: // delimited XML attributes based on the property key="value" pairs. michael@0: // When the String is not empty, it includes a space at the beginning, michael@0: // to delimit this attribute from prior attributes. michael@0: static String TestPropertiesAsXmlAttributes(const TestResult& result); michael@0: michael@0: // The output file. michael@0: const String output_file_; michael@0: michael@0: GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); michael@0: }; michael@0: michael@0: // Creates a new XmlUnitTestResultPrinter. michael@0: XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) michael@0: : output_file_(output_file) { michael@0: if (output_file_.c_str() == NULL || output_file_.empty()) { michael@0: fprintf(stderr, "XML output file may not be null\n"); michael@0: fflush(stderr); michael@0: exit(EXIT_FAILURE); michael@0: } michael@0: } michael@0: michael@0: // Called after the unit test ends. michael@0: void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, michael@0: int /*iteration*/) { michael@0: FILE* xmlout = NULL; michael@0: FilePath output_file(output_file_); michael@0: FilePath output_dir(output_file.RemoveFileName()); michael@0: michael@0: if (output_dir.CreateDirectoriesRecursively()) { michael@0: xmlout = posix::FOpen(output_file_.c_str(), "w"); michael@0: } michael@0: if (xmlout == NULL) { michael@0: // TODO(wan): report the reason of the failure. michael@0: // michael@0: // We don't do it for now as: michael@0: // michael@0: // 1. There is no urgent need for it. michael@0: // 2. It's a bit involved to make the errno variable thread-safe on michael@0: // all three operating systems (Linux, Windows, and Mac OS). michael@0: // 3. To interpret the meaning of errno in a thread-safe way, michael@0: // we need the strerror_r() function, which is not available on michael@0: // Windows. michael@0: fprintf(stderr, michael@0: "Unable to open file \"%s\"\n", michael@0: output_file_.c_str()); michael@0: fflush(stderr); michael@0: exit(EXIT_FAILURE); michael@0: } michael@0: PrintXmlUnitTest(xmlout, unit_test); michael@0: fclose(xmlout); michael@0: } michael@0: michael@0: // Returns an XML-escaped copy of the input string str. If is_attribute michael@0: // is true, the text is meant to appear as an attribute value, and michael@0: // normalizable whitespace is preserved by replacing it with character michael@0: // references. michael@0: // michael@0: // Invalid XML characters in str, if any, are stripped from the output. michael@0: // It is expected that most, if not all, of the text processed by this michael@0: // module will consist of ordinary English text. michael@0: // If this module is ever modified to produce version 1.1 XML output, michael@0: // most invalid characters can be retained using character references. michael@0: // TODO(wan): It might be nice to have a minimally invasive, human-readable michael@0: // escaping scheme for invalid characters, rather than dropping them. michael@0: String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { michael@0: Message m; michael@0: michael@0: if (str != NULL) { michael@0: for (const char* src = str; *src; ++src) { michael@0: switch (*src) { michael@0: case '<': michael@0: m << "<"; michael@0: break; michael@0: case '>': michael@0: m << ">"; michael@0: break; michael@0: case '&': michael@0: m << "&"; michael@0: break; michael@0: case '\'': michael@0: if (is_attribute) michael@0: m << "'"; michael@0: else michael@0: m << '\''; michael@0: break; michael@0: case '"': michael@0: if (is_attribute) michael@0: m << """; michael@0: else michael@0: m << '"'; michael@0: break; michael@0: default: michael@0: if (IsValidXmlCharacter(*src)) { michael@0: if (is_attribute && IsNormalizableWhitespace(*src)) michael@0: m << String::Format("&#x%02X;", unsigned(*src)); michael@0: else michael@0: m << *src; michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: return m.GetString(); michael@0: } michael@0: michael@0: // Returns the given string with all characters invalid in XML removed. michael@0: // Currently invalid characters are dropped from the string. An michael@0: // alternative is to replace them with certain characters such as . or ?. michael@0: string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) { michael@0: string output; michael@0: output.reserve(str.size()); michael@0: for (string::const_iterator it = str.begin(); it != str.end(); ++it) michael@0: if (IsValidXmlCharacter(*it)) michael@0: output.push_back(*it); michael@0: michael@0: return output; michael@0: } michael@0: michael@0: // The following routines generate an XML representation of a UnitTest michael@0: // object. michael@0: // michael@0: // This is how Google Test concepts map to the DTD: michael@0: // michael@0: // <-- corresponds to a UnitTest object michael@0: // <-- corresponds to a TestCase object michael@0: // <-- corresponds to a TestInfo object michael@0: // ... michael@0: // ... michael@0: // ... michael@0: // <-- individual assertion failures michael@0: // michael@0: // michael@0: // michael@0: michael@0: // Formats the given time in milliseconds as seconds. michael@0: std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { michael@0: ::std::stringstream ss; michael@0: ss << ms/1000.0; michael@0: return ss.str(); michael@0: } michael@0: michael@0: // Converts the given epoch time in milliseconds to a date string in the ISO michael@0: // 8601 format, without the timezone information. michael@0: std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { michael@0: // Using non-reentrant version as localtime_r is not portable. michael@0: time_t seconds = static_cast(ms / 1000); michael@0: #ifdef _MSC_VER michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4996) // Temporarily disables warning 4996 michael@0: // (function or variable may be unsafe). michael@0: const struct tm* const time_struct = localtime(&seconds); // NOLINT michael@0: # pragma warning(pop) // Restores the warning state again. michael@0: #else michael@0: const struct tm* const time_struct = localtime(&seconds); // NOLINT michael@0: #endif michael@0: if (time_struct == NULL) michael@0: return ""; // Invalid ms value michael@0: michael@0: return String::Format("%d-%02d-%02dT%02d:%02d:%02d", // YYYY-MM-DDThh:mm:ss michael@0: time_struct->tm_year + 1900, michael@0: time_struct->tm_mon + 1, michael@0: time_struct->tm_mday, michael@0: time_struct->tm_hour, michael@0: time_struct->tm_min, michael@0: time_struct->tm_sec); michael@0: } michael@0: michael@0: // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. michael@0: void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, michael@0: const char* data) { michael@0: const char* segment = data; michael@0: *stream << ""); michael@0: if (next_segment != NULL) { michael@0: stream->write( michael@0: segment, static_cast(next_segment - segment)); michael@0: *stream << "]]>]]>"); michael@0: } else { michael@0: *stream << segment; michael@0: break; michael@0: } michael@0: } michael@0: *stream << "]]>"; michael@0: } michael@0: michael@0: // Prints an XML representation of a TestInfo object. michael@0: // TODO(wan): There is also value in printing properties with the plain printer. michael@0: void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, michael@0: const char* test_case_name, michael@0: const TestInfo& test_info) { michael@0: const TestResult& result = *test_info.result(); michael@0: *stream << " \n"; michael@0: } michael@0: const string location = internal::FormatCompilerIndependentFileLocation( michael@0: part.file_name(), part.line_number()); michael@0: const string summary = location + "\n" + part.summary(); michael@0: *stream << " "; michael@0: const string detail = location + "\n" + part.message(); michael@0: OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); michael@0: *stream << "\n"; michael@0: } michael@0: } michael@0: michael@0: if (failures == 0) michael@0: *stream << " />\n"; michael@0: else michael@0: *stream << " \n"; michael@0: } michael@0: michael@0: // Prints an XML representation of a TestCase object michael@0: void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, michael@0: const TestCase& test_case) { michael@0: fprintf(out, michael@0: " \n", michael@0: FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); michael@0: for (int i = 0; i < test_case.total_test_count(); ++i) { michael@0: ::std::stringstream stream; michael@0: OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); michael@0: fprintf(out, "%s", StringStreamToString(&stream).c_str()); michael@0: } michael@0: fprintf(out, " \n"); michael@0: } michael@0: michael@0: // Prints an XML summary of unit_test to output stream out. michael@0: void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, michael@0: const UnitTest& unit_test) { michael@0: fprintf(out, "\n"); michael@0: fprintf(out, michael@0: "\n"); michael@0: for (int i = 0; i < unit_test.total_test_case_count(); ++i) michael@0: PrintXmlTestCase(out, *unit_test.GetTestCase(i)); michael@0: fprintf(out, "\n"); michael@0: } michael@0: michael@0: // Produces a string representing the test properties in a result as space michael@0: // delimited XML attributes based on the property key="value" pairs. michael@0: String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( michael@0: const TestResult& result) { michael@0: Message attributes; michael@0: for (int i = 0; i < result.test_property_count(); ++i) { michael@0: const TestProperty& property = result.GetTestProperty(i); michael@0: attributes << " " << property.key() << "=" michael@0: << "\"" << EscapeXmlAttribute(property.value()) << "\""; michael@0: } michael@0: return attributes.GetString(); michael@0: } michael@0: michael@0: // End XmlUnitTestResultPrinter michael@0: michael@0: #if GTEST_CAN_STREAM_RESULTS_ michael@0: michael@0: // Streams test results to the given port on the given host machine. michael@0: class StreamingListener : public EmptyTestEventListener { michael@0: public: michael@0: // Escapes '=', '&', '%', and '\n' characters in str as "%xx". michael@0: static string UrlEncode(const char* str); michael@0: michael@0: StreamingListener(const string& host, const string& port) michael@0: : sockfd_(-1), host_name_(host), port_num_(port) { michael@0: MakeConnection(); michael@0: Send("gtest_streaming_protocol_version=1.0\n"); michael@0: } michael@0: michael@0: virtual ~StreamingListener() { michael@0: if (sockfd_ != -1) michael@0: CloseConnection(); michael@0: } michael@0: michael@0: void OnTestProgramStart(const UnitTest& /* unit_test */) { michael@0: Send("event=TestProgramStart\n"); michael@0: } michael@0: michael@0: void OnTestProgramEnd(const UnitTest& unit_test) { michael@0: // Note that Google Test current only report elapsed time for each michael@0: // test iteration, not for the entire test program. michael@0: Send(String::Format("event=TestProgramEnd&passed=%d\n", michael@0: unit_test.Passed())); michael@0: michael@0: // Notify the streaming server to stop. michael@0: CloseConnection(); michael@0: } michael@0: michael@0: void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { michael@0: Send(String::Format("event=TestIterationStart&iteration=%d\n", michael@0: iteration)); michael@0: } michael@0: michael@0: void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { michael@0: Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n", michael@0: unit_test.Passed(), michael@0: StreamableToString(unit_test.elapsed_time()).c_str())); michael@0: } michael@0: michael@0: void OnTestCaseStart(const TestCase& test_case) { michael@0: Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name())); michael@0: } michael@0: michael@0: void OnTestCaseEnd(const TestCase& test_case) { michael@0: Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n", michael@0: test_case.Passed(), michael@0: StreamableToString(test_case.elapsed_time()).c_str())); michael@0: } michael@0: michael@0: void OnTestStart(const TestInfo& test_info) { michael@0: Send(String::Format("event=TestStart&name=%s\n", test_info.name())); michael@0: } michael@0: michael@0: void OnTestEnd(const TestInfo& test_info) { michael@0: Send(String::Format( michael@0: "event=TestEnd&passed=%d&elapsed_time=%sms\n", michael@0: (test_info.result())->Passed(), michael@0: StreamableToString((test_info.result())->elapsed_time()).c_str())); michael@0: } michael@0: michael@0: void OnTestPartResult(const TestPartResult& test_part_result) { michael@0: const char* file_name = test_part_result.file_name(); michael@0: if (file_name == NULL) michael@0: file_name = ""; michael@0: Send(String::Format("event=TestPartResult&file=%s&line=%d&message=", michael@0: UrlEncode(file_name).c_str(), michael@0: test_part_result.line_number())); michael@0: Send(UrlEncode(test_part_result.message()) + "\n"); michael@0: } michael@0: michael@0: private: michael@0: // Creates a client socket and connects to the server. michael@0: void MakeConnection(); michael@0: michael@0: // Closes the socket. michael@0: void CloseConnection() { michael@0: GTEST_CHECK_(sockfd_ != -1) michael@0: << "CloseConnection() can be called only when there is a connection."; michael@0: michael@0: close(sockfd_); michael@0: sockfd_ = -1; michael@0: } michael@0: michael@0: // Sends a string to the socket. michael@0: void Send(const string& message) { michael@0: GTEST_CHECK_(sockfd_ != -1) michael@0: << "Send() can be called only when there is a connection."; michael@0: michael@0: const int len = static_cast(message.length()); michael@0: if (write(sockfd_, message.c_str(), len) != len) { michael@0: GTEST_LOG_(WARNING) michael@0: << "stream_result_to: failed to stream to " michael@0: << host_name_ << ":" << port_num_; michael@0: } michael@0: } michael@0: michael@0: int sockfd_; // socket file descriptor michael@0: const string host_name_; michael@0: const string port_num_; michael@0: michael@0: GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); michael@0: }; // class StreamingListener michael@0: michael@0: // Checks if str contains '=', '&', '%' or '\n' characters. If yes, michael@0: // replaces them by "%xx" where xx is their hexadecimal value. For michael@0: // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) michael@0: // in both time and space -- important as the input str may contain an michael@0: // arbitrarily long test failure message and stack trace. michael@0: string StreamingListener::UrlEncode(const char* str) { michael@0: string result; michael@0: result.reserve(strlen(str) + 1); michael@0: for (char ch = *str; ch != '\0'; ch = *++str) { michael@0: switch (ch) { michael@0: case '%': michael@0: case '=': michael@0: case '&': michael@0: case '\n': michael@0: result.append(String::Format("%%%02x", static_cast(ch))); michael@0: break; michael@0: default: michael@0: result.push_back(ch); michael@0: break; michael@0: } michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: void StreamingListener::MakeConnection() { michael@0: GTEST_CHECK_(sockfd_ == -1) michael@0: << "MakeConnection() can't be called when there is already a connection."; michael@0: michael@0: addrinfo hints; michael@0: memset(&hints, 0, sizeof(hints)); michael@0: hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. michael@0: hints.ai_socktype = SOCK_STREAM; michael@0: addrinfo* servinfo = NULL; michael@0: michael@0: // Use the getaddrinfo() to get a linked list of IP addresses for michael@0: // the given host name. michael@0: const int error_num = getaddrinfo( michael@0: host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); michael@0: if (error_num != 0) { michael@0: GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " michael@0: << gai_strerror(error_num); michael@0: } michael@0: michael@0: // Loop through all the results and connect to the first we can. michael@0: for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; michael@0: cur_addr = cur_addr->ai_next) { michael@0: sockfd_ = socket( michael@0: cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); michael@0: if (sockfd_ != -1) { michael@0: // Connect the client socket to the server socket. michael@0: if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { michael@0: close(sockfd_); michael@0: sockfd_ = -1; michael@0: } michael@0: } michael@0: } michael@0: michael@0: freeaddrinfo(servinfo); // all done with this structure michael@0: michael@0: if (sockfd_ == -1) { michael@0: GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " michael@0: << host_name_ << ":" << port_num_; michael@0: } michael@0: } michael@0: michael@0: // End of class Streaming Listener michael@0: #endif // GTEST_CAN_STREAM_RESULTS__ michael@0: michael@0: // Class ScopedTrace michael@0: michael@0: // Pushes the given source file location and message onto a per-thread michael@0: // trace stack maintained by Google Test. michael@0: ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) michael@0: GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { michael@0: TraceInfo trace; michael@0: trace.file = file; michael@0: trace.line = line; michael@0: trace.message = message.GetString(); michael@0: michael@0: UnitTest::GetInstance()->PushGTestTrace(trace); michael@0: } michael@0: michael@0: // Pops the info pushed by the c'tor. michael@0: ScopedTrace::~ScopedTrace() michael@0: GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { michael@0: UnitTest::GetInstance()->PopGTestTrace(); michael@0: } michael@0: michael@0: michael@0: // class OsStackTraceGetter michael@0: michael@0: // Returns the current OS stack trace as a String. Parameters: michael@0: // michael@0: // max_depth - the maximum number of stack frames to be included michael@0: // in the trace. michael@0: // skip_count - the number of top frames to be skipped; doesn't count michael@0: // against max_depth. michael@0: // michael@0: String OsStackTraceGetter::CurrentStackTrace(int /* max_depth */, michael@0: int /* skip_count */) michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: return String(""); michael@0: } michael@0: michael@0: void OsStackTraceGetter::UponLeavingGTest() michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: } michael@0: michael@0: const char* const michael@0: OsStackTraceGetter::kElidedFramesMarker = michael@0: "... " GTEST_NAME_ " internal frames ..."; michael@0: michael@0: } // namespace internal michael@0: michael@0: // class TestEventListeners michael@0: michael@0: TestEventListeners::TestEventListeners() michael@0: : repeater_(new internal::TestEventRepeater()), michael@0: default_result_printer_(NULL), michael@0: default_xml_generator_(NULL) { michael@0: } michael@0: michael@0: TestEventListeners::~TestEventListeners() { delete repeater_; } michael@0: michael@0: // Returns the standard listener responsible for the default console michael@0: // output. Can be removed from the listeners list to shut down default michael@0: // console output. Note that removing this object from the listener list michael@0: // with Release transfers its ownership to the user. michael@0: void TestEventListeners::Append(TestEventListener* listener) { michael@0: repeater_->Append(listener); michael@0: } michael@0: michael@0: // Removes the given event listener from the list and returns it. It then michael@0: // becomes the caller's responsibility to delete the listener. Returns michael@0: // NULL if the listener is not found in the list. michael@0: TestEventListener* TestEventListeners::Release(TestEventListener* listener) { michael@0: if (listener == default_result_printer_) michael@0: default_result_printer_ = NULL; michael@0: else if (listener == default_xml_generator_) michael@0: default_xml_generator_ = NULL; michael@0: return repeater_->Release(listener); michael@0: } michael@0: michael@0: // Returns repeater that broadcasts the TestEventListener events to all michael@0: // subscribers. michael@0: TestEventListener* TestEventListeners::repeater() { return repeater_; } michael@0: michael@0: // Sets the default_result_printer attribute to the provided listener. michael@0: // The listener is also added to the listener list and previous michael@0: // default_result_printer is removed from it and deleted. The listener can michael@0: // also be NULL in which case it will not be added to the list. Does michael@0: // nothing if the previous and the current listener objects are the same. michael@0: void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { michael@0: if (default_result_printer_ != listener) { michael@0: // It is an error to pass this method a listener that is already in the michael@0: // list. michael@0: delete Release(default_result_printer_); michael@0: default_result_printer_ = listener; michael@0: if (listener != NULL) michael@0: Append(listener); michael@0: } michael@0: } michael@0: michael@0: // Sets the default_xml_generator attribute to the provided listener. The michael@0: // listener is also added to the listener list and previous michael@0: // default_xml_generator is removed from it and deleted. The listener can michael@0: // also be NULL in which case it will not be added to the list. Does michael@0: // nothing if the previous and the current listener objects are the same. michael@0: void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { michael@0: if (default_xml_generator_ != listener) { michael@0: // It is an error to pass this method a listener that is already in the michael@0: // list. michael@0: delete Release(default_xml_generator_); michael@0: default_xml_generator_ = listener; michael@0: if (listener != NULL) michael@0: Append(listener); michael@0: } michael@0: } michael@0: michael@0: // Controls whether events will be forwarded by the repeater to the michael@0: // listeners in the list. michael@0: bool TestEventListeners::EventForwardingEnabled() const { michael@0: return repeater_->forwarding_enabled(); michael@0: } michael@0: michael@0: void TestEventListeners::SuppressEventForwarding() { michael@0: repeater_->set_forwarding_enabled(false); michael@0: } michael@0: michael@0: // class UnitTest michael@0: michael@0: // Gets the singleton UnitTest object. The first time this method is michael@0: // called, a UnitTest object is constructed and returned. Consecutive michael@0: // calls will return the same object. michael@0: // michael@0: // We don't protect this under mutex_ as a user is not supposed to michael@0: // call this before main() starts, from which point on the return michael@0: // value will never change. michael@0: UnitTest * UnitTest::GetInstance() { michael@0: // When compiled with MSVC 7.1 in optimized mode, destroying the michael@0: // UnitTest object upon exiting the program messes up the exit code, michael@0: // causing successful tests to appear failed. We have to use a michael@0: // different implementation in this case to bypass the compiler bug. michael@0: // This implementation makes the compiler happy, at the cost of michael@0: // leaking the UnitTest object. michael@0: michael@0: // CodeGear C++Builder insists on a public destructor for the michael@0: // default implementation. Use this implementation to keep good OO michael@0: // design with private destructor. michael@0: michael@0: #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) michael@0: static UnitTest* const instance = new UnitTest; michael@0: return instance; michael@0: #else michael@0: static UnitTest instance; michael@0: return &instance; michael@0: #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) michael@0: } michael@0: michael@0: // Gets the number of successful test cases. michael@0: int UnitTest::successful_test_case_count() const { michael@0: return impl()->successful_test_case_count(); michael@0: } michael@0: michael@0: // Gets the number of failed test cases. michael@0: int UnitTest::failed_test_case_count() const { michael@0: return impl()->failed_test_case_count(); michael@0: } michael@0: michael@0: // Gets the number of all test cases. michael@0: int UnitTest::total_test_case_count() const { michael@0: return impl()->total_test_case_count(); michael@0: } michael@0: michael@0: // Gets the number of all test cases that contain at least one test michael@0: // that should run. michael@0: int UnitTest::test_case_to_run_count() const { michael@0: return impl()->test_case_to_run_count(); michael@0: } michael@0: michael@0: // Gets the number of successful tests. michael@0: int UnitTest::successful_test_count() const { michael@0: return impl()->successful_test_count(); michael@0: } michael@0: michael@0: // Gets the number of failed tests. michael@0: int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } michael@0: michael@0: // Gets the number of disabled tests. michael@0: int UnitTest::disabled_test_count() const { michael@0: return impl()->disabled_test_count(); michael@0: } michael@0: michael@0: // Gets the number of all tests. michael@0: int UnitTest::total_test_count() const { return impl()->total_test_count(); } michael@0: michael@0: // Gets the number of tests that should run. michael@0: int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } michael@0: michael@0: // Gets the time of the test program start, in ms from the start of the michael@0: // UNIX epoch. michael@0: internal::TimeInMillis UnitTest::start_timestamp() const { michael@0: return impl()->start_timestamp(); michael@0: } michael@0: michael@0: // Gets the elapsed time, in milliseconds. michael@0: internal::TimeInMillis UnitTest::elapsed_time() const { michael@0: return impl()->elapsed_time(); michael@0: } michael@0: michael@0: // Returns true iff the unit test passed (i.e. all test cases passed). michael@0: bool UnitTest::Passed() const { return impl()->Passed(); } michael@0: michael@0: // Returns true iff the unit test failed (i.e. some test case failed michael@0: // or something outside of all tests failed). michael@0: bool UnitTest::Failed() const { return impl()->Failed(); } michael@0: michael@0: // Gets the i-th test case among all the test cases. i can range from 0 to michael@0: // total_test_case_count() - 1. If i is not in that range, returns NULL. michael@0: const TestCase* UnitTest::GetTestCase(int i) const { michael@0: return impl()->GetTestCase(i); michael@0: } michael@0: michael@0: // Gets the i-th test case among all the test cases. i can range from 0 to michael@0: // total_test_case_count() - 1. If i is not in that range, returns NULL. michael@0: TestCase* UnitTest::GetMutableTestCase(int i) { michael@0: return impl()->GetMutableTestCase(i); michael@0: } michael@0: michael@0: // Returns the list of event listeners that can be used to track events michael@0: // inside Google Test. michael@0: TestEventListeners& UnitTest::listeners() { michael@0: return *impl()->listeners(); michael@0: } michael@0: michael@0: // Registers and returns a global test environment. When a test michael@0: // program is run, all global test environments will be set-up in the michael@0: // order they were registered. After all tests in the program have michael@0: // finished, all global test environments will be torn-down in the michael@0: // *reverse* order they were registered. michael@0: // michael@0: // The UnitTest object takes ownership of the given environment. michael@0: // michael@0: // We don't protect this under mutex_, as we only support calling it michael@0: // from the main thread. michael@0: Environment* UnitTest::AddEnvironment(Environment* env) { michael@0: if (env == NULL) { michael@0: return NULL; michael@0: } michael@0: michael@0: impl_->environments().push_back(env); michael@0: return env; michael@0: } michael@0: michael@0: // Adds a TestPartResult to the current TestResult object. All Google Test michael@0: // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call michael@0: // this to report their results. The user code should use the michael@0: // assertion macros instead of calling this directly. michael@0: void UnitTest::AddTestPartResult( michael@0: TestPartResult::Type result_type, michael@0: const char* file_name, michael@0: int line_number, michael@0: const internal::String& message, michael@0: const internal::String& os_stack_trace) michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: Message msg; michael@0: msg << message; michael@0: michael@0: internal::MutexLock lock(&mutex_); michael@0: if (impl_->gtest_trace_stack().size() > 0) { michael@0: msg << "\n" << GTEST_NAME_ << " trace:"; michael@0: michael@0: for (int i = static_cast(impl_->gtest_trace_stack().size()); michael@0: i > 0; --i) { michael@0: const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; michael@0: msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) michael@0: << " " << trace.message; michael@0: } michael@0: } michael@0: michael@0: if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { michael@0: msg << internal::kStackTraceMarker << os_stack_trace; michael@0: } michael@0: michael@0: const TestPartResult result = michael@0: TestPartResult(result_type, file_name, line_number, michael@0: msg.GetString().c_str()); michael@0: impl_->GetTestPartResultReporterForCurrentThread()-> michael@0: ReportTestPartResult(result); michael@0: michael@0: if (result_type != TestPartResult::kSuccess) { michael@0: // gtest_break_on_failure takes precedence over michael@0: // gtest_throw_on_failure. This allows a user to set the latter michael@0: // in the code (perhaps in order to use Google Test assertions michael@0: // with another testing framework) and specify the former on the michael@0: // command line for debugging. michael@0: if (GTEST_FLAG(break_on_failure)) { michael@0: #if GTEST_OS_WINDOWS michael@0: // Using DebugBreak on Windows allows gtest to still break into a debugger michael@0: // when a failure happens and both the --gtest_break_on_failure and michael@0: // the --gtest_catch_exceptions flags are specified. michael@0: DebugBreak(); michael@0: #else michael@0: // Dereference NULL through a volatile pointer to prevent the compiler michael@0: // from removing. We use this rather than abort() or __builtin_trap() for michael@0: // portability: Symbian doesn't implement abort() well, and some debuggers michael@0: // don't correctly trap abort(). michael@0: *static_cast(NULL) = 1; michael@0: #endif // GTEST_OS_WINDOWS michael@0: } else if (GTEST_FLAG(throw_on_failure)) { michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: throw GoogleTestFailureException(result); michael@0: #else michael@0: // We cannot call abort() as it generates a pop-up in debug mode michael@0: // that cannot be suppressed in VC 7.1 or below. michael@0: exit(1); michael@0: #endif michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Creates and adds a property to the current TestResult. If a property matching michael@0: // the supplied value already exists, updates its value instead. michael@0: void UnitTest::RecordPropertyForCurrentTest(const char* key, michael@0: const char* value) { michael@0: const TestProperty test_property(key, value); michael@0: impl_->current_test_result()->RecordProperty(test_property); michael@0: } michael@0: michael@0: // Runs all tests in this UnitTest object and prints the result. michael@0: // Returns 0 if successful, or 1 otherwise. michael@0: // michael@0: // We don't protect this under mutex_, as we only support calling it michael@0: // from the main thread. michael@0: int UnitTest::Run() { michael@0: // Captures the value of GTEST_FLAG(catch_exceptions). This value will be michael@0: // used for the duration of the program. michael@0: impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); michael@0: michael@0: #if GTEST_HAS_SEH michael@0: const bool in_death_test_child_process = michael@0: internal::GTEST_FLAG(internal_run_death_test).length() > 0; michael@0: michael@0: // Either the user wants Google Test to catch exceptions thrown by the michael@0: // tests or this is executing in the context of death test child michael@0: // process. In either case the user does not want to see pop-up dialogs michael@0: // about crashes - they are expected. michael@0: if (impl()->catch_exceptions() || in_death_test_child_process) { michael@0: # if !GTEST_OS_WINDOWS_MOBILE michael@0: // SetErrorMode doesn't exist on CE. michael@0: SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | michael@0: SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); michael@0: # endif // !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE michael@0: // Death test children can be terminated with _abort(). On Windows, michael@0: // _abort() can show a dialog with a warning message. This forces the michael@0: // abort message to go to stderr instead. michael@0: _set_error_mode(_OUT_TO_STDERR); michael@0: # endif michael@0: michael@0: # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE michael@0: // In the debug version, Visual Studio pops up a separate dialog michael@0: // offering a choice to debug the aborted program. We need to suppress michael@0: // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement michael@0: // executed. Google Test will notify the user of any unexpected michael@0: // failure via stderr. michael@0: // michael@0: // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. michael@0: // Users of prior VC versions shall suffer the agony and pain of michael@0: // clicking through the countless debug dialogs. michael@0: // TODO(vladl@google.com): find a way to suppress the abort dialog() in the michael@0: // debug mode when compiled with VC 7.1 or lower. michael@0: if (!GTEST_FLAG(break_on_failure)) michael@0: _set_abort_behavior( michael@0: 0x0, // Clear the following flags: michael@0: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. michael@0: # endif michael@0: } michael@0: #endif // GTEST_HAS_SEH michael@0: michael@0: return internal::HandleExceptionsInMethodIfSupported( michael@0: impl(), michael@0: &internal::UnitTestImpl::RunAllTests, michael@0: "auxiliary test code (environments or event listeners)") ? 0 : 1; michael@0: } michael@0: michael@0: // Returns the working directory when the first TEST() or TEST_F() was michael@0: // executed. michael@0: const char* UnitTest::original_working_dir() const { michael@0: return impl_->original_working_dir_.c_str(); michael@0: } michael@0: michael@0: // Returns the TestCase object for the test that's currently running, michael@0: // or NULL if no test is running. michael@0: const TestCase* UnitTest::current_test_case() const michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: internal::MutexLock lock(&mutex_); michael@0: return impl_->current_test_case(); michael@0: } michael@0: michael@0: // Returns the TestInfo object for the test that's currently running, michael@0: // or NULL if no test is running. michael@0: const TestInfo* UnitTest::current_test_info() const michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: internal::MutexLock lock(&mutex_); michael@0: return impl_->current_test_info(); michael@0: } michael@0: michael@0: // Returns the random seed used at the start of the current test run. michael@0: int UnitTest::random_seed() const { return impl_->random_seed(); } michael@0: michael@0: #if GTEST_HAS_PARAM_TEST michael@0: // Returns ParameterizedTestCaseRegistry object used to keep track of michael@0: // value-parameterized tests and instantiate and register them. michael@0: internal::ParameterizedTestCaseRegistry& michael@0: UnitTest::parameterized_test_registry() michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: return impl_->parameterized_test_registry(); michael@0: } michael@0: #endif // GTEST_HAS_PARAM_TEST michael@0: michael@0: // Creates an empty UnitTest. michael@0: UnitTest::UnitTest() { michael@0: impl_ = new internal::UnitTestImpl(this); michael@0: } michael@0: michael@0: // Destructor of UnitTest. michael@0: UnitTest::~UnitTest() { michael@0: delete impl_; michael@0: } michael@0: michael@0: // Pushes a trace defined by SCOPED_TRACE() on to the per-thread michael@0: // Google Test trace stack. michael@0: void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: internal::MutexLock lock(&mutex_); michael@0: impl_->gtest_trace_stack().push_back(trace); michael@0: } michael@0: michael@0: // Pops a trace from the per-thread Google Test trace stack. michael@0: void UnitTest::PopGTestTrace() michael@0: GTEST_LOCK_EXCLUDED_(mutex_) { michael@0: internal::MutexLock lock(&mutex_); michael@0: impl_->gtest_trace_stack().pop_back(); michael@0: } michael@0: michael@0: namespace internal { michael@0: michael@0: UnitTestImpl::UnitTestImpl(UnitTest* parent) michael@0: : parent_(parent), michael@0: #ifdef _MSC_VER michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4355) // Temporarily disables warning 4355 michael@0: // (using this in initializer). michael@0: default_global_test_part_result_reporter_(this), michael@0: default_per_thread_test_part_result_reporter_(this), michael@0: # pragma warning(pop) // Restores the warning state again. michael@0: #else michael@0: default_global_test_part_result_reporter_(this), michael@0: default_per_thread_test_part_result_reporter_(this), michael@0: #endif // _MSC_VER michael@0: global_test_part_result_repoter_( michael@0: &default_global_test_part_result_reporter_), michael@0: per_thread_test_part_result_reporter_( michael@0: &default_per_thread_test_part_result_reporter_), michael@0: #if GTEST_HAS_PARAM_TEST michael@0: parameterized_test_registry_(), michael@0: parameterized_tests_registered_(false), michael@0: #endif // GTEST_HAS_PARAM_TEST michael@0: last_death_test_case_(-1), michael@0: current_test_case_(NULL), michael@0: current_test_info_(NULL), michael@0: ad_hoc_test_result_(), michael@0: os_stack_trace_getter_(NULL), michael@0: post_flag_parse_init_performed_(false), michael@0: random_seed_(0), // Will be overridden by the flag before first use. michael@0: random_(0), // Will be reseeded before first use. michael@0: start_timestamp_(0), michael@0: elapsed_time_(0), michael@0: #if GTEST_HAS_DEATH_TEST michael@0: internal_run_death_test_flag_(NULL), michael@0: death_test_factory_(new DefaultDeathTestFactory), michael@0: #endif michael@0: // Will be overridden by the flag before first use. michael@0: catch_exceptions_(false) { michael@0: listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); michael@0: } michael@0: michael@0: UnitTestImpl::~UnitTestImpl() { michael@0: // Deletes every TestCase. michael@0: ForEach(test_cases_, internal::Delete); michael@0: michael@0: // Deletes every Environment. michael@0: ForEach(environments_, internal::Delete); michael@0: michael@0: delete os_stack_trace_getter_; michael@0: } michael@0: michael@0: #if GTEST_HAS_DEATH_TEST michael@0: // Disables event forwarding if the control is currently in a death test michael@0: // subprocess. Must not be called before InitGoogleTest. michael@0: void UnitTestImpl::SuppressTestEventsIfInSubprocess() { michael@0: if (internal_run_death_test_flag_.get() != NULL) michael@0: listeners()->SuppressEventForwarding(); michael@0: } michael@0: #endif // GTEST_HAS_DEATH_TEST michael@0: michael@0: // Initializes event listeners performing XML output as specified by michael@0: // UnitTestOptions. Must not be called before InitGoogleTest. michael@0: void UnitTestImpl::ConfigureXmlOutput() { michael@0: const String& output_format = UnitTestOptions::GetOutputFormat(); michael@0: if (output_format == "xml") { michael@0: listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( michael@0: UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); michael@0: } else if (output_format != "") { michael@0: printf("WARNING: unrecognized output format \"%s\" ignored.\n", michael@0: output_format.c_str()); michael@0: fflush(stdout); michael@0: } michael@0: } michael@0: michael@0: #if GTEST_CAN_STREAM_RESULTS_ michael@0: // Initializes event listeners for streaming test results in String form. michael@0: // Must not be called before InitGoogleTest. michael@0: void UnitTestImpl::ConfigureStreamingOutput() { michael@0: const string& target = GTEST_FLAG(stream_result_to); michael@0: if (!target.empty()) { michael@0: const size_t pos = target.find(':'); michael@0: if (pos != string::npos) { michael@0: listeners()->Append(new StreamingListener(target.substr(0, pos), michael@0: target.substr(pos+1))); michael@0: } else { michael@0: printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", michael@0: target.c_str()); michael@0: fflush(stdout); michael@0: } michael@0: } michael@0: } michael@0: #endif // GTEST_CAN_STREAM_RESULTS_ michael@0: michael@0: // Performs initialization dependent upon flag values obtained in michael@0: // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to michael@0: // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest michael@0: // this function is also called from RunAllTests. Since this function can be michael@0: // called more than once, it has to be idempotent. michael@0: void UnitTestImpl::PostFlagParsingInit() { michael@0: // Ensures that this function does not execute more than once. michael@0: if (!post_flag_parse_init_performed_) { michael@0: post_flag_parse_init_performed_ = true; michael@0: michael@0: #if GTEST_HAS_DEATH_TEST michael@0: InitDeathTestSubprocessControlInfo(); michael@0: SuppressTestEventsIfInSubprocess(); michael@0: #endif // GTEST_HAS_DEATH_TEST michael@0: michael@0: // Registers parameterized tests. This makes parameterized tests michael@0: // available to the UnitTest reflection API without running michael@0: // RUN_ALL_TESTS. michael@0: RegisterParameterizedTests(); michael@0: michael@0: // Configures listeners for XML output. This makes it possible for users michael@0: // to shut down the default XML output before invoking RUN_ALL_TESTS. michael@0: ConfigureXmlOutput(); michael@0: michael@0: #if GTEST_CAN_STREAM_RESULTS_ michael@0: // Configures listeners for streaming test results to the specified server. michael@0: ConfigureStreamingOutput(); michael@0: #endif // GTEST_CAN_STREAM_RESULTS_ michael@0: } michael@0: } michael@0: michael@0: // A predicate that checks the name of a TestCase against a known michael@0: // value. michael@0: // michael@0: // This is used for implementation of the UnitTest class only. We put michael@0: // it in the anonymous namespace to prevent polluting the outer michael@0: // namespace. michael@0: // michael@0: // TestCaseNameIs is copyable. michael@0: class TestCaseNameIs { michael@0: public: michael@0: // Constructor. michael@0: explicit TestCaseNameIs(const String& name) michael@0: : name_(name) {} michael@0: michael@0: // Returns true iff the name of test_case matches name_. michael@0: bool operator()(const TestCase* test_case) const { michael@0: return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; michael@0: } michael@0: michael@0: private: michael@0: String name_; michael@0: }; michael@0: michael@0: // Finds and returns a TestCase with the given name. If one doesn't michael@0: // exist, creates one and returns it. It's the CALLER'S michael@0: // RESPONSIBILITY to ensure that this function is only called WHEN THE michael@0: // TESTS ARE NOT SHUFFLED. michael@0: // michael@0: // Arguments: michael@0: // michael@0: // test_case_name: name of the test case michael@0: // type_param: the name of the test case's type parameter, or NULL if michael@0: // this is not a typed or a type-parameterized test case. michael@0: // set_up_tc: pointer to the function that sets up the test case michael@0: // tear_down_tc: pointer to the function that tears down the test case michael@0: TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, michael@0: const char* type_param, michael@0: Test::SetUpTestCaseFunc set_up_tc, michael@0: Test::TearDownTestCaseFunc tear_down_tc) { michael@0: // Can we find a TestCase with the given name? michael@0: const std::vector::const_iterator test_case = michael@0: std::find_if(test_cases_.begin(), test_cases_.end(), michael@0: TestCaseNameIs(test_case_name)); michael@0: michael@0: if (test_case != test_cases_.end()) michael@0: return *test_case; michael@0: michael@0: // No. Let's create one. michael@0: TestCase* const new_test_case = michael@0: new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); michael@0: michael@0: // Is this a death test case? michael@0: if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), michael@0: kDeathTestCaseFilter)) { michael@0: // Yes. Inserts the test case after the last death test case michael@0: // defined so far. This only works when the test cases haven't michael@0: // been shuffled. Otherwise we may end up running a death test michael@0: // after a non-death test. michael@0: ++last_death_test_case_; michael@0: test_cases_.insert(test_cases_.begin() + last_death_test_case_, michael@0: new_test_case); michael@0: } else { michael@0: // No. Appends to the end of the list. michael@0: test_cases_.push_back(new_test_case); michael@0: } michael@0: michael@0: test_case_indices_.push_back(static_cast(test_case_indices_.size())); michael@0: return new_test_case; michael@0: } michael@0: michael@0: // Helpers for setting up / tearing down the given environment. They michael@0: // are for use in the ForEach() function. michael@0: static void SetUpEnvironment(Environment* env) { env->SetUp(); } michael@0: static void TearDownEnvironment(Environment* env) { env->TearDown(); } michael@0: michael@0: // Runs all tests in this UnitTest object, prints the result, and michael@0: // returns true if all tests are successful. If any exception is michael@0: // thrown during a test, the test is considered to be failed, but the michael@0: // rest of the tests will still be run. michael@0: // michael@0: // When parameterized tests are enabled, it expands and registers michael@0: // parameterized tests first in RegisterParameterizedTests(). michael@0: // All other functions called from RunAllTests() may safely assume that michael@0: // parameterized tests are ready to be counted and run. michael@0: bool UnitTestImpl::RunAllTests() { michael@0: // Makes sure InitGoogleTest() was called. michael@0: if (!GTestIsInitialized()) { michael@0: printf("%s", michael@0: "\nThis test program did NOT call ::testing::InitGoogleTest " michael@0: "before calling RUN_ALL_TESTS(). Please fix it.\n"); michael@0: return false; michael@0: } michael@0: michael@0: // Do not run any test if the --help flag was specified. michael@0: if (g_help_flag) michael@0: return true; michael@0: michael@0: // Repeats the call to the post-flag parsing initialization in case the michael@0: // user didn't call InitGoogleTest. michael@0: PostFlagParsingInit(); michael@0: michael@0: // Even if sharding is not on, test runners may want to use the michael@0: // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding michael@0: // protocol. michael@0: internal::WriteToShardStatusFileIfNeeded(); michael@0: michael@0: // True iff we are in a subprocess for running a thread-safe-style michael@0: // death test. michael@0: bool in_subprocess_for_death_test = false; michael@0: michael@0: #if GTEST_HAS_DEATH_TEST michael@0: in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); michael@0: #endif // GTEST_HAS_DEATH_TEST michael@0: michael@0: const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, michael@0: in_subprocess_for_death_test); michael@0: michael@0: // Compares the full test names with the filter to decide which michael@0: // tests to run. michael@0: const bool has_tests_to_run = FilterTests(should_shard michael@0: ? HONOR_SHARDING_PROTOCOL michael@0: : IGNORE_SHARDING_PROTOCOL) > 0; michael@0: michael@0: // Lists the tests and exits if the --gtest_list_tests flag was specified. michael@0: if (GTEST_FLAG(list_tests)) { michael@0: // This must be called *after* FilterTests() has been called. michael@0: ListTestsMatchingFilter(); michael@0: return true; michael@0: } michael@0: michael@0: random_seed_ = GTEST_FLAG(shuffle) ? michael@0: GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; michael@0: michael@0: // True iff at least one test has failed. michael@0: bool failed = false; michael@0: michael@0: TestEventListener* repeater = listeners()->repeater(); michael@0: michael@0: start_timestamp_ = GetTimeInMillis(); michael@0: repeater->OnTestProgramStart(*parent_); michael@0: michael@0: // How many times to repeat the tests? We don't want to repeat them michael@0: // when we are inside the subprocess of a death test. michael@0: const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); michael@0: // Repeats forever if the repeat count is negative. michael@0: const bool forever = repeat < 0; michael@0: for (int i = 0; forever || i != repeat; i++) { michael@0: // We want to preserve failures generated by ad-hoc test michael@0: // assertions executed before RUN_ALL_TESTS(). michael@0: ClearNonAdHocTestResult(); michael@0: michael@0: const TimeInMillis start = GetTimeInMillis(); michael@0: michael@0: // Shuffles test cases and tests if requested. michael@0: if (has_tests_to_run && GTEST_FLAG(shuffle)) { michael@0: random()->Reseed(random_seed_); michael@0: // This should be done before calling OnTestIterationStart(), michael@0: // such that a test event listener can see the actual test order michael@0: // in the event. michael@0: ShuffleTests(); michael@0: } michael@0: michael@0: // Tells the unit test event listeners that the tests are about to start. michael@0: repeater->OnTestIterationStart(*parent_, i); michael@0: michael@0: // Runs each test case if there is at least one test to run. michael@0: if (has_tests_to_run) { michael@0: // Sets up all environments beforehand. michael@0: repeater->OnEnvironmentsSetUpStart(*parent_); michael@0: ForEach(environments_, SetUpEnvironment); michael@0: repeater->OnEnvironmentsSetUpEnd(*parent_); michael@0: michael@0: // Runs the tests only if there was no fatal failure during global michael@0: // set-up. michael@0: if (!Test::HasFatalFailure()) { michael@0: for (int test_index = 0; test_index < total_test_case_count(); michael@0: test_index++) { michael@0: GetMutableTestCase(test_index)->Run(); michael@0: } michael@0: } michael@0: michael@0: // Tears down all environments in reverse order afterwards. michael@0: repeater->OnEnvironmentsTearDownStart(*parent_); michael@0: std::for_each(environments_.rbegin(), environments_.rend(), michael@0: TearDownEnvironment); michael@0: repeater->OnEnvironmentsTearDownEnd(*parent_); michael@0: } michael@0: michael@0: elapsed_time_ = GetTimeInMillis() - start; michael@0: michael@0: // Tells the unit test event listener that the tests have just finished. michael@0: repeater->OnTestIterationEnd(*parent_, i); michael@0: michael@0: // Gets the result and clears it. michael@0: if (!Passed()) { michael@0: failed = true; michael@0: } michael@0: michael@0: // Restores the original test order after the iteration. This michael@0: // allows the user to quickly repro a failure that happens in the michael@0: // N-th iteration without repeating the first (N - 1) iterations. michael@0: // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in michael@0: // case the user somehow changes the value of the flag somewhere michael@0: // (it's always safe to unshuffle the tests). michael@0: UnshuffleTests(); michael@0: michael@0: if (GTEST_FLAG(shuffle)) { michael@0: // Picks a new random seed for each iteration. michael@0: random_seed_ = GetNextRandomSeed(random_seed_); michael@0: } michael@0: } michael@0: michael@0: repeater->OnTestProgramEnd(*parent_); michael@0: michael@0: return !failed; michael@0: } michael@0: michael@0: // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file michael@0: // if the variable is present. If a file already exists at this location, this michael@0: // function will write over it. If the variable is present, but the file cannot michael@0: // be created, prints an error and exits. michael@0: void WriteToShardStatusFileIfNeeded() { michael@0: const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); michael@0: if (test_shard_file != NULL) { michael@0: FILE* const file = posix::FOpen(test_shard_file, "w"); michael@0: if (file == NULL) { michael@0: ColoredPrintf(COLOR_RED, michael@0: "Could not write to the test shard status file \"%s\" " michael@0: "specified by the %s environment variable.\n", michael@0: test_shard_file, kTestShardStatusFile); michael@0: fflush(stdout); michael@0: exit(EXIT_FAILURE); michael@0: } michael@0: fclose(file); michael@0: } michael@0: } michael@0: michael@0: // Checks whether sharding is enabled by examining the relevant michael@0: // environment variable values. If the variables are present, michael@0: // but inconsistent (i.e., shard_index >= total_shards), prints michael@0: // an error and exits. If in_subprocess_for_death_test, sharding is michael@0: // disabled because it must only be applied to the original test michael@0: // process. Otherwise, we could filter out death tests we intended to execute. michael@0: bool ShouldShard(const char* total_shards_env, michael@0: const char* shard_index_env, michael@0: bool in_subprocess_for_death_test) { michael@0: if (in_subprocess_for_death_test) { michael@0: return false; michael@0: } michael@0: michael@0: const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); michael@0: const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); michael@0: michael@0: if (total_shards == -1 && shard_index == -1) { michael@0: return false; michael@0: } else if (total_shards == -1 && shard_index != -1) { michael@0: const Message msg = Message() michael@0: << "Invalid environment variables: you have " michael@0: << kTestShardIndex << " = " << shard_index michael@0: << ", but have left " << kTestTotalShards << " unset.\n"; michael@0: ColoredPrintf(COLOR_RED, msg.GetString().c_str()); michael@0: fflush(stdout); michael@0: exit(EXIT_FAILURE); michael@0: } else if (total_shards != -1 && shard_index == -1) { michael@0: const Message msg = Message() michael@0: << "Invalid environment variables: you have " michael@0: << kTestTotalShards << " = " << total_shards michael@0: << ", but have left " << kTestShardIndex << " unset.\n"; michael@0: ColoredPrintf(COLOR_RED, msg.GetString().c_str()); michael@0: fflush(stdout); michael@0: exit(EXIT_FAILURE); michael@0: } else if (shard_index < 0 || shard_index >= total_shards) { michael@0: const Message msg = Message() michael@0: << "Invalid environment variables: we require 0 <= " michael@0: << kTestShardIndex << " < " << kTestTotalShards michael@0: << ", but you have " << kTestShardIndex << "=" << shard_index michael@0: << ", " << kTestTotalShards << "=" << total_shards << ".\n"; michael@0: ColoredPrintf(COLOR_RED, msg.GetString().c_str()); michael@0: fflush(stdout); michael@0: exit(EXIT_FAILURE); michael@0: } michael@0: michael@0: return total_shards > 1; michael@0: } michael@0: michael@0: // Parses the environment variable var as an Int32. If it is unset, michael@0: // returns default_val. If it is not an Int32, prints an error michael@0: // and aborts. michael@0: Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { michael@0: const char* str_val = posix::GetEnv(var); michael@0: if (str_val == NULL) { michael@0: return default_val; michael@0: } michael@0: michael@0: Int32 result; michael@0: if (!ParseInt32(Message() << "The value of environment variable " << var, michael@0: str_val, &result)) { michael@0: exit(EXIT_FAILURE); michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: // Given the total number of shards, the shard index, and the test id, michael@0: // returns true iff the test should be run on this shard. The test id is michael@0: // some arbitrary but unique non-negative integer assigned to each test michael@0: // method. Assumes that 0 <= shard_index < total_shards. michael@0: bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { michael@0: return (test_id % total_shards) == shard_index; michael@0: } michael@0: michael@0: // Compares the name of each test with the user-specified filter to michael@0: // decide whether the test should be run, then records the result in michael@0: // each TestCase and TestInfo object. michael@0: // If shard_tests == true, further filters tests based on sharding michael@0: // variables in the environment - see michael@0: // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. michael@0: // Returns the number of tests that should run. michael@0: int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { michael@0: const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? michael@0: Int32FromEnvOrDie(kTestTotalShards, -1) : -1; michael@0: const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? michael@0: Int32FromEnvOrDie(kTestShardIndex, -1) : -1; michael@0: michael@0: // num_runnable_tests are the number of tests that will michael@0: // run across all shards (i.e., match filter and are not disabled). michael@0: // num_selected_tests are the number of tests to be run on michael@0: // this shard. michael@0: int num_runnable_tests = 0; michael@0: int num_selected_tests = 0; michael@0: for (size_t i = 0; i < test_cases_.size(); i++) { michael@0: TestCase* const test_case = test_cases_[i]; michael@0: const String &test_case_name = test_case->name(); michael@0: test_case->set_should_run(false); michael@0: michael@0: for (size_t j = 0; j < test_case->test_info_list().size(); j++) { michael@0: TestInfo* const test_info = test_case->test_info_list()[j]; michael@0: const String test_name(test_info->name()); michael@0: // A test is disabled if test case name or test name matches michael@0: // kDisableTestFilter. michael@0: const bool is_disabled = michael@0: internal::UnitTestOptions::MatchesFilter(test_case_name, michael@0: kDisableTestFilter) || michael@0: internal::UnitTestOptions::MatchesFilter(test_name, michael@0: kDisableTestFilter); michael@0: test_info->is_disabled_ = is_disabled; michael@0: michael@0: const bool matches_filter = michael@0: internal::UnitTestOptions::FilterMatchesTest(test_case_name, michael@0: test_name); michael@0: test_info->matches_filter_ = matches_filter; michael@0: michael@0: const bool is_runnable = michael@0: (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && michael@0: matches_filter; michael@0: michael@0: const bool is_selected = is_runnable && michael@0: (shard_tests == IGNORE_SHARDING_PROTOCOL || michael@0: ShouldRunTestOnShard(total_shards, shard_index, michael@0: num_runnable_tests)); michael@0: michael@0: num_runnable_tests += is_runnable; michael@0: num_selected_tests += is_selected; michael@0: michael@0: test_info->should_run_ = is_selected; michael@0: test_case->set_should_run(test_case->should_run() || is_selected); michael@0: } michael@0: } michael@0: return num_selected_tests; michael@0: } michael@0: michael@0: // Prints the names of the tests matching the user-specified filter flag. michael@0: void UnitTestImpl::ListTestsMatchingFilter() { michael@0: for (size_t i = 0; i < test_cases_.size(); i++) { michael@0: const TestCase* const test_case = test_cases_[i]; michael@0: bool printed_test_case_name = false; michael@0: michael@0: for (size_t j = 0; j < test_case->test_info_list().size(); j++) { michael@0: const TestInfo* const test_info = michael@0: test_case->test_info_list()[j]; michael@0: if (test_info->matches_filter_) { michael@0: if (!printed_test_case_name) { michael@0: printed_test_case_name = true; michael@0: printf("%s.\n", test_case->name()); michael@0: } michael@0: printf(" %s\n", test_info->name()); michael@0: } michael@0: } michael@0: } michael@0: fflush(stdout); michael@0: } michael@0: michael@0: // Sets the OS stack trace getter. michael@0: // michael@0: // Does nothing if the input and the current OS stack trace getter are michael@0: // the same; otherwise, deletes the old getter and makes the input the michael@0: // current getter. michael@0: void UnitTestImpl::set_os_stack_trace_getter( michael@0: OsStackTraceGetterInterface* getter) { michael@0: if (os_stack_trace_getter_ != getter) { michael@0: delete os_stack_trace_getter_; michael@0: os_stack_trace_getter_ = getter; michael@0: } michael@0: } michael@0: michael@0: // Returns the current OS stack trace getter if it is not NULL; michael@0: // otherwise, creates an OsStackTraceGetter, makes it the current michael@0: // getter, and returns it. michael@0: OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { michael@0: if (os_stack_trace_getter_ == NULL) { michael@0: os_stack_trace_getter_ = new OsStackTraceGetter; michael@0: } michael@0: michael@0: return os_stack_trace_getter_; michael@0: } michael@0: michael@0: // Returns the TestResult for the test that's currently running, or michael@0: // the TestResult for the ad hoc test if no test is running. michael@0: TestResult* UnitTestImpl::current_test_result() { michael@0: return current_test_info_ ? michael@0: &(current_test_info_->result_) : &ad_hoc_test_result_; michael@0: } michael@0: michael@0: // Shuffles all test cases, and the tests within each test case, michael@0: // making sure that death tests are still run first. michael@0: void UnitTestImpl::ShuffleTests() { michael@0: // Shuffles the death test cases. michael@0: ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); michael@0: michael@0: // Shuffles the non-death test cases. michael@0: ShuffleRange(random(), last_death_test_case_ + 1, michael@0: static_cast(test_cases_.size()), &test_case_indices_); michael@0: michael@0: // Shuffles the tests inside each test case. michael@0: for (size_t i = 0; i < test_cases_.size(); i++) { michael@0: test_cases_[i]->ShuffleTests(random()); michael@0: } michael@0: } michael@0: michael@0: // Restores the test cases and tests to their order before the first shuffle. michael@0: void UnitTestImpl::UnshuffleTests() { michael@0: for (size_t i = 0; i < test_cases_.size(); i++) { michael@0: // Unshuffles the tests in each test case. michael@0: test_cases_[i]->UnshuffleTests(); michael@0: // Resets the index of each test case. michael@0: test_case_indices_[i] = static_cast(i); michael@0: } michael@0: } michael@0: michael@0: // Returns the current OS stack trace as a String. michael@0: // michael@0: // The maximum number of stack frames to be included is specified by michael@0: // the gtest_stack_trace_depth flag. The skip_count parameter michael@0: // specifies the number of top frames to be skipped, which doesn't michael@0: // count against the number of frames to be included. michael@0: // michael@0: // For example, if Foo() calls Bar(), which in turn calls michael@0: // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in michael@0: // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. michael@0: String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, michael@0: int skip_count) { michael@0: // We pass skip_count + 1 to skip this wrapper function in addition michael@0: // to what the user really wants to skip. michael@0: return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); michael@0: } michael@0: michael@0: // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to michael@0: // suppress unreachable code warnings. michael@0: namespace { michael@0: class ClassUniqueToAlwaysTrue {}; michael@0: } michael@0: michael@0: bool IsTrue(bool condition) { return condition; } michael@0: michael@0: bool AlwaysTrue() { michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: // This condition is always false so AlwaysTrue() never actually throws, michael@0: // but it makes the compiler think that it may throw. michael@0: if (IsTrue(false)) michael@0: throw ClassUniqueToAlwaysTrue(); michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: return true; michael@0: } michael@0: michael@0: // If *pstr starts with the given prefix, modifies *pstr to be right michael@0: // past the prefix and returns true; otherwise leaves *pstr unchanged michael@0: // and returns false. None of pstr, *pstr, and prefix can be NULL. michael@0: bool SkipPrefix(const char* prefix, const char** pstr) { michael@0: const size_t prefix_len = strlen(prefix); michael@0: if (strncmp(*pstr, prefix, prefix_len) == 0) { michael@0: *pstr += prefix_len; michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // Parses a string as a command line flag. The string should have michael@0: // the format "--flag=value". When def_optional is true, the "=value" michael@0: // part can be omitted. michael@0: // michael@0: // Returns the value of the flag, or NULL if the parsing failed. michael@0: const char* ParseFlagValue(const char* str, michael@0: const char* flag, michael@0: bool def_optional) { michael@0: // str and flag must not be NULL. michael@0: if (str == NULL || flag == NULL) return NULL; michael@0: michael@0: // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. michael@0: const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); michael@0: const size_t flag_len = flag_str.length(); michael@0: if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; michael@0: michael@0: // Skips the flag name. michael@0: const char* flag_end = str + flag_len; michael@0: michael@0: // When def_optional is true, it's OK to not have a "=value" part. michael@0: if (def_optional && (flag_end[0] == '\0')) { michael@0: return flag_end; michael@0: } michael@0: michael@0: // If def_optional is true and there are more characters after the michael@0: // flag name, or if def_optional is false, there must be a '=' after michael@0: // the flag name. michael@0: if (flag_end[0] != '=') return NULL; michael@0: michael@0: // Returns the string after "=". michael@0: return flag_end + 1; michael@0: } michael@0: michael@0: // Parses a string for a bool flag, in the form of either michael@0: // "--flag=value" or "--flag". michael@0: // michael@0: // In the former case, the value is taken as true as long as it does michael@0: // not start with '0', 'f', or 'F'. michael@0: // michael@0: // In the latter case, the value is taken as true. michael@0: // michael@0: // On success, stores the value of the flag in *value, and returns michael@0: // true. On failure, returns false without changing *value. michael@0: bool ParseBoolFlag(const char* str, const char* flag, bool* value) { michael@0: // Gets the value of the flag as a string. michael@0: const char* const value_str = ParseFlagValue(str, flag, true); michael@0: michael@0: // Aborts if the parsing failed. michael@0: if (value_str == NULL) return false; michael@0: michael@0: // Converts the string value to a bool. michael@0: *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); michael@0: return true; michael@0: } michael@0: michael@0: // Parses a string for an Int32 flag, in the form of michael@0: // "--flag=value". michael@0: // michael@0: // On success, stores the value of the flag in *value, and returns michael@0: // true. On failure, returns false without changing *value. michael@0: bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { michael@0: // Gets the value of the flag as a string. michael@0: const char* const value_str = ParseFlagValue(str, flag, false); michael@0: michael@0: // Aborts if the parsing failed. michael@0: if (value_str == NULL) return false; michael@0: michael@0: // Sets *value to the value of the flag. michael@0: return ParseInt32(Message() << "The value of flag --" << flag, michael@0: value_str, value); michael@0: } michael@0: michael@0: // Parses a string for a string flag, in the form of michael@0: // "--flag=value". michael@0: // michael@0: // On success, stores the value of the flag in *value, and returns michael@0: // true. On failure, returns false without changing *value. michael@0: bool ParseStringFlag(const char* str, const char* flag, String* value) { michael@0: // Gets the value of the flag as a string. michael@0: const char* const value_str = ParseFlagValue(str, flag, false); michael@0: michael@0: // Aborts if the parsing failed. michael@0: if (value_str == NULL) return false; michael@0: michael@0: // Sets *value to the value of the flag. michael@0: *value = value_str; michael@0: return true; michael@0: } michael@0: michael@0: // Determines whether a string has a prefix that Google Test uses for its michael@0: // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. michael@0: // If Google Test detects that a command line flag has its prefix but is not michael@0: // recognized, it will print its help message. Flags starting with michael@0: // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test michael@0: // internal flags and do not trigger the help message. michael@0: static bool HasGoogleTestFlagPrefix(const char* str) { michael@0: return (SkipPrefix("--", &str) || michael@0: SkipPrefix("-", &str) || michael@0: SkipPrefix("/", &str)) && michael@0: !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && michael@0: (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || michael@0: SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); michael@0: } michael@0: michael@0: // Prints a string containing code-encoded text. The following escape michael@0: // sequences can be used in the string to control the text color: michael@0: // michael@0: // @@ prints a single '@' character. michael@0: // @R changes the color to red. michael@0: // @G changes the color to green. michael@0: // @Y changes the color to yellow. michael@0: // @D changes to the default terminal text color. michael@0: // michael@0: // TODO(wan@google.com): Write tests for this once we add stdout michael@0: // capturing to Google Test. michael@0: static void PrintColorEncoded(const char* str) { michael@0: GTestColor color = COLOR_DEFAULT; // The current color. michael@0: michael@0: // Conceptually, we split the string into segments divided by escape michael@0: // sequences. Then we print one segment at a time. At the end of michael@0: // each iteration, the str pointer advances to the beginning of the michael@0: // next segment. michael@0: for (;;) { michael@0: const char* p = strchr(str, '@'); michael@0: if (p == NULL) { michael@0: ColoredPrintf(color, "%s", str); michael@0: return; michael@0: } michael@0: michael@0: ColoredPrintf(color, "%s", String(str, p - str).c_str()); michael@0: michael@0: const char ch = p[1]; michael@0: str = p + 2; michael@0: if (ch == '@') { michael@0: ColoredPrintf(color, "@"); michael@0: } else if (ch == 'D') { michael@0: color = COLOR_DEFAULT; michael@0: } else if (ch == 'R') { michael@0: color = COLOR_RED; michael@0: } else if (ch == 'G') { michael@0: color = COLOR_GREEN; michael@0: } else if (ch == 'Y') { michael@0: color = COLOR_YELLOW; michael@0: } else { michael@0: --str; michael@0: } michael@0: } michael@0: } michael@0: michael@0: static const char kColorEncodedHelpMessage[] = michael@0: "This program contains tests written using " GTEST_NAME_ ". You can use the\n" michael@0: "following command line flags to control its behavior:\n" michael@0: "\n" michael@0: "Test Selection:\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" michael@0: " List the names of all tests instead of running them. The name of\n" michael@0: " TEST(Foo, Bar) is \"Foo.Bar\".\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" michael@0: "[@G-@YNEGATIVE_PATTERNS]@D\n" michael@0: " Run only the tests whose name matches one of the positive patterns but\n" michael@0: " none of the negative patterns. '?' matches any single character; '*'\n" michael@0: " matches any substring; ':' separates two patterns.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" michael@0: " Run all disabled tests too.\n" michael@0: "\n" michael@0: "Test Execution:\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" michael@0: " Run the tests repeatedly; use a negative count to repeat forever.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" michael@0: " Randomize tests' orders on every iteration.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" michael@0: " Random number seed to use for shuffling test orders (between 1 and\n" michael@0: " 99999, or 0 to use a seed based on the current time).\n" michael@0: "\n" michael@0: "Test Output:\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" michael@0: " Enable/disable colored output. The default is @Gauto@D.\n" michael@0: " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" michael@0: " Don't print the elapsed time of each test.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" michael@0: GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" michael@0: " Generate an XML report in the given directory or with the given file\n" michael@0: " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" michael@0: #if GTEST_CAN_STREAM_RESULTS_ michael@0: " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" michael@0: " Stream test results to the given server.\n" michael@0: #endif // GTEST_CAN_STREAM_RESULTS_ michael@0: "\n" michael@0: "Assertion Behavior:\n" michael@0: #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS michael@0: " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" michael@0: " Set the default death test style.\n" michael@0: #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS michael@0: " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" michael@0: " Turn assertion failures into debugger break-points.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" michael@0: " Turn assertion failures into C++ exceptions.\n" michael@0: " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" michael@0: " Do not report exceptions as test failures. Instead, allow them\n" michael@0: " to crash the program or throw a pop-up (on Windows).\n" michael@0: "\n" michael@0: "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " michael@0: "the corresponding\n" michael@0: "environment variable of a flag (all letters in upper-case). For example, to\n" michael@0: "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ michael@0: "color=no@D or set\n" michael@0: "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" michael@0: "\n" michael@0: "For more information, please read the " GTEST_NAME_ " documentation at\n" michael@0: "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" michael@0: "(not one in your own code or tests), please report it to\n" michael@0: "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; michael@0: michael@0: // Parses the command line for Google Test flags, without initializing michael@0: // other parts of Google Test. The type parameter CharType can be michael@0: // instantiated to either char or wchar_t. michael@0: template michael@0: void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { michael@0: for (int i = 1; i < *argc; i++) { michael@0: const String arg_string = StreamableToString(argv[i]); michael@0: const char* const arg = arg_string.c_str(); michael@0: michael@0: using internal::ParseBoolFlag; michael@0: using internal::ParseInt32Flag; michael@0: using internal::ParseStringFlag; michael@0: michael@0: // Do we see a Google Test flag? michael@0: if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, michael@0: >EST_FLAG(also_run_disabled_tests)) || michael@0: ParseBoolFlag(arg, kBreakOnFailureFlag, michael@0: >EST_FLAG(break_on_failure)) || michael@0: ParseBoolFlag(arg, kCatchExceptionsFlag, michael@0: >EST_FLAG(catch_exceptions)) || michael@0: ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || michael@0: ParseStringFlag(arg, kDeathTestStyleFlag, michael@0: >EST_FLAG(death_test_style)) || michael@0: ParseBoolFlag(arg, kDeathTestUseFork, michael@0: >EST_FLAG(death_test_use_fork)) || michael@0: ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || michael@0: ParseStringFlag(arg, kInternalRunDeathTestFlag, michael@0: >EST_FLAG(internal_run_death_test)) || michael@0: ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || michael@0: ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || michael@0: ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || michael@0: ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || michael@0: ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || michael@0: ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || michael@0: ParseInt32Flag(arg, kStackTraceDepthFlag, michael@0: >EST_FLAG(stack_trace_depth)) || michael@0: ParseStringFlag(arg, kStreamResultToFlag, michael@0: >EST_FLAG(stream_result_to)) || michael@0: ParseBoolFlag(arg, kThrowOnFailureFlag, michael@0: >EST_FLAG(throw_on_failure)) michael@0: ) { michael@0: // Yes. Shift the remainder of the argv list left by one. Note michael@0: // that argv has (*argc + 1) elements, the last one always being michael@0: // NULL. The following loop moves the trailing NULL element as michael@0: // well. michael@0: for (int j = i; j != *argc; j++) { michael@0: argv[j] = argv[j + 1]; michael@0: } michael@0: michael@0: // Decrements the argument count. michael@0: (*argc)--; michael@0: michael@0: // We also need to decrement the iterator as we just removed michael@0: // an element. michael@0: i--; michael@0: } else if (arg_string == "--help" || arg_string == "-h" || michael@0: arg_string == "-?" || arg_string == "/?" || michael@0: HasGoogleTestFlagPrefix(arg)) { michael@0: // Both help flag and unrecognized Google Test flags (excluding michael@0: // internal ones) trigger help display. michael@0: g_help_flag = true; michael@0: } michael@0: } michael@0: michael@0: if (g_help_flag) { michael@0: // We print the help here instead of in RUN_ALL_TESTS(), as the michael@0: // latter may not be called at all if the user is using Google michael@0: // Test with another testing framework. michael@0: PrintColorEncoded(kColorEncodedHelpMessage); michael@0: } michael@0: } michael@0: michael@0: // Parses the command line for Google Test flags, without initializing michael@0: // other parts of Google Test. michael@0: void ParseGoogleTestFlagsOnly(int* argc, char** argv) { michael@0: ParseGoogleTestFlagsOnlyImpl(argc, argv); michael@0: } michael@0: void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { michael@0: ParseGoogleTestFlagsOnlyImpl(argc, argv); michael@0: } michael@0: michael@0: // The internal implementation of InitGoogleTest(). michael@0: // michael@0: // The type parameter CharType can be instantiated to either char or michael@0: // wchar_t. michael@0: template michael@0: void InitGoogleTestImpl(int* argc, CharType** argv) { michael@0: g_init_gtest_count++; michael@0: michael@0: // We don't want to run the initialization code twice. michael@0: if (g_init_gtest_count != 1) return; michael@0: michael@0: if (*argc <= 0) return; michael@0: michael@0: internal::g_executable_path = internal::StreamableToString(argv[0]); michael@0: michael@0: #if GTEST_HAS_DEATH_TEST michael@0: michael@0: g_argvs.clear(); michael@0: for (int i = 0; i != *argc; i++) { michael@0: g_argvs.push_back(StreamableToString(argv[i])); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_DEATH_TEST michael@0: michael@0: ParseGoogleTestFlagsOnly(argc, argv); michael@0: GetUnitTestImpl()->PostFlagParsingInit(); michael@0: } michael@0: michael@0: } // namespace internal michael@0: michael@0: // Initializes Google Test. This must be called before calling michael@0: // RUN_ALL_TESTS(). In particular, it parses a command line for the michael@0: // flags that Google Test recognizes. Whenever a Google Test flag is michael@0: // seen, it is removed from argv, and *argc is decremented. michael@0: // michael@0: // No value is returned. Instead, the Google Test flag variables are michael@0: // updated. michael@0: // michael@0: // Calling the function for the second time has no user-visible effect. michael@0: void InitGoogleTest(int* argc, char** argv) { michael@0: internal::InitGoogleTestImpl(argc, argv); michael@0: } michael@0: michael@0: // This overloaded version can be used in Windows programs compiled in michael@0: // UNICODE mode. michael@0: void InitGoogleTest(int* argc, wchar_t** argv) { michael@0: internal::InitGoogleTestImpl(argc, argv); michael@0: } michael@0: michael@0: } // namespace testing