Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1 | // Copyright 2005, Google Inc. |
| 2 | // All rights reserved. |
| 3 | // |
| 4 | // Redistribution and use in source and binary forms, with or without |
| 5 | // modification, are permitted provided that the following conditions are |
| 6 | // met: |
| 7 | // |
| 8 | // * Redistributions of source code must retain the above copyright |
| 9 | // notice, this list of conditions and the following disclaimer. |
| 10 | // * Redistributions in binary form must reproduce the above |
| 11 | // copyright notice, this list of conditions and the following disclaimer |
| 12 | // in the documentation and/or other materials provided with the |
| 13 | // distribution. |
| 14 | // * Neither the name of Google Inc. nor the names of its |
| 15 | // contributors may be used to endorse or promote products derived from |
| 16 | // this software without specific prior written permission. |
| 17 | // |
| 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | // |
| 30 | // Author: wan@google.com (Zhanyong Wan) |
| 31 | // |
| 32 | // The Google C++ Testing Framework (Google Test) |
| 33 | |
| 34 | #include <gtest/gtest.h> |
| 35 | #include <gtest/gtest-spi.h> |
| 36 | |
| 37 | #include <ctype.h> |
| 38 | #include <math.h> |
| 39 | #include <stdarg.h> |
| 40 | #include <stdio.h> |
| 41 | #include <stdlib.h> |
| 42 | #include <string.h> |
| 43 | #include <wchar.h> |
| 44 | #include <wctype.h> |
| 45 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 46 | #if GTEST_OS_LINUX |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 47 | |
| 48 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 49 | // gettimeofday(). |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 50 | #define GTEST_HAS_GETTIMEOFDAY_ 1 |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 51 | |
| 52 | #include <fcntl.h> |
| 53 | #include <limits.h> |
| 54 | #include <sched.h> |
| 55 | // Declares vsnprintf(). This header is not available on Windows. |
| 56 | #include <strings.h> |
| 57 | #include <sys/mman.h> |
| 58 | #include <sys/time.h> |
| 59 | #include <unistd.h> |
| 60 | #include <string> |
| 61 | #include <vector> |
| 62 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 63 | #elif GTEST_OS_SYMBIAN |
| 64 | #define GTEST_HAS_GETTIMEOFDAY_ 1 |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 65 | #include <sys/time.h> // NOLINT |
| 66 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 67 | #elif GTEST_OS_ZOS |
| 68 | #define GTEST_HAS_GETTIMEOFDAY_ 1 |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 69 | #include <sys/time.h> // NOLINT |
| 70 | |
| 71 | // On z/OS we additionally need strings.h for strcasecmp. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 72 | #include <strings.h> // NOLINT |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 73 | |
| 74 | #elif defined(_WIN32_WCE) // We are on Windows CE. |
| 75 | |
| 76 | #include <windows.h> // NOLINT |
| 77 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 78 | #elif GTEST_OS_WINDOWS // We are on Windows proper. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 79 | |
| 80 | #include <io.h> // NOLINT |
| 81 | #include <sys/timeb.h> // NOLINT |
| 82 | #include <sys/types.h> // NOLINT |
| 83 | #include <sys/stat.h> // NOLINT |
| 84 | |
| 85 | #if defined(__MINGW__) || defined(__MINGW32__) |
| 86 | // MinGW has gettimeofday() but not _ftime64(). |
| 87 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 88 | // gettimeofday(). |
| 89 | // TODO(kenton@google.com): There are other ways to get the time on |
| 90 | // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW |
| 91 | // supports these. consider using them instead. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 92 | #define GTEST_HAS_GETTIMEOFDAY_ 1 |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 93 | #include <sys/time.h> // NOLINT |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 94 | #endif // defined(__MINGW__) || defined(__MINGW32__) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 95 | |
| 96 | // cpplint thinks that the header is already included, so we want to |
| 97 | // silence it. |
| 98 | #include <windows.h> // NOLINT |
| 99 | |
| 100 | #else |
| 101 | |
| 102 | // Assume other platforms have gettimeofday(). |
| 103 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 104 | // gettimeofday(). |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 105 | #define GTEST_HAS_GETTIMEOFDAY_ 1 |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 106 | |
| 107 | // cpplint thinks that the header is already included, so we want to |
| 108 | // silence it. |
| 109 | #include <sys/time.h> // NOLINT |
| 110 | #include <unistd.h> // NOLINT |
| 111 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 112 | #endif // GTEST_OS_LINUX |
| 113 | |
| 114 | #if GTEST_HAS_EXCEPTIONS |
| 115 | #include <stdexcept> |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 116 | #endif |
| 117 | |
| 118 | // Indicates that this translation unit is part of Google Test's |
| 119 | // implementation. It must come before gtest-internal-inl.h is |
| 120 | // included, or there will be a compiler error. This trick is to |
| 121 | // prevent a user from accidentally including gtest-internal-inl.h in |
| 122 | // his code. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 123 | #define GTEST_IMPLEMENTATION_ 1 |
Misha Brukman | e5f9471 | 2009-01-01 02:05:43 +0000 | [diff] [blame] | 124 | #include "gtest/internal/gtest-internal-inl.h" |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 125 | #undef GTEST_IMPLEMENTATION_ |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 126 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 127 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 128 | #define fileno _fileno |
| 129 | #define isatty _isatty |
| 130 | #define vsnprintf _vsnprintf |
| 131 | #endif // GTEST_OS_WINDOWS |
| 132 | |
| 133 | namespace testing { |
| 134 | |
| 135 | // Constants. |
| 136 | |
| 137 | // A test whose test case name or test name matches this filter is |
| 138 | // disabled and not run. |
| 139 | static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; |
| 140 | |
| 141 | // A test case whose name matches this filter is considered a death |
| 142 | // test case and will be run before test cases whose name doesn't |
| 143 | // match this filter. |
| 144 | static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; |
| 145 | |
| 146 | // A test filter that matches everything. |
| 147 | static const char kUniversalFilter[] = "*"; |
| 148 | |
| 149 | // The default output file for XML output. |
| 150 | static const char kDefaultOutputFile[] = "test_detail.xml"; |
| 151 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 152 | // The environment variable name for the test shard index. |
| 153 | static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; |
| 154 | // The environment variable name for the total number of test shards. |
| 155 | static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; |
| 156 | // The environment variable name for the test shard status file. |
| 157 | static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; |
| 158 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 159 | namespace internal { |
| 160 | |
| 161 | // The text used in failure messages to indicate the start of the |
| 162 | // stack trace. |
| 163 | const char kStackTraceMarker[] = "\nStack trace:\n"; |
| 164 | |
| 165 | } // namespace internal |
| 166 | |
| 167 | GTEST_DEFINE_bool_( |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 168 | also_run_disabled_tests, |
| 169 | internal::BoolFromGTestEnv("also_run_disabled_tests", false), |
| 170 | "Run disabled tests too, in addition to the tests normally being run."); |
| 171 | |
| 172 | GTEST_DEFINE_bool_( |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 173 | break_on_failure, |
| 174 | internal::BoolFromGTestEnv("break_on_failure", false), |
| 175 | "True iff a failed assertion should be a debugger break-point."); |
| 176 | |
| 177 | GTEST_DEFINE_bool_( |
| 178 | catch_exceptions, |
| 179 | internal::BoolFromGTestEnv("catch_exceptions", false), |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 180 | "True iff " GTEST_NAME_ |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 181 | " should catch exceptions and treat them as test failures."); |
| 182 | |
| 183 | GTEST_DEFINE_string_( |
| 184 | color, |
| 185 | internal::StringFromGTestEnv("color", "auto"), |
| 186 | "Whether to use colors in the output. Valid values: yes, no, " |
| 187 | "and auto. 'auto' means to use colors if the output is " |
| 188 | "being sent to a terminal and the TERM environment variable " |
| 189 | "is set to xterm or xterm-color."); |
| 190 | |
| 191 | GTEST_DEFINE_string_( |
| 192 | filter, |
| 193 | internal::StringFromGTestEnv("filter", kUniversalFilter), |
| 194 | "A colon-separated list of glob (not regex) patterns " |
| 195 | "for filtering the tests to run, optionally followed by a " |
| 196 | "'-' and a : separated list of negative patterns (tests to " |
| 197 | "exclude). A test is run if it matches one of the positive " |
| 198 | "patterns and does not match any of the negative patterns."); |
| 199 | |
| 200 | GTEST_DEFINE_bool_(list_tests, false, |
| 201 | "List all tests without running them."); |
| 202 | |
| 203 | GTEST_DEFINE_string_( |
| 204 | output, |
| 205 | internal::StringFromGTestEnv("output", ""), |
| 206 | "A format (currently must be \"xml\"), optionally followed " |
| 207 | "by a colon and an output file name or directory. A directory " |
| 208 | "is indicated by a trailing pathname separator. " |
| 209 | "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " |
| 210 | "If a directory is specified, output files will be created " |
| 211 | "within that directory, with file-names based on the test " |
| 212 | "executable's name and, if necessary, made unique by adding " |
| 213 | "digits."); |
| 214 | |
| 215 | GTEST_DEFINE_bool_( |
| 216 | print_time, |
| 217 | internal::BoolFromGTestEnv("print_time", false), |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 218 | "True iff " GTEST_NAME_ |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 219 | " should display elapsed time in text output."); |
| 220 | |
| 221 | GTEST_DEFINE_int32_( |
| 222 | repeat, |
| 223 | internal::Int32FromGTestEnv("repeat", 1), |
| 224 | "How many times to repeat each test. Specify a negative number " |
| 225 | "for repeating forever. Useful for shaking out flaky tests."); |
| 226 | |
| 227 | GTEST_DEFINE_int32_( |
| 228 | stack_trace_depth, |
| 229 | internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), |
| 230 | "The maximum number of stack frames to print when an " |
| 231 | "assertion fails. The valid range is 0 through 100, inclusive."); |
| 232 | |
| 233 | GTEST_DEFINE_bool_( |
| 234 | show_internal_stack_frames, false, |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 235 | "True iff " GTEST_NAME_ " should include internal stack frames when " |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 236 | "printing test failure stack traces."); |
| 237 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 238 | GTEST_DEFINE_bool_( |
| 239 | throw_on_failure, |
| 240 | internal::BoolFromGTestEnv("throw_on_failure", false), |
| 241 | "When this flag is specified, a failed assertion will throw an exception " |
| 242 | "if exceptions are enabled or exit the program with a non-zero code " |
| 243 | "otherwise."); |
| 244 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 245 | namespace internal { |
| 246 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 247 | // g_help_flag is true iff the --help flag or an equivalent form is |
| 248 | // specified on the command line. |
| 249 | static bool g_help_flag = false; |
| 250 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 251 | // GTestIsInitialized() returns true iff the user has initialized |
| 252 | // Google Test. Useful for catching the user mistake of not initializing |
| 253 | // Google Test before calling RUN_ALL_TESTS(). |
| 254 | // |
| 255 | // A user must call testing::InitGoogleTest() to initialize Google |
| 256 | // Test. g_init_gtest_count is set to the number of times |
| 257 | // InitGoogleTest() has been called. We don't protect this variable |
| 258 | // under a mutex as it is only accessed in the main thread. |
| 259 | int g_init_gtest_count = 0; |
| 260 | static bool GTestIsInitialized() { return g_init_gtest_count != 0; } |
| 261 | |
| 262 | // Iterates over a list of TestCases, keeping a running sum of the |
| 263 | // results of calling a given int-returning method on each. |
| 264 | // Returns the sum. |
| 265 | static int SumOverTestCaseList(const internal::List<TestCase*>& case_list, |
| 266 | int (TestCase::*method)() const) { |
| 267 | int sum = 0; |
| 268 | for (const internal::ListNode<TestCase*>* node = case_list.Head(); |
| 269 | node != NULL; |
| 270 | node = node->next()) { |
| 271 | sum += (node->element()->*method)(); |
| 272 | } |
| 273 | return sum; |
| 274 | } |
| 275 | |
| 276 | // Returns true iff the test case passed. |
| 277 | static bool TestCasePassed(const TestCase* test_case) { |
| 278 | return test_case->should_run() && test_case->Passed(); |
| 279 | } |
| 280 | |
| 281 | // Returns true iff the test case failed. |
| 282 | static bool TestCaseFailed(const TestCase* test_case) { |
| 283 | return test_case->should_run() && test_case->Failed(); |
| 284 | } |
| 285 | |
| 286 | // Returns true iff test_case contains at least one test that should |
| 287 | // run. |
| 288 | static bool ShouldRunTestCase(const TestCase* test_case) { |
| 289 | return test_case->should_run(); |
| 290 | } |
| 291 | |
| 292 | // AssertHelper constructor. |
| 293 | AssertHelper::AssertHelper(TestPartResultType type, const char* file, |
| 294 | int line, const char* message) |
| 295 | : type_(type), file_(file), line_(line), message_(message) { |
| 296 | } |
| 297 | |
| 298 | // Message assignment, for assertion streaming support. |
| 299 | void AssertHelper::operator=(const Message& message) const { |
| 300 | UnitTest::GetInstance()-> |
| 301 | AddTestPartResult(type_, file_, line_, |
| 302 | AppendUserMessage(message_, message), |
| 303 | UnitTest::GetInstance()->impl() |
| 304 | ->CurrentOsStackTraceExceptTop(1) |
| 305 | // Skips the stack frame for this function itself. |
| 306 | ); // NOLINT |
| 307 | } |
| 308 | |
| 309 | // Mutex for linked pointers. |
| 310 | Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX); |
| 311 | |
| 312 | // Application pathname gotten in InitGoogleTest. |
| 313 | String g_executable_path; |
| 314 | |
| 315 | // Returns the current application's name, removing directory path if that |
| 316 | // is present. |
| 317 | FilePath GetCurrentExecutableName() { |
| 318 | FilePath result; |
| 319 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 320 | #if defined(_WIN32_WCE) || GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 321 | result.Set(FilePath(g_executable_path).RemoveExtension("exe")); |
| 322 | #else |
| 323 | result.Set(FilePath(g_executable_path)); |
| 324 | #endif // _WIN32_WCE || GTEST_OS_WINDOWS |
| 325 | |
| 326 | return result.RemoveDirectoryName(); |
| 327 | } |
| 328 | |
| 329 | // Functions for processing the gtest_output flag. |
| 330 | |
| 331 | // Returns the output format, or "" for normal printed output. |
| 332 | String UnitTestOptions::GetOutputFormat() { |
| 333 | const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); |
| 334 | if (gtest_output_flag == NULL) return String(""); |
| 335 | |
| 336 | const char* const colon = strchr(gtest_output_flag, ':'); |
| 337 | return (colon == NULL) ? |
| 338 | String(gtest_output_flag) : |
| 339 | String(gtest_output_flag, colon - gtest_output_flag); |
| 340 | } |
| 341 | |
| 342 | // Returns the name of the requested output file, or the default if none |
| 343 | // was explicitly specified. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 344 | String UnitTestOptions::GetAbsolutePathToOutputFile() { |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 345 | const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); |
| 346 | if (gtest_output_flag == NULL) |
| 347 | return String(""); |
| 348 | |
| 349 | const char* const colon = strchr(gtest_output_flag, ':'); |
| 350 | if (colon == NULL) |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 351 | return String(internal::FilePath::ConcatPaths( |
| 352 | internal::FilePath( |
| 353 | UnitTest::GetInstance()->original_working_dir()), |
| 354 | internal::FilePath(kDefaultOutputFile)).ToString() ); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 355 | |
| 356 | internal::FilePath output_name(colon + 1); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 357 | if (!output_name.IsAbsolutePath()) |
| 358 | // TODO(wan@google.com): on Windows \some\path is not an absolute |
| 359 | // path (as its meaning depends on the current drive), yet the |
| 360 | // following logic for turning it into an absolute path is wrong. |
| 361 | // Fix it. |
| 362 | output_name = internal::FilePath::ConcatPaths( |
| 363 | internal::FilePath(UnitTest::GetInstance()->original_working_dir()), |
| 364 | internal::FilePath(colon + 1)); |
| 365 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 366 | if (!output_name.IsDirectory()) |
| 367 | return output_name.ToString(); |
| 368 | |
| 369 | internal::FilePath result(internal::FilePath::GenerateUniqueFileName( |
| 370 | output_name, internal::GetCurrentExecutableName(), |
| 371 | GetOutputFormat().c_str())); |
| 372 | return result.ToString(); |
| 373 | } |
| 374 | |
| 375 | // Returns true iff the wildcard pattern matches the string. The |
| 376 | // first ':' or '\0' character in pattern marks the end of it. |
| 377 | // |
| 378 | // This recursive algorithm isn't very efficient, but is clear and |
| 379 | // works well enough for matching test names, which are short. |
| 380 | bool UnitTestOptions::PatternMatchesString(const char *pattern, |
| 381 | const char *str) { |
| 382 | switch (*pattern) { |
| 383 | case '\0': |
| 384 | case ':': // Either ':' or '\0' marks the end of the pattern. |
| 385 | return *str == '\0'; |
| 386 | case '?': // Matches any single character. |
| 387 | return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); |
| 388 | case '*': // Matches any string (possibly empty) of characters. |
| 389 | return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || |
| 390 | PatternMatchesString(pattern + 1, str); |
| 391 | default: // Non-special character. Matches itself. |
| 392 | return *pattern == *str && |
| 393 | PatternMatchesString(pattern + 1, str + 1); |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { |
| 398 | const char *cur_pattern = filter; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 399 | for (;;) { |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 400 | if (PatternMatchesString(cur_pattern, name.c_str())) { |
| 401 | return true; |
| 402 | } |
| 403 | |
| 404 | // Finds the next pattern in the filter. |
| 405 | cur_pattern = strchr(cur_pattern, ':'); |
| 406 | |
| 407 | // Returns if no more pattern can be found. |
| 408 | if (cur_pattern == NULL) { |
| 409 | return false; |
| 410 | } |
| 411 | |
| 412 | // Skips the pattern separater (the ':' character). |
| 413 | cur_pattern++; |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | // TODO(keithray): move String function implementations to gtest-string.cc. |
| 418 | |
| 419 | // Returns true iff the user-specified filter matches the test case |
| 420 | // name and the test name. |
| 421 | bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, |
| 422 | const String &test_name) { |
| 423 | const String& full_name = String::Format("%s.%s", |
| 424 | test_case_name.c_str(), |
| 425 | test_name.c_str()); |
| 426 | |
| 427 | // Split --gtest_filter at '-', if there is one, to separate into |
| 428 | // positive filter and negative filter portions |
| 429 | const char* const p = GTEST_FLAG(filter).c_str(); |
| 430 | const char* const dash = strchr(p, '-'); |
| 431 | String positive; |
| 432 | String negative; |
| 433 | if (dash == NULL) { |
| 434 | positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter |
| 435 | negative = String(""); |
| 436 | } else { |
| 437 | positive.Set(p, dash - p); // Everything up to the dash |
| 438 | negative = String(dash+1); // Everything after the dash |
| 439 | if (positive.empty()) { |
| 440 | // Treat '-test1' as the same as '*-test1' |
| 441 | positive = kUniversalFilter; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // A filter is a colon-separated list of patterns. It matches a |
| 446 | // test if any pattern in it matches the test. |
| 447 | return (MatchesFilter(full_name, positive.c_str()) && |
| 448 | !MatchesFilter(full_name, negative.c_str())); |
| 449 | } |
| 450 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 451 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 452 | // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the |
| 453 | // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. |
| 454 | // This function is useful as an __except condition. |
| 455 | int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { |
| 456 | // Google Test should handle an exception if: |
| 457 | // 1. the user wants it to, AND |
| 458 | // 2. this is not a breakpoint exception. |
| 459 | return (GTEST_FLAG(catch_exceptions) && |
| 460 | exception_code != EXCEPTION_BREAKPOINT) ? |
| 461 | EXCEPTION_EXECUTE_HANDLER : |
| 462 | EXCEPTION_CONTINUE_SEARCH; |
| 463 | } |
| 464 | #endif // GTEST_OS_WINDOWS |
| 465 | |
| 466 | } // namespace internal |
| 467 | |
| 468 | // The interface for printing the result of a UnitTest |
| 469 | class UnitTestEventListenerInterface { |
| 470 | public: |
| 471 | // The d'tor is pure virtual as this is an abstract class. |
| 472 | virtual ~UnitTestEventListenerInterface() = 0; |
| 473 | |
| 474 | // Called before the unit test starts. |
| 475 | virtual void OnUnitTestStart(const UnitTest*) {} |
| 476 | |
| 477 | // Called after the unit test ends. |
| 478 | virtual void OnUnitTestEnd(const UnitTest*) {} |
| 479 | |
| 480 | // Called before the test case starts. |
| 481 | virtual void OnTestCaseStart(const TestCase*) {} |
| 482 | |
| 483 | // Called after the test case ends. |
| 484 | virtual void OnTestCaseEnd(const TestCase*) {} |
| 485 | |
| 486 | // Called before the global set-up starts. |
| 487 | virtual void OnGlobalSetUpStart(const UnitTest*) {} |
| 488 | |
| 489 | // Called after the global set-up ends. |
| 490 | virtual void OnGlobalSetUpEnd(const UnitTest*) {} |
| 491 | |
| 492 | // Called before the global tear-down starts. |
| 493 | virtual void OnGlobalTearDownStart(const UnitTest*) {} |
| 494 | |
| 495 | // Called after the global tear-down ends. |
| 496 | virtual void OnGlobalTearDownEnd(const UnitTest*) {} |
| 497 | |
| 498 | // Called before the test starts. |
| 499 | virtual void OnTestStart(const TestInfo*) {} |
| 500 | |
| 501 | // Called after the test ends. |
| 502 | virtual void OnTestEnd(const TestInfo*) {} |
| 503 | |
| 504 | // Called after an assertion. |
| 505 | virtual void OnNewTestPartResult(const TestPartResult*) {} |
| 506 | }; |
| 507 | |
| 508 | // The c'tor sets this object as the test part result reporter used by |
| 509 | // Google Test. The 'result' parameter specifies where to report the |
| 510 | // results. Intercepts only failures from the current thread. |
| 511 | ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( |
| 512 | TestPartResultArray* result) |
| 513 | : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), |
| 514 | result_(result) { |
| 515 | Init(); |
| 516 | } |
| 517 | |
| 518 | // The c'tor sets this object as the test part result reporter used by |
| 519 | // Google Test. The 'result' parameter specifies where to report the |
| 520 | // results. |
| 521 | ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( |
| 522 | InterceptMode intercept_mode, TestPartResultArray* result) |
| 523 | : intercept_mode_(intercept_mode), |
| 524 | result_(result) { |
| 525 | Init(); |
| 526 | } |
| 527 | |
| 528 | void ScopedFakeTestPartResultReporter::Init() { |
| 529 | internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl(); |
| 530 | if (intercept_mode_ == INTERCEPT_ALL_THREADS) { |
| 531 | old_reporter_ = impl->GetGlobalTestPartResultReporter(); |
| 532 | impl->SetGlobalTestPartResultReporter(this); |
| 533 | } else { |
| 534 | old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); |
| 535 | impl->SetTestPartResultReporterForCurrentThread(this); |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | // The d'tor restores the test part result reporter used by Google Test |
| 540 | // before. |
| 541 | ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { |
| 542 | internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl(); |
| 543 | if (intercept_mode_ == INTERCEPT_ALL_THREADS) { |
| 544 | impl->SetGlobalTestPartResultReporter(old_reporter_); |
| 545 | } else { |
| 546 | impl->SetTestPartResultReporterForCurrentThread(old_reporter_); |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | // Increments the test part result count and remembers the result. |
| 551 | // This method is from the TestPartResultReporterInterface interface. |
| 552 | void ScopedFakeTestPartResultReporter::ReportTestPartResult( |
| 553 | const TestPartResult& result) { |
| 554 | result_->Append(result); |
| 555 | } |
| 556 | |
| 557 | namespace internal { |
| 558 | |
| 559 | // Returns the type ID of ::testing::Test. We should always call this |
| 560 | // instead of GetTypeId< ::testing::Test>() to get the type ID of |
| 561 | // testing::Test. This is to work around a suspected linker bug when |
| 562 | // using Google Test as a framework on Mac OS X. The bug causes |
| 563 | // GetTypeId< ::testing::Test>() to return different values depending |
| 564 | // on whether the call is from the Google Test framework itself or |
| 565 | // from user test code. GetTestTypeId() is guaranteed to always |
| 566 | // return the same value, as it always calls GetTypeId<>() from the |
| 567 | // gtest.cc, which is within the Google Test framework. |
| 568 | TypeId GetTestTypeId() { |
| 569 | return GetTypeId<Test>(); |
| 570 | } |
| 571 | |
| 572 | // The value of GetTestTypeId() as seen from within the Google Test |
| 573 | // library. This is solely for testing GetTestTypeId(). |
Bill Wendling | 0a0124e | 2009-12-16 19:36:42 +0000 | [diff] [blame] | 574 | const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 575 | |
| 576 | // This predicate-formatter checks that 'results' contains a test part |
| 577 | // failure of the given type and that the failure message contains the |
| 578 | // given substring. |
| 579 | AssertionResult HasOneFailure(const char* /* results_expr */, |
| 580 | const char* /* type_expr */, |
| 581 | const char* /* substr_expr */, |
| 582 | const TestPartResultArray& results, |
| 583 | TestPartResultType type, |
| 584 | const char* substr) { |
| 585 | const String expected( |
| 586 | type == TPRT_FATAL_FAILURE ? "1 fatal failure" : |
| 587 | "1 non-fatal failure"); |
| 588 | Message msg; |
| 589 | if (results.size() != 1) { |
| 590 | msg << "Expected: " << expected << "\n" |
| 591 | << " Actual: " << results.size() << " failures"; |
| 592 | for (int i = 0; i < results.size(); i++) { |
| 593 | msg << "\n" << results.GetTestPartResult(i); |
| 594 | } |
| 595 | return AssertionFailure(msg); |
| 596 | } |
| 597 | |
| 598 | const TestPartResult& r = results.GetTestPartResult(0); |
| 599 | if (r.type() != type) { |
| 600 | msg << "Expected: " << expected << "\n" |
| 601 | << " Actual:\n" |
| 602 | << r; |
| 603 | return AssertionFailure(msg); |
| 604 | } |
| 605 | |
| 606 | if (strstr(r.message(), substr) == NULL) { |
| 607 | msg << "Expected: " << expected << " containing \"" |
| 608 | << substr << "\"\n" |
| 609 | << " Actual:\n" |
| 610 | << r; |
| 611 | return AssertionFailure(msg); |
| 612 | } |
| 613 | |
| 614 | return AssertionSuccess(); |
| 615 | } |
| 616 | |
| 617 | // The constructor of SingleFailureChecker remembers where to look up |
| 618 | // test part results, what type of failure we expect, and what |
| 619 | // substring the failure message should contain. |
| 620 | SingleFailureChecker:: SingleFailureChecker( |
| 621 | const TestPartResultArray* results, |
| 622 | TestPartResultType type, |
| 623 | const char* substr) |
| 624 | : results_(results), |
| 625 | type_(type), |
| 626 | substr_(substr) {} |
| 627 | |
| 628 | // The destructor of SingleFailureChecker verifies that the given |
| 629 | // TestPartResultArray contains exactly one failure that has the given |
| 630 | // type and contains the given substring. If that's not the case, a |
| 631 | // non-fatal failure will be generated. |
| 632 | SingleFailureChecker::~SingleFailureChecker() { |
| 633 | EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str()); |
| 634 | } |
| 635 | |
| 636 | DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( |
| 637 | UnitTestImpl* unit_test) : unit_test_(unit_test) {} |
| 638 | |
| 639 | void DefaultGlobalTestPartResultReporter::ReportTestPartResult( |
| 640 | const TestPartResult& result) { |
| 641 | unit_test_->current_test_result()->AddTestPartResult(result); |
| 642 | unit_test_->result_printer()->OnNewTestPartResult(&result); |
| 643 | } |
| 644 | |
| 645 | DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( |
| 646 | UnitTestImpl* unit_test) : unit_test_(unit_test) {} |
| 647 | |
| 648 | void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( |
| 649 | const TestPartResult& result) { |
| 650 | unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); |
| 651 | } |
| 652 | |
| 653 | // Returns the global test part result reporter. |
| 654 | TestPartResultReporterInterface* |
| 655 | UnitTestImpl::GetGlobalTestPartResultReporter() { |
| 656 | internal::MutexLock lock(&global_test_part_result_reporter_mutex_); |
| 657 | return global_test_part_result_repoter_; |
| 658 | } |
| 659 | |
| 660 | // Sets the global test part result reporter. |
| 661 | void UnitTestImpl::SetGlobalTestPartResultReporter( |
| 662 | TestPartResultReporterInterface* reporter) { |
| 663 | internal::MutexLock lock(&global_test_part_result_reporter_mutex_); |
| 664 | global_test_part_result_repoter_ = reporter; |
| 665 | } |
| 666 | |
| 667 | // Returns the test part result reporter for the current thread. |
| 668 | TestPartResultReporterInterface* |
| 669 | UnitTestImpl::GetTestPartResultReporterForCurrentThread() { |
| 670 | return per_thread_test_part_result_reporter_.get(); |
| 671 | } |
| 672 | |
| 673 | // Sets the test part result reporter for the current thread. |
| 674 | void UnitTestImpl::SetTestPartResultReporterForCurrentThread( |
| 675 | TestPartResultReporterInterface* reporter) { |
| 676 | per_thread_test_part_result_reporter_.set(reporter); |
| 677 | } |
| 678 | |
| 679 | // Gets the number of successful test cases. |
| 680 | int UnitTestImpl::successful_test_case_count() const { |
| 681 | return test_cases_.CountIf(TestCasePassed); |
| 682 | } |
| 683 | |
| 684 | // Gets the number of failed test cases. |
| 685 | int UnitTestImpl::failed_test_case_count() const { |
| 686 | return test_cases_.CountIf(TestCaseFailed); |
| 687 | } |
| 688 | |
| 689 | // Gets the number of all test cases. |
| 690 | int UnitTestImpl::total_test_case_count() const { |
| 691 | return test_cases_.size(); |
| 692 | } |
| 693 | |
| 694 | // Gets the number of all test cases that contain at least one test |
| 695 | // that should run. |
| 696 | int UnitTestImpl::test_case_to_run_count() const { |
| 697 | return test_cases_.CountIf(ShouldRunTestCase); |
| 698 | } |
| 699 | |
| 700 | // Gets the number of successful tests. |
| 701 | int UnitTestImpl::successful_test_count() const { |
| 702 | return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); |
| 703 | } |
| 704 | |
| 705 | // Gets the number of failed tests. |
| 706 | int UnitTestImpl::failed_test_count() const { |
| 707 | return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); |
| 708 | } |
| 709 | |
| 710 | // Gets the number of disabled tests. |
| 711 | int UnitTestImpl::disabled_test_count() const { |
| 712 | return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); |
| 713 | } |
| 714 | |
| 715 | // Gets the number of all tests. |
| 716 | int UnitTestImpl::total_test_count() const { |
| 717 | return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); |
| 718 | } |
| 719 | |
| 720 | // Gets the number of tests that should run. |
| 721 | int UnitTestImpl::test_to_run_count() const { |
| 722 | return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); |
| 723 | } |
| 724 | |
| 725 | // Returns the current OS stack trace as a String. |
| 726 | // |
| 727 | // The maximum number of stack frames to be included is specified by |
| 728 | // the gtest_stack_trace_depth flag. The skip_count parameter |
| 729 | // specifies the number of top frames to be skipped, which doesn't |
| 730 | // count against the number of frames to be included. |
| 731 | // |
| 732 | // For example, if Foo() calls Bar(), which in turn calls |
| 733 | // CurrentOsStackTraceExceptTop(1), Foo() will be included in the |
| 734 | // trace but Bar() and CurrentOsStackTraceExceptTop() won't. |
| 735 | String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { |
| 736 | (void)skip_count; |
| 737 | return String(""); |
| 738 | } |
| 739 | |
| 740 | static TimeInMillis GetTimeInMillis() { |
| 741 | #ifdef _WIN32_WCE // We are on Windows CE |
| 742 | // Difference between 1970-01-01 and 1601-01-01 in miliseconds. |
| 743 | // http://analogous.blogspot.com/2005/04/epoch.html |
| 744 | const TimeInMillis kJavaEpochToWinFileTimeDelta = 11644473600000UL; |
| 745 | const DWORD kTenthMicrosInMilliSecond = 10000; |
| 746 | |
| 747 | SYSTEMTIME now_systime; |
| 748 | FILETIME now_filetime; |
| 749 | ULARGE_INTEGER now_int64; |
| 750 | // TODO(kenton@google.com): Shouldn't this just use |
| 751 | // GetSystemTimeAsFileTime()? |
| 752 | GetSystemTime(&now_systime); |
| 753 | if (SystemTimeToFileTime(&now_systime, &now_filetime)) { |
| 754 | now_int64.LowPart = now_filetime.dwLowDateTime; |
| 755 | now_int64.HighPart = now_filetime.dwHighDateTime; |
| 756 | now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - |
| 757 | kJavaEpochToWinFileTimeDelta; |
| 758 | return now_int64.QuadPart; |
| 759 | } |
| 760 | return 0; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 761 | #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 762 | __timeb64 now; |
| 763 | #ifdef _MSC_VER |
| 764 | // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 |
| 765 | // (deprecated function) there. |
| 766 | // TODO(kenton@google.com): Use GetTickCount()? Or use |
| 767 | // SystemTimeToFileTime() |
| 768 | #pragma warning(push) // Saves the current warning state. |
| 769 | #pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 770 | _ftime64(&now); |
| 771 | #pragma warning(pop) // Restores the warning state. |
| 772 | #else |
| 773 | _ftime64(&now); |
| 774 | #endif // _MSC_VER |
| 775 | return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 776 | #elif GTEST_HAS_GETTIMEOFDAY_ |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 777 | struct timeval now; |
| 778 | gettimeofday(&now, NULL); |
| 779 | return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; |
| 780 | #else |
| 781 | #error "Don't know how to get the current time on your system." |
| 782 | #endif |
| 783 | } |
| 784 | |
| 785 | // Utilities |
| 786 | |
| 787 | // class String |
| 788 | |
| 789 | // Returns the input enclosed in double quotes if it's not NULL; |
| 790 | // otherwise returns "(null)". For example, "\"Hello\"" is returned |
| 791 | // for input "Hello". |
| 792 | // |
| 793 | // This is useful for printing a C string in the syntax of a literal. |
| 794 | // |
| 795 | // Known issue: escape sequences are not handled yet. |
| 796 | String String::ShowCStringQuoted(const char* c_str) { |
| 797 | return c_str ? String::Format("\"%s\"", c_str) : String("(null)"); |
| 798 | } |
| 799 | |
| 800 | // Copies at most length characters from str into a newly-allocated |
| 801 | // piece of memory of size length+1. The memory is allocated with new[]. |
| 802 | // A terminating null byte is written to the memory, and a pointer to it |
| 803 | // is returned. If str is NULL, NULL is returned. |
| 804 | static char* CloneString(const char* str, size_t length) { |
| 805 | if (str == NULL) { |
| 806 | return NULL; |
| 807 | } else { |
| 808 | char* const clone = new char[length + 1]; |
| 809 | // MSVC 8 deprecates strncpy(), so we want to suppress warning |
| 810 | // 4996 (deprecated function) there. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 811 | #if GTEST_OS_WINDOWS // We are on Windows. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 812 | #pragma warning(push) // Saves the current warning state. |
| 813 | #pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 814 | strncpy(clone, str, length); |
| 815 | #pragma warning(pop) // Restores the warning state. |
| 816 | #else // We are on Linux or Mac OS. |
| 817 | strncpy(clone, str, length); |
| 818 | #endif // GTEST_OS_WINDOWS |
| 819 | clone[length] = '\0'; |
| 820 | return clone; |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | // Clones a 0-terminated C string, allocating memory using new. The |
| 825 | // caller is responsible for deleting[] the return value. Returns the |
| 826 | // cloned string, or NULL if the input is NULL. |
| 827 | const char * String::CloneCString(const char* c_str) { |
| 828 | return (c_str == NULL) ? |
| 829 | NULL : CloneString(c_str, strlen(c_str)); |
| 830 | } |
| 831 | |
| 832 | #ifdef _WIN32_WCE |
| 833 | // Creates a UTF-16 wide string from the given ANSI string, allocating |
| 834 | // memory using new. The caller is responsible for deleting the return |
| 835 | // value using delete[]. Returns the wide string, or NULL if the |
| 836 | // input is NULL. |
| 837 | LPCWSTR String::AnsiToUtf16(const char* ansi) { |
| 838 | if (!ansi) return NULL; |
| 839 | const int length = strlen(ansi); |
| 840 | const int unicode_length = |
| 841 | MultiByteToWideChar(CP_ACP, 0, ansi, length, |
| 842 | NULL, 0); |
| 843 | WCHAR* unicode = new WCHAR[unicode_length + 1]; |
| 844 | MultiByteToWideChar(CP_ACP, 0, ansi, length, |
| 845 | unicode, unicode_length); |
| 846 | unicode[unicode_length] = 0; |
| 847 | return unicode; |
| 848 | } |
| 849 | |
| 850 | // Creates an ANSI string from the given wide string, allocating |
| 851 | // memory using new. The caller is responsible for deleting the return |
| 852 | // value using delete[]. Returns the ANSI string, or NULL if the |
| 853 | // input is NULL. |
| 854 | const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { |
| 855 | if (!utf16_str) return NULL; |
| 856 | const int ansi_length = |
| 857 | WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, |
| 858 | NULL, 0, NULL, NULL); |
| 859 | char* ansi = new char[ansi_length + 1]; |
| 860 | WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, |
| 861 | ansi, ansi_length, NULL, NULL); |
| 862 | ansi[ansi_length] = 0; |
| 863 | return ansi; |
| 864 | } |
| 865 | |
| 866 | #endif // _WIN32_WCE |
| 867 | |
| 868 | // Compares two C strings. Returns true iff they have the same content. |
| 869 | // |
| 870 | // Unlike strcmp(), this function can handle NULL argument(s). A NULL |
| 871 | // C string is considered different to any non-NULL C string, |
| 872 | // including the empty string. |
| 873 | bool String::CStringEquals(const char * lhs, const char * rhs) { |
| 874 | if ( lhs == NULL ) return rhs == NULL; |
| 875 | |
| 876 | if ( rhs == NULL ) return false; |
| 877 | |
| 878 | return strcmp(lhs, rhs) == 0; |
| 879 | } |
| 880 | |
| 881 | #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING |
| 882 | |
| 883 | // Converts an array of wide chars to a narrow string using the UTF-8 |
| 884 | // encoding, and streams the result to the given Message object. |
| 885 | static void StreamWideCharsToMessage(const wchar_t* wstr, size_t len, |
| 886 | Message* msg) { |
| 887 | // TODO(wan): consider allowing a testing::String object to |
| 888 | // contain '\0'. This will make it behave more like std::string, |
| 889 | // and will allow ToUtf8String() to return the correct encoding |
| 890 | // for '\0' s.t. we can get rid of the conditional here (and in |
| 891 | // several other places). |
| 892 | for (size_t i = 0; i != len; ) { // NOLINT |
| 893 | if (wstr[i] != L'\0') { |
| 894 | *msg << WideStringToUtf8(wstr + i, static_cast<int>(len - i)); |
| 895 | while (i != len && wstr[i] != L'\0') |
| 896 | i++; |
| 897 | } else { |
| 898 | *msg << '\0'; |
| 899 | i++; |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | |
| 904 | #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING |
| 905 | |
| 906 | } // namespace internal |
| 907 | |
| 908 | #if GTEST_HAS_STD_WSTRING |
| 909 | // Converts the given wide string to a narrow string using the UTF-8 |
| 910 | // encoding, and streams the result to this Message object. |
| 911 | Message& Message::operator <<(const ::std::wstring& wstr) { |
| 912 | internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); |
| 913 | return *this; |
| 914 | } |
| 915 | #endif // GTEST_HAS_STD_WSTRING |
| 916 | |
| 917 | #if GTEST_HAS_GLOBAL_WSTRING |
| 918 | // Converts the given wide string to a narrow string using the UTF-8 |
| 919 | // encoding, and streams the result to this Message object. |
| 920 | Message& Message::operator <<(const ::wstring& wstr) { |
| 921 | internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); |
| 922 | return *this; |
| 923 | } |
| 924 | #endif // GTEST_HAS_GLOBAL_WSTRING |
| 925 | |
| 926 | namespace internal { |
| 927 | |
| 928 | // Formats a value to be used in a failure message. |
| 929 | |
| 930 | // For a char value, we print it as a C++ char literal and as an |
| 931 | // unsigned integer (both in decimal and in hexadecimal). |
| 932 | String FormatForFailureMessage(char ch) { |
| 933 | const unsigned int ch_as_uint = ch; |
| 934 | // A String object cannot contain '\0', so we print "\\0" when ch is |
| 935 | // '\0'. |
| 936 | return String::Format("'%s' (%u, 0x%X)", |
| 937 | ch ? String::Format("%c", ch).c_str() : "\\0", |
| 938 | ch_as_uint, ch_as_uint); |
| 939 | } |
| 940 | |
| 941 | // For a wchar_t value, we print it as a C++ wchar_t literal and as an |
| 942 | // unsigned integer (both in decimal and in hexidecimal). |
| 943 | String FormatForFailureMessage(wchar_t wchar) { |
| 944 | // The C++ standard doesn't specify the exact size of the wchar_t |
| 945 | // type. It just says that it shall have the same size as another |
| 946 | // integral type, called its underlying type. |
| 947 | // |
| 948 | // Therefore, in order to print a wchar_t value in the numeric form, |
| 949 | // we first convert it to the largest integral type (UInt64) and |
| 950 | // then print the converted value. |
| 951 | // |
| 952 | // We use streaming to print the value as "%llu" doesn't work |
| 953 | // correctly with MSVC 7.1. |
| 954 | const UInt64 wchar_as_uint64 = wchar; |
| 955 | Message msg; |
| 956 | // A String object cannot contain '\0', so we print "\\0" when wchar is |
| 957 | // L'\0'. |
| 958 | char buffer[32]; // CodePointToUtf8 requires a buffer that big. |
| 959 | msg << "L'" |
| 960 | << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0") |
| 961 | << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16) |
| 962 | << wchar_as_uint64 << ")"; |
| 963 | return msg.GetString(); |
| 964 | } |
| 965 | |
| 966 | } // namespace internal |
| 967 | |
| 968 | // AssertionResult constructor. |
| 969 | AssertionResult::AssertionResult(const internal::String& failure_message) |
| 970 | : failure_message_(failure_message) { |
| 971 | } |
| 972 | |
| 973 | |
| 974 | // Makes a successful assertion result. |
| 975 | AssertionResult AssertionSuccess() { |
| 976 | return AssertionResult(); |
| 977 | } |
| 978 | |
| 979 | |
| 980 | // Makes a failed assertion result with the given failure message. |
| 981 | AssertionResult AssertionFailure(const Message& message) { |
| 982 | return AssertionResult(message.GetString()); |
| 983 | } |
| 984 | |
| 985 | namespace internal { |
| 986 | |
| 987 | // Constructs and returns the message for an equality assertion |
| 988 | // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. |
| 989 | // |
| 990 | // The first four parameters are the expressions used in the assertion |
| 991 | // and their values, as strings. For example, for ASSERT_EQ(foo, bar) |
| 992 | // where foo is 5 and bar is 6, we have: |
| 993 | // |
| 994 | // expected_expression: "foo" |
| 995 | // actual_expression: "bar" |
| 996 | // expected_value: "5" |
| 997 | // actual_value: "6" |
| 998 | // |
| 999 | // The ignoring_case parameter is true iff the assertion is a |
| 1000 | // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will |
| 1001 | // be inserted into the message. |
| 1002 | AssertionResult EqFailure(const char* expected_expression, |
| 1003 | const char* actual_expression, |
| 1004 | const String& expected_value, |
| 1005 | const String& actual_value, |
| 1006 | bool ignoring_case) { |
| 1007 | Message msg; |
| 1008 | msg << "Value of: " << actual_expression; |
| 1009 | if (actual_value != actual_expression) { |
| 1010 | msg << "\n Actual: " << actual_value; |
| 1011 | } |
| 1012 | |
| 1013 | msg << "\nExpected: " << expected_expression; |
| 1014 | if (ignoring_case) { |
| 1015 | msg << " (ignoring case)"; |
| 1016 | } |
| 1017 | if (expected_value != expected_expression) { |
| 1018 | msg << "\nWhich is: " << expected_value; |
| 1019 | } |
| 1020 | |
| 1021 | return AssertionFailure(msg); |
| 1022 | } |
| 1023 | |
| 1024 | |
| 1025 | // Helper function for implementing ASSERT_NEAR. |
| 1026 | AssertionResult DoubleNearPredFormat(const char* expr1, |
| 1027 | const char* expr2, |
| 1028 | const char* abs_error_expr, |
| 1029 | double val1, |
| 1030 | double val2, |
| 1031 | double abs_error) { |
| 1032 | const double diff = fabs(val1 - val2); |
| 1033 | if (diff <= abs_error) return AssertionSuccess(); |
| 1034 | |
| 1035 | // TODO(wan): do not print the value of an expression if it's |
| 1036 | // already a literal. |
| 1037 | Message msg; |
| 1038 | msg << "The difference between " << expr1 << " and " << expr2 |
| 1039 | << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" |
| 1040 | << expr1 << " evaluates to " << val1 << ",\n" |
| 1041 | << expr2 << " evaluates to " << val2 << ", and\n" |
| 1042 | << abs_error_expr << " evaluates to " << abs_error << "."; |
| 1043 | return AssertionFailure(msg); |
| 1044 | } |
| 1045 | |
| 1046 | |
| 1047 | // Helper template for implementing FloatLE() and DoubleLE(). |
| 1048 | template <typename RawType> |
| 1049 | AssertionResult FloatingPointLE(const char* expr1, |
| 1050 | const char* expr2, |
| 1051 | RawType val1, |
| 1052 | RawType val2) { |
| 1053 | // Returns success if val1 is less than val2, |
| 1054 | if (val1 < val2) { |
| 1055 | return AssertionSuccess(); |
| 1056 | } |
| 1057 | |
| 1058 | // or if val1 is almost equal to val2. |
| 1059 | const FloatingPoint<RawType> lhs(val1), rhs(val2); |
| 1060 | if (lhs.AlmostEquals(rhs)) { |
| 1061 | return AssertionSuccess(); |
| 1062 | } |
| 1063 | |
| 1064 | // Note that the above two checks will both fail if either val1 or |
| 1065 | // val2 is NaN, as the IEEE floating-point standard requires that |
| 1066 | // any predicate involving a NaN must return false. |
| 1067 | |
| 1068 | StrStream val1_ss; |
| 1069 | val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) |
| 1070 | << val1; |
| 1071 | |
| 1072 | StrStream val2_ss; |
| 1073 | val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) |
| 1074 | << val2; |
| 1075 | |
| 1076 | Message msg; |
| 1077 | msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" |
| 1078 | << " Actual: " << StrStreamToString(&val1_ss) << " vs " |
| 1079 | << StrStreamToString(&val2_ss); |
| 1080 | |
| 1081 | return AssertionFailure(msg); |
| 1082 | } |
| 1083 | |
| 1084 | } // namespace internal |
| 1085 | |
| 1086 | // Asserts that val1 is less than, or almost equal to, val2. Fails |
| 1087 | // otherwise. In particular, it fails if either val1 or val2 is NaN. |
| 1088 | AssertionResult FloatLE(const char* expr1, const char* expr2, |
| 1089 | float val1, float val2) { |
| 1090 | return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); |
| 1091 | } |
| 1092 | |
| 1093 | // Asserts that val1 is less than, or almost equal to, val2. Fails |
| 1094 | // otherwise. In particular, it fails if either val1 or val2 is NaN. |
| 1095 | AssertionResult DoubleLE(const char* expr1, const char* expr2, |
| 1096 | double val1, double val2) { |
| 1097 | return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); |
| 1098 | } |
| 1099 | |
| 1100 | namespace internal { |
| 1101 | |
| 1102 | // The helper function for {ASSERT|EXPECT}_EQ with int or enum |
| 1103 | // arguments. |
| 1104 | AssertionResult CmpHelperEQ(const char* expected_expression, |
| 1105 | const char* actual_expression, |
| 1106 | BiggestInt expected, |
| 1107 | BiggestInt actual) { |
| 1108 | if (expected == actual) { |
| 1109 | return AssertionSuccess(); |
| 1110 | } |
| 1111 | |
| 1112 | return EqFailure(expected_expression, |
| 1113 | actual_expression, |
| 1114 | FormatForComparisonFailureMessage(expected, actual), |
| 1115 | FormatForComparisonFailureMessage(actual, expected), |
| 1116 | false); |
| 1117 | } |
| 1118 | |
| 1119 | // A macro for implementing the helper functions needed to implement |
| 1120 | // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here |
| 1121 | // just to avoid copy-and-paste of similar code. |
| 1122 | #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ |
| 1123 | AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ |
| 1124 | BiggestInt val1, BiggestInt val2) {\ |
| 1125 | if (val1 op val2) {\ |
| 1126 | return AssertionSuccess();\ |
| 1127 | } else {\ |
| 1128 | Message msg;\ |
| 1129 | msg << "Expected: (" << expr1 << ") " #op " (" << expr2\ |
| 1130 | << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ |
| 1131 | << " vs " << FormatForComparisonFailureMessage(val2, val1);\ |
| 1132 | return AssertionFailure(msg);\ |
| 1133 | }\ |
| 1134 | } |
| 1135 | |
| 1136 | // Implements the helper function for {ASSERT|EXPECT}_NE with int or |
| 1137 | // enum arguments. |
| 1138 | GTEST_IMPL_CMP_HELPER_(NE, !=) |
| 1139 | // Implements the helper function for {ASSERT|EXPECT}_LE with int or |
| 1140 | // enum arguments. |
| 1141 | GTEST_IMPL_CMP_HELPER_(LE, <=) |
| 1142 | // Implements the helper function for {ASSERT|EXPECT}_LT with int or |
| 1143 | // enum arguments. |
| 1144 | GTEST_IMPL_CMP_HELPER_(LT, < ) |
| 1145 | // Implements the helper function for {ASSERT|EXPECT}_GE with int or |
| 1146 | // enum arguments. |
| 1147 | GTEST_IMPL_CMP_HELPER_(GE, >=) |
| 1148 | // Implements the helper function for {ASSERT|EXPECT}_GT with int or |
| 1149 | // enum arguments. |
| 1150 | GTEST_IMPL_CMP_HELPER_(GT, > ) |
| 1151 | |
| 1152 | #undef GTEST_IMPL_CMP_HELPER_ |
| 1153 | |
| 1154 | // The helper function for {ASSERT|EXPECT}_STREQ. |
| 1155 | AssertionResult CmpHelperSTREQ(const char* expected_expression, |
| 1156 | const char* actual_expression, |
| 1157 | const char* expected, |
| 1158 | const char* actual) { |
| 1159 | if (String::CStringEquals(expected, actual)) { |
| 1160 | return AssertionSuccess(); |
| 1161 | } |
| 1162 | |
| 1163 | return EqFailure(expected_expression, |
| 1164 | actual_expression, |
| 1165 | String::ShowCStringQuoted(expected), |
| 1166 | String::ShowCStringQuoted(actual), |
| 1167 | false); |
| 1168 | } |
| 1169 | |
| 1170 | // The helper function for {ASSERT|EXPECT}_STRCASEEQ. |
| 1171 | AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, |
| 1172 | const char* actual_expression, |
| 1173 | const char* expected, |
| 1174 | const char* actual) { |
| 1175 | if (String::CaseInsensitiveCStringEquals(expected, actual)) { |
| 1176 | return AssertionSuccess(); |
| 1177 | } |
| 1178 | |
| 1179 | return EqFailure(expected_expression, |
| 1180 | actual_expression, |
| 1181 | String::ShowCStringQuoted(expected), |
| 1182 | String::ShowCStringQuoted(actual), |
| 1183 | true); |
| 1184 | } |
| 1185 | |
| 1186 | // The helper function for {ASSERT|EXPECT}_STRNE. |
| 1187 | AssertionResult CmpHelperSTRNE(const char* s1_expression, |
| 1188 | const char* s2_expression, |
| 1189 | const char* s1, |
| 1190 | const char* s2) { |
| 1191 | if (!String::CStringEquals(s1, s2)) { |
| 1192 | return AssertionSuccess(); |
| 1193 | } else { |
| 1194 | Message msg; |
| 1195 | msg << "Expected: (" << s1_expression << ") != (" |
| 1196 | << s2_expression << "), actual: \"" |
| 1197 | << s1 << "\" vs \"" << s2 << "\""; |
| 1198 | return AssertionFailure(msg); |
| 1199 | } |
| 1200 | } |
| 1201 | |
| 1202 | // The helper function for {ASSERT|EXPECT}_STRCASENE. |
| 1203 | AssertionResult CmpHelperSTRCASENE(const char* s1_expression, |
| 1204 | const char* s2_expression, |
| 1205 | const char* s1, |
| 1206 | const char* s2) { |
| 1207 | if (!String::CaseInsensitiveCStringEquals(s1, s2)) { |
| 1208 | return AssertionSuccess(); |
| 1209 | } else { |
| 1210 | Message msg; |
| 1211 | msg << "Expected: (" << s1_expression << ") != (" |
| 1212 | << s2_expression << ") (ignoring case), actual: \"" |
| 1213 | << s1 << "\" vs \"" << s2 << "\""; |
| 1214 | return AssertionFailure(msg); |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | } // namespace internal |
| 1219 | |
| 1220 | namespace { |
| 1221 | |
| 1222 | // Helper functions for implementing IsSubString() and IsNotSubstring(). |
| 1223 | |
| 1224 | // This group of overloaded functions return true iff needle is a |
| 1225 | // substring of haystack. NULL is considered a substring of itself |
| 1226 | // only. |
| 1227 | |
| 1228 | bool IsSubstringPred(const char* needle, const char* haystack) { |
| 1229 | if (needle == NULL || haystack == NULL) |
| 1230 | return needle == haystack; |
| 1231 | |
| 1232 | return strstr(haystack, needle) != NULL; |
| 1233 | } |
| 1234 | |
| 1235 | bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { |
| 1236 | if (needle == NULL || haystack == NULL) |
| 1237 | return needle == haystack; |
| 1238 | |
| 1239 | return wcsstr(haystack, needle) != NULL; |
| 1240 | } |
| 1241 | |
| 1242 | // StringType here can be either ::std::string or ::std::wstring. |
| 1243 | template <typename StringType> |
| 1244 | bool IsSubstringPred(const StringType& needle, |
| 1245 | const StringType& haystack) { |
| 1246 | return haystack.find(needle) != StringType::npos; |
| 1247 | } |
| 1248 | |
| 1249 | // This function implements either IsSubstring() or IsNotSubstring(), |
| 1250 | // depending on the value of the expected_to_be_substring parameter. |
| 1251 | // StringType here can be const char*, const wchar_t*, ::std::string, |
| 1252 | // or ::std::wstring. |
| 1253 | template <typename StringType> |
| 1254 | AssertionResult IsSubstringImpl( |
| 1255 | bool expected_to_be_substring, |
| 1256 | const char* needle_expr, const char* haystack_expr, |
| 1257 | const StringType& needle, const StringType& haystack) { |
| 1258 | if (IsSubstringPred(needle, haystack) == expected_to_be_substring) |
| 1259 | return AssertionSuccess(); |
| 1260 | |
| 1261 | const bool is_wide_string = sizeof(needle[0]) > 1; |
| 1262 | const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; |
| 1263 | return AssertionFailure( |
| 1264 | Message() |
| 1265 | << "Value of: " << needle_expr << "\n" |
| 1266 | << " Actual: " << begin_string_quote << needle << "\"\n" |
| 1267 | << "Expected: " << (expected_to_be_substring ? "" : "not ") |
| 1268 | << "a substring of " << haystack_expr << "\n" |
| 1269 | << "Which is: " << begin_string_quote << haystack << "\""); |
| 1270 | } |
| 1271 | |
| 1272 | } // namespace |
| 1273 | |
| 1274 | // IsSubstring() and IsNotSubstring() check whether needle is a |
| 1275 | // substring of haystack (NULL is considered a substring of itself |
| 1276 | // only), and return an appropriate error message when they fail. |
| 1277 | |
| 1278 | AssertionResult IsSubstring( |
| 1279 | const char* needle_expr, const char* haystack_expr, |
| 1280 | const char* needle, const char* haystack) { |
| 1281 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1282 | } |
| 1283 | |
| 1284 | AssertionResult IsSubstring( |
| 1285 | const char* needle_expr, const char* haystack_expr, |
| 1286 | const wchar_t* needle, const wchar_t* haystack) { |
| 1287 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1288 | } |
| 1289 | |
| 1290 | AssertionResult IsNotSubstring( |
| 1291 | const char* needle_expr, const char* haystack_expr, |
| 1292 | const char* needle, const char* haystack) { |
| 1293 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1294 | } |
| 1295 | |
| 1296 | AssertionResult IsNotSubstring( |
| 1297 | const char* needle_expr, const char* haystack_expr, |
| 1298 | const wchar_t* needle, const wchar_t* haystack) { |
| 1299 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1300 | } |
| 1301 | |
| 1302 | #if GTEST_HAS_STD_STRING |
| 1303 | AssertionResult IsSubstring( |
| 1304 | const char* needle_expr, const char* haystack_expr, |
| 1305 | const ::std::string& needle, const ::std::string& haystack) { |
| 1306 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1307 | } |
| 1308 | |
| 1309 | AssertionResult IsNotSubstring( |
| 1310 | const char* needle_expr, const char* haystack_expr, |
| 1311 | const ::std::string& needle, const ::std::string& haystack) { |
| 1312 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1313 | } |
| 1314 | #endif // GTEST_HAS_STD_STRING |
| 1315 | |
| 1316 | #if GTEST_HAS_STD_WSTRING |
| 1317 | AssertionResult IsSubstring( |
| 1318 | const char* needle_expr, const char* haystack_expr, |
| 1319 | const ::std::wstring& needle, const ::std::wstring& haystack) { |
| 1320 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1321 | } |
| 1322 | |
| 1323 | AssertionResult IsNotSubstring( |
| 1324 | const char* needle_expr, const char* haystack_expr, |
| 1325 | const ::std::wstring& needle, const ::std::wstring& haystack) { |
| 1326 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1327 | } |
| 1328 | #endif // GTEST_HAS_STD_WSTRING |
| 1329 | |
| 1330 | namespace internal { |
| 1331 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1332 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1333 | |
| 1334 | namespace { |
| 1335 | |
| 1336 | // Helper function for IsHRESULT{SuccessFailure} predicates |
| 1337 | AssertionResult HRESULTFailureHelper(const char* expr, |
| 1338 | const char* expected, |
| 1339 | long hr) { // NOLINT |
| 1340 | #ifdef _WIN32_WCE |
| 1341 | // Windows CE doesn't support FormatMessage. |
| 1342 | const char error_text[] = ""; |
| 1343 | #else |
| 1344 | // Looks up the human-readable system message for the HRESULT code |
| 1345 | // and since we're not passing any params to FormatMessage, we don't |
| 1346 | // want inserts expanded. |
| 1347 | const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | |
| 1348 | FORMAT_MESSAGE_IGNORE_INSERTS; |
| 1349 | const DWORD kBufSize = 4096; // String::Format can't exceed this length. |
| 1350 | // Gets the system's human readable message string for this HRESULT. |
| 1351 | char error_text[kBufSize] = { '\0' }; |
| 1352 | DWORD message_length = ::FormatMessageA(kFlags, |
| 1353 | 0, // no source, we're asking system |
| 1354 | hr, // the error |
| 1355 | 0, // no line width restrictions |
| 1356 | error_text, // output buffer |
| 1357 | kBufSize, // buf size |
| 1358 | NULL); // no arguments for inserts |
| 1359 | // Trims tailing white space (FormatMessage leaves a trailing cr-lf) |
| 1360 | for (; message_length && isspace(error_text[message_length - 1]); |
| 1361 | --message_length) { |
| 1362 | error_text[message_length - 1] = '\0'; |
| 1363 | } |
| 1364 | #endif // _WIN32_WCE |
| 1365 | |
| 1366 | const String error_hex(String::Format("0x%08X ", hr)); |
| 1367 | Message msg; |
| 1368 | msg << "Expected: " << expr << " " << expected << ".\n" |
| 1369 | << " Actual: " << error_hex << error_text << "\n"; |
| 1370 | |
| 1371 | return ::testing::AssertionFailure(msg); |
| 1372 | } |
| 1373 | |
| 1374 | } // namespace |
| 1375 | |
| 1376 | AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT |
| 1377 | if (SUCCEEDED(hr)) { |
| 1378 | return AssertionSuccess(); |
| 1379 | } |
| 1380 | return HRESULTFailureHelper(expr, "succeeds", hr); |
| 1381 | } |
| 1382 | |
| 1383 | AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT |
| 1384 | if (FAILED(hr)) { |
| 1385 | return AssertionSuccess(); |
| 1386 | } |
| 1387 | return HRESULTFailureHelper(expr, "fails", hr); |
| 1388 | } |
| 1389 | |
| 1390 | #endif // GTEST_OS_WINDOWS |
| 1391 | |
| 1392 | // Utility functions for encoding Unicode text (wide strings) in |
| 1393 | // UTF-8. |
| 1394 | |
| 1395 | // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 |
| 1396 | // like this: |
| 1397 | // |
| 1398 | // Code-point length Encoding |
| 1399 | // 0 - 7 bits 0xxxxxxx |
| 1400 | // 8 - 11 bits 110xxxxx 10xxxxxx |
| 1401 | // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx |
| 1402 | // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 1403 | |
| 1404 | // The maximum code-point a one-byte UTF-8 sequence can represent. |
| 1405 | const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; |
| 1406 | |
| 1407 | // The maximum code-point a two-byte UTF-8 sequence can represent. |
| 1408 | const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; |
| 1409 | |
| 1410 | // The maximum code-point a three-byte UTF-8 sequence can represent. |
| 1411 | const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; |
| 1412 | |
| 1413 | // The maximum code-point a four-byte UTF-8 sequence can represent. |
| 1414 | const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; |
| 1415 | |
| 1416 | // Chops off the n lowest bits from a bit pattern. Returns the n |
| 1417 | // lowest bits. As a side effect, the original bit pattern will be |
| 1418 | // shifted to the right by n bits. |
| 1419 | inline UInt32 ChopLowBits(UInt32* bits, int n) { |
| 1420 | const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); |
| 1421 | *bits >>= n; |
| 1422 | return low_bits; |
| 1423 | } |
| 1424 | |
| 1425 | // Converts a Unicode code point to a narrow string in UTF-8 encoding. |
| 1426 | // code_point parameter is of type UInt32 because wchar_t may not be |
| 1427 | // wide enough to contain a code point. |
| 1428 | // The output buffer str must containt at least 32 characters. |
| 1429 | // The function returns the address of the output buffer. |
| 1430 | // If the code_point is not a valid Unicode code point |
| 1431 | // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output |
| 1432 | // as '(Invalid Unicode 0xXXXXXXXX)'. |
| 1433 | char* CodePointToUtf8(UInt32 code_point, char* str) { |
| 1434 | if (code_point <= kMaxCodePoint1) { |
| 1435 | str[1] = '\0'; |
| 1436 | str[0] = static_cast<char>(code_point); // 0xxxxxxx |
| 1437 | } else if (code_point <= kMaxCodePoint2) { |
| 1438 | str[2] = '\0'; |
| 1439 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1440 | str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx |
| 1441 | } else if (code_point <= kMaxCodePoint3) { |
| 1442 | str[3] = '\0'; |
| 1443 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1444 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1445 | str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx |
| 1446 | } else if (code_point <= kMaxCodePoint4) { |
| 1447 | str[4] = '\0'; |
| 1448 | str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1449 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1450 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1451 | str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx |
| 1452 | } else { |
| 1453 | // The longest string String::Format can produce when invoked |
| 1454 | // with these parameters is 28 character long (not including |
| 1455 | // the terminating nul character). We are asking for 32 character |
| 1456 | // buffer just in case. This is also enough for strncpy to |
| 1457 | // null-terminate the destination string. |
| 1458 | // MSVC 8 deprecates strncpy(), so we want to suppress warning |
| 1459 | // 4996 (deprecated function) there. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1460 | #if GTEST_OS_WINDOWS // We are on Windows. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1461 | #pragma warning(push) // Saves the current warning state. |
| 1462 | #pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 1463 | #endif |
| 1464 | strncpy(str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), |
| 1465 | 32); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1466 | #if GTEST_OS_WINDOWS // We are on Windows. |
| 1467 | #pragma warning(pop) // Restores the warning state. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1468 | #endif |
| 1469 | str[31] = '\0'; // Makes sure no change in the format to strncpy leaves |
| 1470 | // the result unterminated. |
| 1471 | } |
| 1472 | return str; |
| 1473 | } |
| 1474 | |
| 1475 | // The following two functions only make sense if the the system |
| 1476 | // uses UTF-16 for wide string encoding. All supported systems |
| 1477 | // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. |
| 1478 | |
| 1479 | // Determines if the arguments constitute UTF-16 surrogate pair |
| 1480 | // and thus should be combined into a single Unicode code point |
| 1481 | // using CreateCodePointFromUtf16SurrogatePair. |
| 1482 | inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1483 | return sizeof(wchar_t) == 2 && |
| 1484 | (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1485 | } |
| 1486 | |
| 1487 | // Creates a Unicode code point from UTF16 surrogate pair. |
| 1488 | inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, |
| 1489 | wchar_t second) { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1490 | const UInt32 mask = (1 << 10) - 1; |
| 1491 | return (sizeof(wchar_t) == 2) ? |
| 1492 | (((first & mask) << 10) | (second & mask)) + 0x10000 : |
| 1493 | // This function should not be called when the condition is |
| 1494 | // false, but we provide a sensible default in case it is. |
| 1495 | static_cast<UInt32>(first); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1496 | } |
| 1497 | |
| 1498 | // Converts a wide string to a narrow string in UTF-8 encoding. |
| 1499 | // The wide string is assumed to have the following encoding: |
| 1500 | // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) |
| 1501 | // UTF-32 if sizeof(wchar_t) == 4 (on Linux) |
| 1502 | // Parameter str points to a null-terminated wide string. |
| 1503 | // Parameter num_chars may additionally limit the number |
| 1504 | // of wchar_t characters processed. -1 is used when the entire string |
| 1505 | // should be processed. |
| 1506 | // If the string contains code points that are not valid Unicode code points |
| 1507 | // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output |
| 1508 | // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding |
| 1509 | // and contains invalid UTF-16 surrogate pairs, values in those pairs |
| 1510 | // will be encoded as individual Unicode characters from Basic Normal Plane. |
| 1511 | String WideStringToUtf8(const wchar_t* str, int num_chars) { |
| 1512 | if (num_chars == -1) |
| 1513 | num_chars = static_cast<int>(wcslen(str)); |
| 1514 | |
| 1515 | StrStream stream; |
| 1516 | for (int i = 0; i < num_chars; ++i) { |
| 1517 | UInt32 unicode_code_point; |
| 1518 | |
| 1519 | if (str[i] == L'\0') { |
| 1520 | break; |
| 1521 | } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { |
| 1522 | unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], |
| 1523 | str[i + 1]); |
| 1524 | i++; |
| 1525 | } else { |
| 1526 | unicode_code_point = static_cast<UInt32>(str[i]); |
| 1527 | } |
| 1528 | |
| 1529 | char buffer[32]; // CodePointToUtf8 requires a buffer this big. |
| 1530 | stream << CodePointToUtf8(unicode_code_point, buffer); |
| 1531 | } |
| 1532 | return StrStreamToString(&stream); |
| 1533 | } |
| 1534 | |
| 1535 | // Converts a wide C string to a String using the UTF-8 encoding. |
| 1536 | // NULL will be converted to "(null)". |
| 1537 | String String::ShowWideCString(const wchar_t * wide_c_str) { |
| 1538 | if (wide_c_str == NULL) return String("(null)"); |
| 1539 | |
| 1540 | return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); |
| 1541 | } |
| 1542 | |
| 1543 | // Similar to ShowWideCString(), except that this function encloses |
| 1544 | // the converted string in double quotes. |
| 1545 | String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) { |
| 1546 | if (wide_c_str == NULL) return String("(null)"); |
| 1547 | |
| 1548 | return String::Format("L\"%s\"", |
| 1549 | String::ShowWideCString(wide_c_str).c_str()); |
| 1550 | } |
| 1551 | |
| 1552 | // Compares two wide C strings. Returns true iff they have the same |
| 1553 | // content. |
| 1554 | // |
| 1555 | // Unlike wcscmp(), this function can handle NULL argument(s). A NULL |
| 1556 | // C string is considered different to any non-NULL C string, |
| 1557 | // including the empty string. |
| 1558 | bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { |
| 1559 | if (lhs == NULL) return rhs == NULL; |
| 1560 | |
| 1561 | if (rhs == NULL) return false; |
| 1562 | |
| 1563 | return wcscmp(lhs, rhs) == 0; |
| 1564 | } |
| 1565 | |
| 1566 | // Helper function for *_STREQ on wide strings. |
| 1567 | AssertionResult CmpHelperSTREQ(const char* expected_expression, |
| 1568 | const char* actual_expression, |
| 1569 | const wchar_t* expected, |
| 1570 | const wchar_t* actual) { |
| 1571 | if (String::WideCStringEquals(expected, actual)) { |
| 1572 | return AssertionSuccess(); |
| 1573 | } |
| 1574 | |
| 1575 | return EqFailure(expected_expression, |
| 1576 | actual_expression, |
| 1577 | String::ShowWideCStringQuoted(expected), |
| 1578 | String::ShowWideCStringQuoted(actual), |
| 1579 | false); |
| 1580 | } |
| 1581 | |
| 1582 | // Helper function for *_STRNE on wide strings. |
| 1583 | AssertionResult CmpHelperSTRNE(const char* s1_expression, |
| 1584 | const char* s2_expression, |
| 1585 | const wchar_t* s1, |
| 1586 | const wchar_t* s2) { |
| 1587 | if (!String::WideCStringEquals(s1, s2)) { |
| 1588 | return AssertionSuccess(); |
| 1589 | } |
| 1590 | |
| 1591 | Message msg; |
| 1592 | msg << "Expected: (" << s1_expression << ") != (" |
| 1593 | << s2_expression << "), actual: " |
| 1594 | << String::ShowWideCStringQuoted(s1) |
| 1595 | << " vs " << String::ShowWideCStringQuoted(s2); |
| 1596 | return AssertionFailure(msg); |
| 1597 | } |
| 1598 | |
| 1599 | // Compares two C strings, ignoring case. Returns true iff they have |
| 1600 | // the same content. |
| 1601 | // |
| 1602 | // Unlike strcasecmp(), this function can handle NULL argument(s). A |
| 1603 | // NULL C string is considered different to any non-NULL C string, |
| 1604 | // including the empty string. |
| 1605 | bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { |
| 1606 | if ( lhs == NULL ) return rhs == NULL; |
| 1607 | |
| 1608 | if ( rhs == NULL ) return false; |
| 1609 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1610 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1611 | return _stricmp(lhs, rhs) == 0; |
| 1612 | #else // GTEST_OS_WINDOWS |
| 1613 | return strcasecmp(lhs, rhs) == 0; |
| 1614 | #endif // GTEST_OS_WINDOWS |
| 1615 | } |
| 1616 | |
| 1617 | // Compares two wide C strings, ignoring case. Returns true iff they |
| 1618 | // have the same content. |
| 1619 | // |
| 1620 | // Unlike wcscasecmp(), this function can handle NULL argument(s). |
| 1621 | // A NULL C string is considered different to any non-NULL wide C string, |
| 1622 | // including the empty string. |
| 1623 | // NB: The implementations on different platforms slightly differ. |
| 1624 | // On windows, this method uses _wcsicmp which compares according to LC_CTYPE |
| 1625 | // environment variable. On GNU platform this method uses wcscasecmp |
| 1626 | // which compares according to LC_CTYPE category of the current locale. |
| 1627 | // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the |
| 1628 | // current locale. |
| 1629 | bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, |
| 1630 | const wchar_t* rhs) { |
| 1631 | if ( lhs == NULL ) return rhs == NULL; |
| 1632 | |
| 1633 | if ( rhs == NULL ) return false; |
| 1634 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1635 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1636 | return _wcsicmp(lhs, rhs) == 0; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1637 | #elif GTEST_OS_LINUX |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1638 | return wcscasecmp(lhs, rhs) == 0; |
| 1639 | #else |
| 1640 | // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes |
| 1641 | // may not define it either. |
| 1642 | wint_t left, right; |
| 1643 | do { |
| 1644 | left = towlower(*lhs++); |
| 1645 | right = towlower(*rhs++); |
| 1646 | } while (left && left == right); |
| 1647 | return left == right; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1648 | #endif // OS selector |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1649 | } |
| 1650 | |
| 1651 | // Constructs a String by copying a given number of chars from a |
| 1652 | // buffer. E.g. String("hello", 3) will create the string "hel". |
| 1653 | String::String(const char * buffer, size_t len) { |
| 1654 | char * const temp = new char[ len + 1 ]; |
| 1655 | memcpy(temp, buffer, len); |
| 1656 | temp[ len ] = '\0'; |
| 1657 | c_str_ = temp; |
| 1658 | } |
| 1659 | |
| 1660 | // Compares this with another String. |
| 1661 | // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 |
| 1662 | // if this is greater than rhs. |
| 1663 | int String::Compare(const String & rhs) const { |
| 1664 | if ( c_str_ == NULL ) { |
| 1665 | return rhs.c_str_ == NULL ? 0 : -1; // NULL < anything except NULL |
| 1666 | } |
| 1667 | |
| 1668 | return rhs.c_str_ == NULL ? 1 : strcmp(c_str_, rhs.c_str_); |
| 1669 | } |
| 1670 | |
| 1671 | // Returns true iff this String ends with the given suffix. *Any* |
| 1672 | // String is considered to end with a NULL or empty suffix. |
| 1673 | bool String::EndsWith(const char* suffix) const { |
| 1674 | if (suffix == NULL || CStringEquals(suffix, "")) return true; |
| 1675 | |
| 1676 | if (c_str_ == NULL) return false; |
| 1677 | |
| 1678 | const size_t this_len = strlen(c_str_); |
| 1679 | const size_t suffix_len = strlen(suffix); |
| 1680 | return (this_len >= suffix_len) && |
| 1681 | CStringEquals(c_str_ + this_len - suffix_len, suffix); |
| 1682 | } |
| 1683 | |
| 1684 | // Returns true iff this String ends with the given suffix, ignoring case. |
| 1685 | // Any String is considered to end with a NULL or empty suffix. |
| 1686 | bool String::EndsWithCaseInsensitive(const char* suffix) const { |
| 1687 | if (suffix == NULL || CStringEquals(suffix, "")) return true; |
| 1688 | |
| 1689 | if (c_str_ == NULL) return false; |
| 1690 | |
| 1691 | const size_t this_len = strlen(c_str_); |
| 1692 | const size_t suffix_len = strlen(suffix); |
| 1693 | return (this_len >= suffix_len) && |
| 1694 | CaseInsensitiveCStringEquals(c_str_ + this_len - suffix_len, suffix); |
| 1695 | } |
| 1696 | |
| 1697 | // Sets the 0-terminated C string this String object represents. The |
| 1698 | // old string in this object is deleted, and this object will own a |
| 1699 | // clone of the input string. This function copies only up to length |
| 1700 | // bytes (plus a terminating null byte), or until the first null byte, |
| 1701 | // whichever comes first. |
| 1702 | // |
| 1703 | // This function works even when the c_str parameter has the same |
| 1704 | // value as that of the c_str_ field. |
| 1705 | void String::Set(const char * c_str, size_t length) { |
| 1706 | // Makes sure this works when c_str == c_str_ |
| 1707 | const char* const temp = CloneString(c_str, length); |
| 1708 | delete[] c_str_; |
| 1709 | c_str_ = temp; |
| 1710 | } |
| 1711 | |
| 1712 | // Assigns a C string to this object. Self-assignment works. |
| 1713 | const String& String::operator=(const char* c_str) { |
| 1714 | // Makes sure this works when c_str == c_str_ |
| 1715 | if (c_str != c_str_) { |
| 1716 | delete[] c_str_; |
| 1717 | c_str_ = CloneCString(c_str); |
| 1718 | } |
| 1719 | return *this; |
| 1720 | } |
| 1721 | |
| 1722 | // Formats a list of arguments to a String, using the same format |
| 1723 | // spec string as for printf. |
| 1724 | // |
| 1725 | // We do not use the StringPrintf class as it is not universally |
| 1726 | // available. |
| 1727 | // |
| 1728 | // The result is limited to 4096 characters (including the tailing 0). |
| 1729 | // If 4096 characters are not enough to format the input, |
| 1730 | // "<buffer exceeded>" is returned. |
| 1731 | String String::Format(const char * format, ...) { |
| 1732 | va_list args; |
| 1733 | va_start(args, format); |
| 1734 | |
| 1735 | char buffer[4096]; |
| 1736 | // MSVC 8 deprecates vsnprintf(), so we want to suppress warning |
| 1737 | // 4996 (deprecated function) there. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1738 | #if GTEST_OS_WINDOWS // We are on Windows. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1739 | #pragma warning(push) // Saves the current warning state. |
| 1740 | #pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 1741 | const int size = |
| 1742 | vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args); |
| 1743 | #pragma warning(pop) // Restores the warning state. |
| 1744 | #else // We are on Linux or Mac OS. |
| 1745 | const int size = |
| 1746 | vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args); |
| 1747 | #endif // GTEST_OS_WINDOWS |
| 1748 | va_end(args); |
| 1749 | |
| 1750 | return String(size >= 0 ? buffer : "<buffer exceeded>"); |
| 1751 | } |
| 1752 | |
| 1753 | // Converts the buffer in a StrStream to a String, converting NUL |
| 1754 | // bytes to "\\0" along the way. |
| 1755 | String StrStreamToString(StrStream* ss) { |
| 1756 | #if GTEST_HAS_STD_STRING |
| 1757 | const ::std::string& str = ss->str(); |
| 1758 | const char* const start = str.c_str(); |
| 1759 | const char* const end = start + str.length(); |
| 1760 | #else |
| 1761 | const char* const start = ss->str(); |
| 1762 | const char* const end = start + ss->pcount(); |
| 1763 | #endif // GTEST_HAS_STD_STRING |
| 1764 | |
| 1765 | // We need to use a helper StrStream to do this transformation |
| 1766 | // because String doesn't support push_back(). |
| 1767 | StrStream helper; |
| 1768 | for (const char* ch = start; ch != end; ++ch) { |
| 1769 | if (*ch == '\0') { |
| 1770 | helper << "\\0"; // Replaces NUL with "\\0"; |
| 1771 | } else { |
| 1772 | helper.put(*ch); |
| 1773 | } |
| 1774 | } |
| 1775 | |
| 1776 | #if GTEST_HAS_STD_STRING |
| 1777 | return String(helper.str().c_str()); |
| 1778 | #else |
| 1779 | const String str(helper.str(), helper.pcount()); |
| 1780 | helper.freeze(false); |
| 1781 | ss->freeze(false); |
| 1782 | return str; |
| 1783 | #endif // GTEST_HAS_STD_STRING |
| 1784 | } |
| 1785 | |
| 1786 | // Appends the user-supplied message to the Google-Test-generated message. |
| 1787 | String AppendUserMessage(const String& gtest_msg, |
| 1788 | const Message& user_msg) { |
| 1789 | // Appends the user message if it's non-empty. |
| 1790 | const String user_msg_string = user_msg.GetString(); |
| 1791 | if (user_msg_string.empty()) { |
| 1792 | return gtest_msg; |
| 1793 | } |
| 1794 | |
| 1795 | Message msg; |
| 1796 | msg << gtest_msg << "\n" << user_msg_string; |
| 1797 | |
| 1798 | return msg.GetString(); |
| 1799 | } |
| 1800 | |
| 1801 | // class TestResult |
| 1802 | |
| 1803 | // Creates an empty TestResult. |
| 1804 | TestResult::TestResult() |
| 1805 | : death_test_count_(0), |
| 1806 | elapsed_time_(0) { |
| 1807 | } |
| 1808 | |
| 1809 | // D'tor. |
| 1810 | TestResult::~TestResult() { |
| 1811 | } |
| 1812 | |
| 1813 | // Adds a test part result to the list. |
| 1814 | void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { |
| 1815 | test_part_results_.PushBack(test_part_result); |
| 1816 | } |
| 1817 | |
| 1818 | // Adds a test property to the list. If a property with the same key as the |
| 1819 | // supplied property is already represented, the value of this test_property |
| 1820 | // replaces the old value for that key. |
| 1821 | void TestResult::RecordProperty(const TestProperty& test_property) { |
| 1822 | if (!ValidateTestProperty(test_property)) { |
| 1823 | return; |
| 1824 | } |
| 1825 | MutexLock lock(&test_properites_mutex_); |
| 1826 | ListNode<TestProperty>* const node_with_matching_key = |
| 1827 | test_properties_.FindIf(TestPropertyKeyIs(test_property.key())); |
| 1828 | if (node_with_matching_key == NULL) { |
| 1829 | test_properties_.PushBack(test_property); |
| 1830 | return; |
| 1831 | } |
| 1832 | TestProperty& property_with_matching_key = node_with_matching_key->element(); |
| 1833 | property_with_matching_key.SetValue(test_property.value()); |
| 1834 | } |
| 1835 | |
| 1836 | // Adds a failure if the key is a reserved attribute of Google Test |
| 1837 | // testcase tags. Returns true if the property is valid. |
| 1838 | bool TestResult::ValidateTestProperty(const TestProperty& test_property) { |
| 1839 | String key(test_property.key()); |
| 1840 | if (key == "name" || key == "status" || key == "time" || key == "classname") { |
| 1841 | ADD_FAILURE() |
| 1842 | << "Reserved key used in RecordProperty(): " |
| 1843 | << key |
| 1844 | << " ('name', 'status', 'time', and 'classname' are reserved by " |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1845 | << GTEST_NAME_ << ")"; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1846 | return false; |
| 1847 | } |
| 1848 | return true; |
| 1849 | } |
| 1850 | |
| 1851 | // Clears the object. |
| 1852 | void TestResult::Clear() { |
| 1853 | test_part_results_.Clear(); |
| 1854 | test_properties_.Clear(); |
| 1855 | death_test_count_ = 0; |
| 1856 | elapsed_time_ = 0; |
| 1857 | } |
| 1858 | |
| 1859 | // Returns true iff the test part passed. |
| 1860 | static bool TestPartPassed(const TestPartResult & result) { |
| 1861 | return result.passed(); |
| 1862 | } |
| 1863 | |
| 1864 | // Gets the number of successful test parts. |
| 1865 | int TestResult::successful_part_count() const { |
| 1866 | return test_part_results_.CountIf(TestPartPassed); |
| 1867 | } |
| 1868 | |
| 1869 | // Returns true iff the test part failed. |
| 1870 | static bool TestPartFailed(const TestPartResult & result) { |
| 1871 | return result.failed(); |
| 1872 | } |
| 1873 | |
| 1874 | // Gets the number of failed test parts. |
| 1875 | int TestResult::failed_part_count() const { |
| 1876 | return test_part_results_.CountIf(TestPartFailed); |
| 1877 | } |
| 1878 | |
| 1879 | // Returns true iff the test part fatally failed. |
| 1880 | static bool TestPartFatallyFailed(const TestPartResult & result) { |
| 1881 | return result.fatally_failed(); |
| 1882 | } |
| 1883 | |
| 1884 | // Returns true iff the test fatally failed. |
| 1885 | bool TestResult::HasFatalFailure() const { |
| 1886 | return test_part_results_.CountIf(TestPartFatallyFailed) > 0; |
| 1887 | } |
| 1888 | |
| 1889 | // Gets the number of all test parts. This is the sum of the number |
| 1890 | // of successful test parts and the number of failed test parts. |
| 1891 | int TestResult::total_part_count() const { |
| 1892 | return test_part_results_.size(); |
| 1893 | } |
| 1894 | |
| 1895 | } // namespace internal |
| 1896 | |
| 1897 | // class Test |
| 1898 | |
| 1899 | // Creates a Test object. |
| 1900 | |
| 1901 | // The c'tor saves the values of all Google Test flags. |
| 1902 | Test::Test() |
| 1903 | : gtest_flag_saver_(new internal::GTestFlagSaver) { |
| 1904 | } |
| 1905 | |
| 1906 | // The d'tor restores the values of all Google Test flags. |
| 1907 | Test::~Test() { |
| 1908 | delete gtest_flag_saver_; |
| 1909 | } |
| 1910 | |
| 1911 | // Sets up the test fixture. |
| 1912 | // |
| 1913 | // A sub-class may override this. |
| 1914 | void Test::SetUp() { |
| 1915 | } |
| 1916 | |
| 1917 | // Tears down the test fixture. |
| 1918 | // |
| 1919 | // A sub-class may override this. |
| 1920 | void Test::TearDown() { |
| 1921 | } |
| 1922 | |
| 1923 | // Allows user supplied key value pairs to be recorded for later output. |
| 1924 | void Test::RecordProperty(const char* key, const char* value) { |
| 1925 | UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); |
| 1926 | } |
| 1927 | |
| 1928 | // Allows user supplied key value pairs to be recorded for later output. |
| 1929 | void Test::RecordProperty(const char* key, int value) { |
| 1930 | Message value_message; |
| 1931 | value_message << value; |
| 1932 | RecordProperty(key, value_message.GetString().c_str()); |
| 1933 | } |
| 1934 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 1935 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 1936 | // We are on Windows. |
| 1937 | |
| 1938 | // Adds an "exception thrown" fatal failure to the current test. |
| 1939 | static void AddExceptionThrownFailure(DWORD exception_code, |
| 1940 | const char* location) { |
| 1941 | Message message; |
| 1942 | message << "Exception thrown with code 0x" << std::setbase(16) << |
| 1943 | exception_code << std::setbase(10) << " in " << location << "."; |
| 1944 | |
| 1945 | UnitTest* const unit_test = UnitTest::GetInstance(); |
| 1946 | unit_test->AddTestPartResult( |
| 1947 | TPRT_FATAL_FAILURE, |
| 1948 | static_cast<const char *>(NULL), |
| 1949 | // We have no info about the source file where the exception |
| 1950 | // occurred. |
| 1951 | -1, // We have no info on which line caused the exception. |
| 1952 | message.GetString(), |
| 1953 | internal::String("")); |
| 1954 | } |
| 1955 | |
| 1956 | #endif // GTEST_OS_WINDOWS |
| 1957 | |
| 1958 | // Google Test requires all tests in the same test case to use the same test |
| 1959 | // fixture class. This function checks if the current test has the |
| 1960 | // same fixture class as the first test in the current test case. If |
| 1961 | // yes, it returns true; otherwise it generates a Google Test failure and |
| 1962 | // returns false. |
| 1963 | bool Test::HasSameFixtureClass() { |
| 1964 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 1965 | const TestCase* const test_case = impl->current_test_case(); |
| 1966 | |
| 1967 | // Info about the first test in the current test case. |
| 1968 | const internal::TestInfoImpl* const first_test_info = |
| 1969 | test_case->test_info_list().Head()->element()->impl(); |
| 1970 | const internal::TypeId first_fixture_id = first_test_info->fixture_class_id(); |
| 1971 | const char* const first_test_name = first_test_info->name(); |
| 1972 | |
| 1973 | // Info about the current test. |
| 1974 | const internal::TestInfoImpl* const this_test_info = |
| 1975 | impl->current_test_info()->impl(); |
| 1976 | const internal::TypeId this_fixture_id = this_test_info->fixture_class_id(); |
| 1977 | const char* const this_test_name = this_test_info->name(); |
| 1978 | |
| 1979 | if (this_fixture_id != first_fixture_id) { |
| 1980 | // Is the first test defined using TEST? |
| 1981 | const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); |
| 1982 | // Is this test defined using TEST? |
| 1983 | const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); |
| 1984 | |
| 1985 | if (first_is_TEST || this_is_TEST) { |
| 1986 | // The user mixed TEST and TEST_F in this test case - we'll tell |
| 1987 | // him/her how to fix it. |
| 1988 | |
| 1989 | // Gets the name of the TEST and the name of the TEST_F. Note |
| 1990 | // that first_is_TEST and this_is_TEST cannot both be true, as |
| 1991 | // the fixture IDs are different for the two tests. |
| 1992 | const char* const TEST_name = |
| 1993 | first_is_TEST ? first_test_name : this_test_name; |
| 1994 | const char* const TEST_F_name = |
| 1995 | first_is_TEST ? this_test_name : first_test_name; |
| 1996 | |
| 1997 | ADD_FAILURE() |
| 1998 | << "All tests in the same test case must use the same test fixture\n" |
| 1999 | << "class, so mixing TEST_F and TEST in the same test case is\n" |
| 2000 | << "illegal. In test case " << this_test_info->test_case_name() |
| 2001 | << ",\n" |
| 2002 | << "test " << TEST_F_name << " is defined using TEST_F but\n" |
| 2003 | << "test " << TEST_name << " is defined using TEST. You probably\n" |
| 2004 | << "want to change the TEST to TEST_F or move it to another test\n" |
| 2005 | << "case."; |
| 2006 | } else { |
| 2007 | // The user defined two fixture classes with the same name in |
| 2008 | // two namespaces - we'll tell him/her how to fix it. |
| 2009 | ADD_FAILURE() |
| 2010 | << "All tests in the same test case must use the same test fixture\n" |
| 2011 | << "class. However, in test case " |
| 2012 | << this_test_info->test_case_name() << ",\n" |
| 2013 | << "you defined test " << first_test_name |
| 2014 | << " and test " << this_test_name << "\n" |
| 2015 | << "using two different test fixture classes. This can happen if\n" |
| 2016 | << "the two classes are from different namespaces or translation\n" |
| 2017 | << "units and have the same name. You should probably rename one\n" |
| 2018 | << "of the classes to put the tests into different test cases."; |
| 2019 | } |
| 2020 | return false; |
| 2021 | } |
| 2022 | |
| 2023 | return true; |
| 2024 | } |
| 2025 | |
| 2026 | // Runs the test and updates the test result. |
| 2027 | void Test::Run() { |
| 2028 | if (!HasSameFixtureClass()) return; |
| 2029 | |
| 2030 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2031 | #if GTEST_OS_WINDOWS && !defined(__MINGW32__) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2032 | // We are on Windows. |
| 2033 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2034 | __try { |
| 2035 | SetUp(); |
| 2036 | } __except(internal::UnitTestOptions::GTestShouldProcessSEH( |
| 2037 | GetExceptionCode())) { |
| 2038 | AddExceptionThrownFailure(GetExceptionCode(), "SetUp()"); |
| 2039 | } |
| 2040 | |
| 2041 | // We will run the test only if SetUp() had no fatal failure. |
| 2042 | if (!HasFatalFailure()) { |
| 2043 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2044 | __try { |
| 2045 | TestBody(); |
| 2046 | } __except(internal::UnitTestOptions::GTestShouldProcessSEH( |
| 2047 | GetExceptionCode())) { |
| 2048 | AddExceptionThrownFailure(GetExceptionCode(), "the test body"); |
| 2049 | } |
| 2050 | } |
| 2051 | |
| 2052 | // However, we want to clean up as much as possible. Hence we will |
| 2053 | // always call TearDown(), even if SetUp() or the test body has |
| 2054 | // failed. |
| 2055 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2056 | __try { |
| 2057 | TearDown(); |
| 2058 | } __except(internal::UnitTestOptions::GTestShouldProcessSEH( |
| 2059 | GetExceptionCode())) { |
| 2060 | AddExceptionThrownFailure(GetExceptionCode(), "TearDown()"); |
| 2061 | } |
| 2062 | |
Julien Lerouge | e0a056b | 2009-02-12 08:02:35 +0000 | [diff] [blame] | 2063 | #else // We are on Linux, Mac or MingW - exceptions are disabled. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2064 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2065 | SetUp(); |
| 2066 | |
| 2067 | // We will run the test only if SetUp() was successful. |
| 2068 | if (!HasFatalFailure()) { |
| 2069 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2070 | TestBody(); |
| 2071 | } |
| 2072 | |
| 2073 | // However, we want to clean up as much as possible. Hence we will |
| 2074 | // always call TearDown(), even if SetUp() or the test body has |
| 2075 | // failed. |
| 2076 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2077 | TearDown(); |
| 2078 | #endif // GTEST_OS_WINDOWS |
| 2079 | } |
| 2080 | |
| 2081 | |
| 2082 | // Returns true iff the current test has a fatal failure. |
| 2083 | bool Test::HasFatalFailure() { |
| 2084 | return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); |
| 2085 | } |
| 2086 | |
| 2087 | // class TestInfo |
| 2088 | |
| 2089 | // Constructs a TestInfo object. It assumes ownership of the test factory |
| 2090 | // object via impl_. |
| 2091 | TestInfo::TestInfo(const char* test_case_name, |
| 2092 | const char* name, |
| 2093 | const char* test_case_comment, |
| 2094 | const char* comment, |
| 2095 | internal::TypeId fixture_class_id, |
| 2096 | internal::TestFactoryBase* factory) { |
| 2097 | impl_ = new internal::TestInfoImpl(this, test_case_name, name, |
| 2098 | test_case_comment, comment, |
| 2099 | fixture_class_id, factory); |
| 2100 | } |
| 2101 | |
| 2102 | // Destructs a TestInfo object. |
| 2103 | TestInfo::~TestInfo() { |
| 2104 | delete impl_; |
| 2105 | } |
| 2106 | |
| 2107 | namespace internal { |
| 2108 | |
| 2109 | // Creates a new TestInfo object and registers it with Google Test; |
| 2110 | // returns the created object. |
| 2111 | // |
| 2112 | // Arguments: |
| 2113 | // |
| 2114 | // test_case_name: name of the test case |
| 2115 | // name: name of the test |
| 2116 | // test_case_comment: a comment on the test case that will be included in |
| 2117 | // the test output |
| 2118 | // comment: a comment on the test that will be included in the |
| 2119 | // test output |
| 2120 | // fixture_class_id: ID of the test fixture class |
| 2121 | // set_up_tc: pointer to the function that sets up the test case |
| 2122 | // tear_down_tc: pointer to the function that tears down the test case |
| 2123 | // factory: pointer to the factory that creates a test object. |
| 2124 | // The newly created TestInfo instance will assume |
| 2125 | // ownership of the factory object. |
| 2126 | TestInfo* MakeAndRegisterTestInfo( |
| 2127 | const char* test_case_name, const char* name, |
| 2128 | const char* test_case_comment, const char* comment, |
| 2129 | TypeId fixture_class_id, |
| 2130 | SetUpTestCaseFunc set_up_tc, |
| 2131 | TearDownTestCaseFunc tear_down_tc, |
| 2132 | TestFactoryBase* factory) { |
| 2133 | TestInfo* const test_info = |
| 2134 | new TestInfo(test_case_name, name, test_case_comment, comment, |
| 2135 | fixture_class_id, factory); |
| 2136 | GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); |
| 2137 | return test_info; |
| 2138 | } |
| 2139 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2140 | #if GTEST_HAS_PARAM_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2141 | void ReportInvalidTestCaseType(const char* test_case_name, |
| 2142 | const char* file, int line) { |
| 2143 | Message errors; |
| 2144 | errors |
| 2145 | << "Attempted redefinition of test case " << test_case_name << ".\n" |
| 2146 | << "All tests in the same test case must use the same test fixture\n" |
| 2147 | << "class. However, in test case " << test_case_name << ", you tried\n" |
| 2148 | << "to define a test using a fixture class different from the one\n" |
| 2149 | << "used earlier. This can happen if the two fixture classes are\n" |
| 2150 | << "from different namespaces and have the same name. You should\n" |
| 2151 | << "probably rename one of the classes to put the tests into different\n" |
| 2152 | << "test cases."; |
| 2153 | |
| 2154 | fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), |
| 2155 | errors.GetString().c_str()); |
| 2156 | } |
| 2157 | #endif // GTEST_HAS_PARAM_TEST |
| 2158 | |
| 2159 | } // namespace internal |
| 2160 | |
| 2161 | // Returns the test case name. |
| 2162 | const char* TestInfo::test_case_name() const { |
| 2163 | return impl_->test_case_name(); |
| 2164 | } |
| 2165 | |
| 2166 | // Returns the test name. |
| 2167 | const char* TestInfo::name() const { |
| 2168 | return impl_->name(); |
| 2169 | } |
| 2170 | |
| 2171 | // Returns the test case comment. |
| 2172 | const char* TestInfo::test_case_comment() const { |
| 2173 | return impl_->test_case_comment(); |
| 2174 | } |
| 2175 | |
| 2176 | // Returns the test comment. |
| 2177 | const char* TestInfo::comment() const { |
| 2178 | return impl_->comment(); |
| 2179 | } |
| 2180 | |
| 2181 | // Returns true if this test should run. |
| 2182 | bool TestInfo::should_run() const { return impl_->should_run(); } |
| 2183 | |
| 2184 | // Returns the result of the test. |
| 2185 | const internal::TestResult* TestInfo::result() const { return impl_->result(); } |
| 2186 | |
| 2187 | // Increments the number of death tests encountered in this test so |
| 2188 | // far. |
| 2189 | int TestInfo::increment_death_test_count() { |
| 2190 | return impl_->result()->increment_death_test_count(); |
| 2191 | } |
| 2192 | |
| 2193 | namespace { |
| 2194 | |
| 2195 | // A predicate that checks the test name of a TestInfo against a known |
| 2196 | // value. |
| 2197 | // |
| 2198 | // This is used for implementation of the TestCase class only. We put |
| 2199 | // it in the anonymous namespace to prevent polluting the outer |
| 2200 | // namespace. |
| 2201 | // |
| 2202 | // TestNameIs is copyable. |
| 2203 | class TestNameIs { |
| 2204 | public: |
| 2205 | // Constructor. |
| 2206 | // |
| 2207 | // TestNameIs has NO default constructor. |
| 2208 | explicit TestNameIs(const char* name) |
| 2209 | : name_(name) {} |
| 2210 | |
| 2211 | // Returns true iff the test name of test_info matches name_. |
| 2212 | bool operator()(const TestInfo * test_info) const { |
| 2213 | return test_info && internal::String(test_info->name()).Compare(name_) == 0; |
| 2214 | } |
| 2215 | |
| 2216 | private: |
| 2217 | internal::String name_; |
| 2218 | }; |
| 2219 | |
| 2220 | } // namespace |
| 2221 | |
| 2222 | // Finds and returns a TestInfo with the given name. If one doesn't |
| 2223 | // exist, returns NULL. |
| 2224 | TestInfo * TestCase::GetTestInfo(const char* test_name) { |
| 2225 | // Can we find a TestInfo with the given name? |
| 2226 | internal::ListNode<TestInfo *> * const node = test_info_list_->FindIf( |
| 2227 | TestNameIs(test_name)); |
| 2228 | |
| 2229 | // Returns the TestInfo found. |
| 2230 | return node ? node->element() : NULL; |
| 2231 | } |
| 2232 | |
| 2233 | namespace internal { |
| 2234 | |
| 2235 | // This method expands all parameterized tests registered with macros TEST_P |
| 2236 | // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. |
| 2237 | // This will be done just once during the program runtime. |
| 2238 | void UnitTestImpl::RegisterParameterizedTests() { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2239 | #if GTEST_HAS_PARAM_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2240 | if (!parameterized_tests_registered_) { |
| 2241 | parameterized_test_registry_.RegisterTests(); |
| 2242 | parameterized_tests_registered_ = true; |
| 2243 | } |
| 2244 | #endif |
| 2245 | } |
| 2246 | |
| 2247 | // Creates the test object, runs it, records its result, and then |
| 2248 | // deletes it. |
| 2249 | void TestInfoImpl::Run() { |
| 2250 | if (!should_run_) return; |
| 2251 | |
| 2252 | // Tells UnitTest where to store test result. |
| 2253 | UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 2254 | impl->set_current_test_info(parent_); |
| 2255 | |
| 2256 | // Notifies the unit test event listener that a test is about to |
| 2257 | // start. |
| 2258 | UnitTestEventListenerInterface* const result_printer = |
| 2259 | impl->result_printer(); |
| 2260 | result_printer->OnTestStart(parent_); |
| 2261 | |
| 2262 | const TimeInMillis start = GetTimeInMillis(); |
| 2263 | |
| 2264 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2265 | #if GTEST_OS_WINDOWS && !defined(__MINGW32__) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2266 | // We are on Windows. |
| 2267 | Test* test = NULL; |
| 2268 | |
| 2269 | __try { |
| 2270 | // Creates the test object. |
| 2271 | test = factory_->CreateTest(); |
| 2272 | } __except(internal::UnitTestOptions::GTestShouldProcessSEH( |
| 2273 | GetExceptionCode())) { |
| 2274 | AddExceptionThrownFailure(GetExceptionCode(), |
| 2275 | "the test fixture's constructor"); |
| 2276 | return; |
| 2277 | } |
Julien Lerouge | e0a056b | 2009-02-12 08:02:35 +0000 | [diff] [blame] | 2278 | #else // We are on Linux, Mac OS or MingW - exceptions are disabled. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2279 | |
| 2280 | // TODO(wan): If test->Run() throws, test won't be deleted. This is |
| 2281 | // not a problem now as we don't use exceptions. If we were to |
| 2282 | // enable exceptions, we should revise the following to be |
| 2283 | // exception-safe. |
| 2284 | |
| 2285 | // Creates the test object. |
| 2286 | Test* test = factory_->CreateTest(); |
| 2287 | #endif // GTEST_OS_WINDOWS |
| 2288 | |
| 2289 | // Runs the test only if the constructor of the test fixture didn't |
| 2290 | // generate a fatal failure. |
| 2291 | if (!Test::HasFatalFailure()) { |
| 2292 | test->Run(); |
| 2293 | } |
| 2294 | |
| 2295 | // Deletes the test object. |
| 2296 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2297 | delete test; |
| 2298 | test = NULL; |
| 2299 | |
| 2300 | result_.set_elapsed_time(GetTimeInMillis() - start); |
| 2301 | |
| 2302 | // Notifies the unit test event listener that a test has just finished. |
| 2303 | result_printer->OnTestEnd(parent_); |
| 2304 | |
| 2305 | // Tells UnitTest to stop associating assertion results to this |
| 2306 | // test. |
| 2307 | impl->set_current_test_info(NULL); |
| 2308 | } |
| 2309 | |
| 2310 | } // namespace internal |
| 2311 | |
| 2312 | // class TestCase |
| 2313 | |
| 2314 | // Gets the number of successful tests in this test case. |
| 2315 | int TestCase::successful_test_count() const { |
| 2316 | return test_info_list_->CountIf(TestPassed); |
| 2317 | } |
| 2318 | |
| 2319 | // Gets the number of failed tests in this test case. |
| 2320 | int TestCase::failed_test_count() const { |
| 2321 | return test_info_list_->CountIf(TestFailed); |
| 2322 | } |
| 2323 | |
| 2324 | int TestCase::disabled_test_count() const { |
| 2325 | return test_info_list_->CountIf(TestDisabled); |
| 2326 | } |
| 2327 | |
| 2328 | // Get the number of tests in this test case that should run. |
| 2329 | int TestCase::test_to_run_count() const { |
| 2330 | return test_info_list_->CountIf(ShouldRunTest); |
| 2331 | } |
| 2332 | |
| 2333 | // Gets the number of all tests. |
| 2334 | int TestCase::total_test_count() const { |
| 2335 | return test_info_list_->size(); |
| 2336 | } |
| 2337 | |
| 2338 | // Creates a TestCase with the given name. |
| 2339 | // |
| 2340 | // Arguments: |
| 2341 | // |
| 2342 | // name: name of the test case |
| 2343 | // set_up_tc: pointer to the function that sets up the test case |
| 2344 | // tear_down_tc: pointer to the function that tears down the test case |
| 2345 | TestCase::TestCase(const char* name, const char* comment, |
| 2346 | Test::SetUpTestCaseFunc set_up_tc, |
| 2347 | Test::TearDownTestCaseFunc tear_down_tc) |
| 2348 | : name_(name), |
| 2349 | comment_(comment), |
| 2350 | set_up_tc_(set_up_tc), |
| 2351 | tear_down_tc_(tear_down_tc), |
| 2352 | should_run_(false), |
| 2353 | elapsed_time_(0) { |
| 2354 | test_info_list_ = new internal::List<TestInfo *>; |
| 2355 | } |
| 2356 | |
| 2357 | // Destructor of TestCase. |
| 2358 | TestCase::~TestCase() { |
| 2359 | // Deletes every Test in the collection. |
| 2360 | test_info_list_->ForEach(internal::Delete<TestInfo>); |
| 2361 | |
| 2362 | // Then deletes the Test collection. |
| 2363 | delete test_info_list_; |
| 2364 | test_info_list_ = NULL; |
| 2365 | } |
| 2366 | |
| 2367 | // Adds a test to this test case. Will delete the test upon |
| 2368 | // destruction of the TestCase object. |
| 2369 | void TestCase::AddTestInfo(TestInfo * test_info) { |
| 2370 | test_info_list_->PushBack(test_info); |
| 2371 | } |
| 2372 | |
| 2373 | // Runs every test in this TestCase. |
| 2374 | void TestCase::Run() { |
| 2375 | if (!should_run_) return; |
| 2376 | |
| 2377 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 2378 | impl->set_current_test_case(this); |
| 2379 | |
| 2380 | UnitTestEventListenerInterface * const result_printer = |
| 2381 | impl->result_printer(); |
| 2382 | |
| 2383 | result_printer->OnTestCaseStart(this); |
| 2384 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2385 | set_up_tc_(); |
| 2386 | |
| 2387 | const internal::TimeInMillis start = internal::GetTimeInMillis(); |
| 2388 | test_info_list_->ForEach(internal::TestInfoImpl::RunTest); |
| 2389 | elapsed_time_ = internal::GetTimeInMillis() - start; |
| 2390 | |
| 2391 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2392 | tear_down_tc_(); |
| 2393 | result_printer->OnTestCaseEnd(this); |
| 2394 | impl->set_current_test_case(NULL); |
| 2395 | } |
| 2396 | |
| 2397 | // Clears the results of all tests in this test case. |
| 2398 | void TestCase::ClearResult() { |
| 2399 | test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult); |
| 2400 | } |
| 2401 | |
| 2402 | |
| 2403 | // class UnitTestEventListenerInterface |
| 2404 | |
| 2405 | // The virtual d'tor. |
| 2406 | UnitTestEventListenerInterface::~UnitTestEventListenerInterface() { |
| 2407 | } |
| 2408 | |
| 2409 | // A result printer that never prints anything. Used in the child process |
| 2410 | // of an exec-style death test to avoid needless output clutter. |
| 2411 | class NullUnitTestResultPrinter : public UnitTestEventListenerInterface {}; |
| 2412 | |
| 2413 | // Formats a countable noun. Depending on its quantity, either the |
| 2414 | // singular form or the plural form is used. e.g. |
| 2415 | // |
| 2416 | // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". |
| 2417 | // FormatCountableNoun(5, "book", "books") returns "5 books". |
| 2418 | static internal::String FormatCountableNoun(int count, |
| 2419 | const char * singular_form, |
| 2420 | const char * plural_form) { |
| 2421 | return internal::String::Format("%d %s", count, |
| 2422 | count == 1 ? singular_form : plural_form); |
| 2423 | } |
| 2424 | |
| 2425 | // Formats the count of tests. |
| 2426 | static internal::String FormatTestCount(int test_count) { |
| 2427 | return FormatCountableNoun(test_count, "test", "tests"); |
| 2428 | } |
| 2429 | |
| 2430 | // Formats the count of test cases. |
| 2431 | static internal::String FormatTestCaseCount(int test_case_count) { |
| 2432 | return FormatCountableNoun(test_case_count, "test case", "test cases"); |
| 2433 | } |
| 2434 | |
| 2435 | // Converts a TestPartResultType enum to human-friendly string |
| 2436 | // representation. Both TPRT_NONFATAL_FAILURE and TPRT_FATAL_FAILURE |
| 2437 | // are translated to "Failure", as the user usually doesn't care about |
| 2438 | // the difference between the two when viewing the test result. |
| 2439 | static const char * TestPartResultTypeToString(TestPartResultType type) { |
| 2440 | switch (type) { |
| 2441 | case TPRT_SUCCESS: |
| 2442 | return "Success"; |
| 2443 | |
| 2444 | case TPRT_NONFATAL_FAILURE: |
| 2445 | case TPRT_FATAL_FAILURE: |
| 2446 | #ifdef _MSC_VER |
| 2447 | return "error: "; |
| 2448 | #else |
| 2449 | return "Failure\n"; |
| 2450 | #endif |
| 2451 | } |
| 2452 | |
| 2453 | return "Unknown result type"; |
| 2454 | } |
| 2455 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2456 | // Prints a TestPartResult to a String. |
| 2457 | static internal::String PrintTestPartResultToString( |
| 2458 | const TestPartResult& test_part_result) { |
| 2459 | return (Message() |
| 2460 | << internal::FormatFileLocation(test_part_result.file_name(), |
| 2461 | test_part_result.line_number()) |
| 2462 | << " " << TestPartResultTypeToString(test_part_result.type()) |
| 2463 | << test_part_result.message()).GetString(); |
| 2464 | } |
| 2465 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2466 | // Prints a TestPartResult. |
| 2467 | static void PrintTestPartResult( |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2468 | const TestPartResult& test_part_result) { |
| 2469 | printf("%s\n", PrintTestPartResultToString(test_part_result).c_str()); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2470 | fflush(stdout); |
| 2471 | } |
| 2472 | |
| 2473 | // class PrettyUnitTestResultPrinter |
| 2474 | |
| 2475 | namespace internal { |
| 2476 | |
| 2477 | enum GTestColor { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2478 | COLOR_DEFAULT, |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2479 | COLOR_RED, |
| 2480 | COLOR_GREEN, |
| 2481 | COLOR_YELLOW |
| 2482 | }; |
| 2483 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2484 | #if GTEST_OS_WINDOWS && !defined(_WIN32_WCE) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2485 | |
| 2486 | // Returns the character attribute for the given color. |
| 2487 | WORD GetColorAttribute(GTestColor color) { |
| 2488 | switch (color) { |
| 2489 | case COLOR_RED: return FOREGROUND_RED; |
| 2490 | case COLOR_GREEN: return FOREGROUND_GREEN; |
| 2491 | case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2492 | default: return 0; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2493 | } |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2494 | } |
| 2495 | |
| 2496 | #else |
| 2497 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2498 | // Returns the ANSI color code for the given color. COLOR_DEFAULT is |
| 2499 | // an invalid input. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2500 | const char* GetAnsiColorCode(GTestColor color) { |
| 2501 | switch (color) { |
| 2502 | case COLOR_RED: return "1"; |
| 2503 | case COLOR_GREEN: return "2"; |
| 2504 | case COLOR_YELLOW: return "3"; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2505 | default: return NULL; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2506 | }; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2507 | } |
| 2508 | |
| 2509 | #endif // GTEST_OS_WINDOWS && !_WIN32_WCE |
| 2510 | |
| 2511 | // Returns true iff Google Test should use colors in the output. |
| 2512 | bool ShouldUseColor(bool stdout_is_tty) { |
| 2513 | const char* const gtest_color = GTEST_FLAG(color).c_str(); |
| 2514 | |
| 2515 | if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2516 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2517 | // On Windows the TERM variable is usually not set, but the |
| 2518 | // console there does support colors. |
| 2519 | return stdout_is_tty; |
| 2520 | #else |
| 2521 | // On non-Windows platforms, we rely on the TERM variable. |
| 2522 | const char* const term = GetEnv("TERM"); |
| 2523 | const bool term_supports_color = |
| 2524 | String::CStringEquals(term, "xterm") || |
| 2525 | String::CStringEquals(term, "xterm-color") || |
| 2526 | String::CStringEquals(term, "cygwin"); |
| 2527 | return stdout_is_tty && term_supports_color; |
| 2528 | #endif // GTEST_OS_WINDOWS |
| 2529 | } |
| 2530 | |
| 2531 | return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || |
| 2532 | String::CaseInsensitiveCStringEquals(gtest_color, "true") || |
| 2533 | String::CaseInsensitiveCStringEquals(gtest_color, "t") || |
| 2534 | String::CStringEquals(gtest_color, "1"); |
| 2535 | // We take "yes", "true", "t", and "1" as meaning "yes". If the |
| 2536 | // value is neither one of these nor "auto", we treat it as "no" to |
| 2537 | // be conservative. |
| 2538 | } |
| 2539 | |
| 2540 | // Helpers for printing colored strings to stdout. Note that on Windows, we |
| 2541 | // cannot simply emit special characters and have the terminal change colors. |
| 2542 | // This routine must actually emit the characters rather than return a string |
| 2543 | // that would be colored when printed, as can be done on Linux. |
| 2544 | void ColoredPrintf(GTestColor color, const char* fmt, ...) { |
| 2545 | va_list args; |
| 2546 | va_start(args, fmt); |
| 2547 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2548 | #if defined(_WIN32_WCE) || GTEST_OS_SYMBIAN || GTEST_OS_ZOS |
| 2549 | const bool use_color = false; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2550 | #else |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2551 | static const bool in_color_mode = |
| 2552 | ShouldUseColor(isatty(fileno(stdout)) != 0); |
| 2553 | const bool use_color = in_color_mode && (color != COLOR_DEFAULT); |
| 2554 | #endif // defined(_WIN32_WCE) || GTEST_OS_SYMBIAN || GTEST_OS_ZOS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2555 | // The '!= 0' comparison is necessary to satisfy MSVC 7.1. |
| 2556 | |
| 2557 | if (!use_color) { |
| 2558 | vprintf(fmt, args); |
| 2559 | va_end(args); |
| 2560 | return; |
| 2561 | } |
| 2562 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2563 | #if GTEST_OS_WINDOWS && !defined(_WIN32_WCE) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2564 | const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); |
| 2565 | |
| 2566 | // Gets the current text color. |
| 2567 | CONSOLE_SCREEN_BUFFER_INFO buffer_info; |
| 2568 | GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); |
| 2569 | const WORD old_color_attrs = buffer_info.wAttributes; |
| 2570 | |
| 2571 | SetConsoleTextAttribute(stdout_handle, |
| 2572 | GetColorAttribute(color) | FOREGROUND_INTENSITY); |
| 2573 | vprintf(fmt, args); |
| 2574 | |
| 2575 | // Restores the text color. |
| 2576 | SetConsoleTextAttribute(stdout_handle, old_color_attrs); |
| 2577 | #else |
| 2578 | printf("\033[0;3%sm", GetAnsiColorCode(color)); |
| 2579 | vprintf(fmt, args); |
| 2580 | printf("\033[m"); // Resets the terminal to default. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2581 | #endif // GTEST_OS_WINDOWS && !defined(_WIN32_WCE) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2582 | va_end(args); |
| 2583 | } |
| 2584 | |
| 2585 | } // namespace internal |
| 2586 | |
| 2587 | using internal::ColoredPrintf; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2588 | using internal::COLOR_DEFAULT; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2589 | using internal::COLOR_RED; |
| 2590 | using internal::COLOR_GREEN; |
| 2591 | using internal::COLOR_YELLOW; |
| 2592 | |
| 2593 | // This class implements the UnitTestEventListenerInterface interface. |
| 2594 | // |
| 2595 | // Class PrettyUnitTestResultPrinter is copyable. |
| 2596 | class PrettyUnitTestResultPrinter : public UnitTestEventListenerInterface { |
| 2597 | public: |
| 2598 | PrettyUnitTestResultPrinter() {} |
| 2599 | static void PrintTestName(const char * test_case, const char * test) { |
| 2600 | printf("%s.%s", test_case, test); |
| 2601 | } |
| 2602 | |
| 2603 | // The following methods override what's in the |
| 2604 | // UnitTestEventListenerInterface class. |
| 2605 | virtual void OnUnitTestStart(const UnitTest * unit_test); |
| 2606 | virtual void OnGlobalSetUpStart(const UnitTest*); |
| 2607 | virtual void OnTestCaseStart(const TestCase * test_case); |
| 2608 | virtual void OnTestCaseEnd(const TestCase * test_case); |
| 2609 | virtual void OnTestStart(const TestInfo * test_info); |
| 2610 | virtual void OnNewTestPartResult(const TestPartResult * result); |
| 2611 | virtual void OnTestEnd(const TestInfo * test_info); |
| 2612 | virtual void OnGlobalTearDownStart(const UnitTest*); |
| 2613 | virtual void OnUnitTestEnd(const UnitTest * unit_test); |
| 2614 | |
| 2615 | private: |
| 2616 | internal::String test_case_name_; |
| 2617 | }; |
| 2618 | |
| 2619 | // Called before the unit test starts. |
| 2620 | void PrettyUnitTestResultPrinter::OnUnitTestStart( |
| 2621 | const UnitTest * unit_test) { |
| 2622 | const char * const filter = GTEST_FLAG(filter).c_str(); |
| 2623 | |
| 2624 | // Prints the filter if it's not *. This reminds the user that some |
| 2625 | // tests may be skipped. |
| 2626 | if (!internal::String::CStringEquals(filter, kUniversalFilter)) { |
| 2627 | ColoredPrintf(COLOR_YELLOW, |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2628 | "Note: %s filter = %s\n", GTEST_NAME_, filter); |
| 2629 | } |
| 2630 | |
| 2631 | if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { |
| 2632 | ColoredPrintf(COLOR_YELLOW, |
| 2633 | "Note: This is test shard %s of %s.\n", |
| 2634 | internal::GetEnv(kTestShardIndex), |
| 2635 | internal::GetEnv(kTestTotalShards)); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2636 | } |
| 2637 | |
| 2638 | const internal::UnitTestImpl* const impl = unit_test->impl(); |
| 2639 | ColoredPrintf(COLOR_GREEN, "[==========] "); |
| 2640 | printf("Running %s from %s.\n", |
| 2641 | FormatTestCount(impl->test_to_run_count()).c_str(), |
| 2642 | FormatTestCaseCount(impl->test_case_to_run_count()).c_str()); |
| 2643 | fflush(stdout); |
| 2644 | } |
| 2645 | |
| 2646 | void PrettyUnitTestResultPrinter::OnGlobalSetUpStart(const UnitTest*) { |
| 2647 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2648 | printf("Global test environment set-up.\n"); |
| 2649 | fflush(stdout); |
| 2650 | } |
| 2651 | |
| 2652 | void PrettyUnitTestResultPrinter::OnTestCaseStart( |
| 2653 | const TestCase * test_case) { |
| 2654 | test_case_name_ = test_case->name(); |
| 2655 | const internal::String counts = |
| 2656 | FormatCountableNoun(test_case->test_to_run_count(), "test", "tests"); |
| 2657 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2658 | printf("%s from %s", counts.c_str(), test_case_name_.c_str()); |
| 2659 | if (test_case->comment()[0] == '\0') { |
| 2660 | printf("\n"); |
| 2661 | } else { |
| 2662 | printf(", where %s\n", test_case->comment()); |
| 2663 | } |
| 2664 | fflush(stdout); |
| 2665 | } |
| 2666 | |
| 2667 | void PrettyUnitTestResultPrinter::OnTestCaseEnd( |
| 2668 | const TestCase * test_case) { |
| 2669 | if (!GTEST_FLAG(print_time)) return; |
| 2670 | |
| 2671 | test_case_name_ = test_case->name(); |
| 2672 | const internal::String counts = |
| 2673 | FormatCountableNoun(test_case->test_to_run_count(), "test", "tests"); |
| 2674 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2675 | printf("%s from %s (%s ms total)\n\n", |
| 2676 | counts.c_str(), test_case_name_.c_str(), |
| 2677 | internal::StreamableToString(test_case->elapsed_time()).c_str()); |
| 2678 | fflush(stdout); |
| 2679 | } |
| 2680 | |
| 2681 | void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo * test_info) { |
| 2682 | ColoredPrintf(COLOR_GREEN, "[ RUN ] "); |
| 2683 | PrintTestName(test_case_name_.c_str(), test_info->name()); |
| 2684 | if (test_info->comment()[0] == '\0') { |
| 2685 | printf("\n"); |
| 2686 | } else { |
| 2687 | printf(", where %s\n", test_info->comment()); |
| 2688 | } |
| 2689 | fflush(stdout); |
| 2690 | } |
| 2691 | |
| 2692 | void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo * test_info) { |
| 2693 | if (test_info->result()->Passed()) { |
| 2694 | ColoredPrintf(COLOR_GREEN, "[ OK ] "); |
| 2695 | } else { |
| 2696 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2697 | } |
| 2698 | PrintTestName(test_case_name_.c_str(), test_info->name()); |
| 2699 | if (GTEST_FLAG(print_time)) { |
| 2700 | printf(" (%s ms)\n", internal::StreamableToString( |
| 2701 | test_info->result()->elapsed_time()).c_str()); |
| 2702 | } else { |
| 2703 | printf("\n"); |
| 2704 | } |
| 2705 | fflush(stdout); |
| 2706 | } |
| 2707 | |
| 2708 | // Called after an assertion failure. |
| 2709 | void PrettyUnitTestResultPrinter::OnNewTestPartResult( |
| 2710 | const TestPartResult * result) { |
| 2711 | // If the test part succeeded, we don't need to do anything. |
| 2712 | if (result->type() == TPRT_SUCCESS) |
| 2713 | return; |
| 2714 | |
| 2715 | // Print failure message from the assertion (e.g. expected this and got that). |
| 2716 | PrintTestPartResult(*result); |
| 2717 | fflush(stdout); |
| 2718 | } |
| 2719 | |
| 2720 | void PrettyUnitTestResultPrinter::OnGlobalTearDownStart(const UnitTest*) { |
| 2721 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2722 | printf("Global test environment tear-down\n"); |
| 2723 | fflush(stdout); |
| 2724 | } |
| 2725 | |
| 2726 | namespace internal { |
| 2727 | |
| 2728 | // Internal helper for printing the list of failed tests. |
| 2729 | static void PrintFailedTestsPretty(const UnitTestImpl* impl) { |
| 2730 | const int failed_test_count = impl->failed_test_count(); |
| 2731 | if (failed_test_count == 0) { |
| 2732 | return; |
| 2733 | } |
| 2734 | |
| 2735 | for (const internal::ListNode<TestCase*>* node = impl->test_cases()->Head(); |
| 2736 | node != NULL; node = node->next()) { |
| 2737 | const TestCase* const tc = node->element(); |
| 2738 | if (!tc->should_run() || (tc->failed_test_count() == 0)) { |
| 2739 | continue; |
| 2740 | } |
| 2741 | for (const internal::ListNode<TestInfo*>* tinode = |
| 2742 | tc->test_info_list().Head(); |
| 2743 | tinode != NULL; tinode = tinode->next()) { |
| 2744 | const TestInfo* const ti = tinode->element(); |
| 2745 | if (!tc->ShouldRunTest(ti) || tc->TestPassed(ti)) { |
| 2746 | continue; |
| 2747 | } |
| 2748 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2749 | printf("%s.%s", ti->test_case_name(), ti->name()); |
| 2750 | if (ti->test_case_comment()[0] != '\0' || |
| 2751 | ti->comment()[0] != '\0') { |
| 2752 | printf(", where %s", ti->test_case_comment()); |
| 2753 | if (ti->test_case_comment()[0] != '\0' && |
| 2754 | ti->comment()[0] != '\0') { |
| 2755 | printf(" and "); |
| 2756 | } |
| 2757 | } |
| 2758 | printf("%s\n", ti->comment()); |
| 2759 | } |
| 2760 | } |
| 2761 | } |
| 2762 | |
| 2763 | } // namespace internal |
| 2764 | |
| 2765 | void PrettyUnitTestResultPrinter::OnUnitTestEnd( |
| 2766 | const UnitTest * unit_test) { |
| 2767 | const internal::UnitTestImpl* const impl = unit_test->impl(); |
| 2768 | |
| 2769 | ColoredPrintf(COLOR_GREEN, "[==========] "); |
| 2770 | printf("%s from %s ran.", |
| 2771 | FormatTestCount(impl->test_to_run_count()).c_str(), |
| 2772 | FormatTestCaseCount(impl->test_case_to_run_count()).c_str()); |
| 2773 | if (GTEST_FLAG(print_time)) { |
| 2774 | printf(" (%s ms total)", |
| 2775 | internal::StreamableToString(impl->elapsed_time()).c_str()); |
| 2776 | } |
| 2777 | printf("\n"); |
| 2778 | ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); |
| 2779 | printf("%s.\n", FormatTestCount(impl->successful_test_count()).c_str()); |
| 2780 | |
| 2781 | int num_failures = impl->failed_test_count(); |
| 2782 | if (!impl->Passed()) { |
| 2783 | const int failed_test_count = impl->failed_test_count(); |
| 2784 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2785 | printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); |
| 2786 | internal::PrintFailedTestsPretty(impl); |
| 2787 | printf("\n%2d FAILED %s\n", num_failures, |
| 2788 | num_failures == 1 ? "TEST" : "TESTS"); |
| 2789 | } |
| 2790 | |
| 2791 | int num_disabled = impl->disabled_test_count(); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2792 | if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2793 | if (!num_failures) { |
| 2794 | printf("\n"); // Add a spacer if no FAILURE banner is displayed. |
| 2795 | } |
| 2796 | ColoredPrintf(COLOR_YELLOW, |
| 2797 | " YOU HAVE %d DISABLED %s\n\n", |
| 2798 | num_disabled, |
| 2799 | num_disabled == 1 ? "TEST" : "TESTS"); |
| 2800 | } |
| 2801 | // Ensure that Google Test output is printed before, e.g., heapchecker output. |
| 2802 | fflush(stdout); |
| 2803 | } |
| 2804 | |
| 2805 | // End PrettyUnitTestResultPrinter |
| 2806 | |
| 2807 | // class UnitTestEventsRepeater |
| 2808 | // |
| 2809 | // This class forwards events to other event listeners. |
| 2810 | class UnitTestEventsRepeater : public UnitTestEventListenerInterface { |
| 2811 | public: |
| 2812 | typedef internal::List<UnitTestEventListenerInterface *> Listeners; |
| 2813 | typedef internal::ListNode<UnitTestEventListenerInterface *> ListenersNode; |
| 2814 | UnitTestEventsRepeater() {} |
| 2815 | virtual ~UnitTestEventsRepeater(); |
| 2816 | void AddListener(UnitTestEventListenerInterface *listener); |
| 2817 | |
| 2818 | virtual void OnUnitTestStart(const UnitTest* unit_test); |
| 2819 | virtual void OnUnitTestEnd(const UnitTest* unit_test); |
| 2820 | virtual void OnGlobalSetUpStart(const UnitTest* unit_test); |
| 2821 | virtual void OnGlobalSetUpEnd(const UnitTest* unit_test); |
| 2822 | virtual void OnGlobalTearDownStart(const UnitTest* unit_test); |
| 2823 | virtual void OnGlobalTearDownEnd(const UnitTest* unit_test); |
| 2824 | virtual void OnTestCaseStart(const TestCase* test_case); |
| 2825 | virtual void OnTestCaseEnd(const TestCase* test_case); |
| 2826 | virtual void OnTestStart(const TestInfo* test_info); |
| 2827 | virtual void OnTestEnd(const TestInfo* test_info); |
| 2828 | virtual void OnNewTestPartResult(const TestPartResult* result); |
| 2829 | |
| 2830 | private: |
| 2831 | Listeners listeners_; |
| 2832 | |
| 2833 | GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestEventsRepeater); |
| 2834 | }; |
| 2835 | |
| 2836 | UnitTestEventsRepeater::~UnitTestEventsRepeater() { |
| 2837 | for (ListenersNode* listener = listeners_.Head(); |
| 2838 | listener != NULL; |
| 2839 | listener = listener->next()) { |
| 2840 | delete listener->element(); |
| 2841 | } |
| 2842 | } |
| 2843 | |
| 2844 | void UnitTestEventsRepeater::AddListener( |
| 2845 | UnitTestEventListenerInterface *listener) { |
| 2846 | listeners_.PushBack(listener); |
| 2847 | } |
| 2848 | |
| 2849 | // Since the methods are identical, use a macro to reduce boilerplate. |
| 2850 | // This defines a member that repeats the call to all listeners. |
| 2851 | #define GTEST_REPEATER_METHOD_(Name, Type) \ |
| 2852 | void UnitTestEventsRepeater::Name(const Type* parameter) { \ |
| 2853 | for (ListenersNode* listener = listeners_.Head(); \ |
| 2854 | listener != NULL; \ |
| 2855 | listener = listener->next()) { \ |
| 2856 | listener->element()->Name(parameter); \ |
| 2857 | } \ |
| 2858 | } |
| 2859 | |
| 2860 | GTEST_REPEATER_METHOD_(OnUnitTestStart, UnitTest) |
| 2861 | GTEST_REPEATER_METHOD_(OnUnitTestEnd, UnitTest) |
| 2862 | GTEST_REPEATER_METHOD_(OnGlobalSetUpStart, UnitTest) |
| 2863 | GTEST_REPEATER_METHOD_(OnGlobalSetUpEnd, UnitTest) |
| 2864 | GTEST_REPEATER_METHOD_(OnGlobalTearDownStart, UnitTest) |
| 2865 | GTEST_REPEATER_METHOD_(OnGlobalTearDownEnd, UnitTest) |
| 2866 | GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) |
| 2867 | GTEST_REPEATER_METHOD_(OnTestCaseEnd, TestCase) |
| 2868 | GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) |
| 2869 | GTEST_REPEATER_METHOD_(OnTestEnd, TestInfo) |
| 2870 | GTEST_REPEATER_METHOD_(OnNewTestPartResult, TestPartResult) |
| 2871 | |
| 2872 | #undef GTEST_REPEATER_METHOD_ |
| 2873 | |
| 2874 | // End PrettyUnitTestResultPrinter |
| 2875 | |
| 2876 | // This class generates an XML output file. |
| 2877 | class XmlUnitTestResultPrinter : public UnitTestEventListenerInterface { |
| 2878 | public: |
| 2879 | explicit XmlUnitTestResultPrinter(const char* output_file); |
| 2880 | |
| 2881 | virtual void OnUnitTestEnd(const UnitTest* unit_test); |
| 2882 | |
| 2883 | private: |
| 2884 | // Is c a whitespace character that is normalized to a space character |
| 2885 | // when it appears in an XML attribute value? |
| 2886 | static bool IsNormalizableWhitespace(char c) { |
| 2887 | return c == 0x9 || c == 0xA || c == 0xD; |
| 2888 | } |
| 2889 | |
| 2890 | // May c appear in a well-formed XML document? |
| 2891 | static bool IsValidXmlCharacter(char c) { |
| 2892 | return IsNormalizableWhitespace(c) || c >= 0x20; |
| 2893 | } |
| 2894 | |
| 2895 | // Returns an XML-escaped copy of the input string str. If |
| 2896 | // is_attribute is true, the text is meant to appear as an attribute |
| 2897 | // value, and normalizable whitespace is preserved by replacing it |
| 2898 | // with character references. |
| 2899 | static internal::String EscapeXml(const char* str, |
| 2900 | bool is_attribute); |
| 2901 | |
| 2902 | // Convenience wrapper around EscapeXml when str is an attribute value. |
| 2903 | static internal::String EscapeXmlAttribute(const char* str) { |
| 2904 | return EscapeXml(str, true); |
| 2905 | } |
| 2906 | |
| 2907 | // Convenience wrapper around EscapeXml when str is not an attribute value. |
| 2908 | static internal::String EscapeXmlText(const char* str) { |
| 2909 | return EscapeXml(str, false); |
| 2910 | } |
| 2911 | |
| 2912 | // Prints an XML representation of a TestInfo object. |
| 2913 | static void PrintXmlTestInfo(FILE* out, |
| 2914 | const char* test_case_name, |
| 2915 | const TestInfo* test_info); |
| 2916 | |
| 2917 | // Prints an XML representation of a TestCase object |
| 2918 | static void PrintXmlTestCase(FILE* out, const TestCase* test_case); |
| 2919 | |
| 2920 | // Prints an XML summary of unit_test to output stream out. |
| 2921 | static void PrintXmlUnitTest(FILE* out, const UnitTest* unit_test); |
| 2922 | |
| 2923 | // Produces a string representing the test properties in a result as space |
| 2924 | // delimited XML attributes based on the property key="value" pairs. |
| 2925 | // When the String is not empty, it includes a space at the beginning, |
| 2926 | // to delimit this attribute from prior attributes. |
| 2927 | static internal::String TestPropertiesAsXmlAttributes( |
| 2928 | const internal::TestResult* result); |
| 2929 | |
| 2930 | // The output file. |
| 2931 | const internal::String output_file_; |
| 2932 | |
| 2933 | GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); |
| 2934 | }; |
| 2935 | |
| 2936 | // Creates a new XmlUnitTestResultPrinter. |
| 2937 | XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) |
| 2938 | : output_file_(output_file) { |
| 2939 | if (output_file_.c_str() == NULL || output_file_.empty()) { |
| 2940 | fprintf(stderr, "XML output file may not be null\n"); |
| 2941 | fflush(stderr); |
| 2942 | exit(EXIT_FAILURE); |
| 2943 | } |
| 2944 | } |
| 2945 | |
| 2946 | // Called after the unit test ends. |
| 2947 | void XmlUnitTestResultPrinter::OnUnitTestEnd(const UnitTest* unit_test) { |
| 2948 | FILE* xmlout = NULL; |
| 2949 | internal::FilePath output_file(output_file_); |
| 2950 | internal::FilePath output_dir(output_file.RemoveFileName()); |
| 2951 | |
| 2952 | if (output_dir.CreateDirectoriesRecursively()) { |
| 2953 | // MSVC 8 deprecates fopen(), so we want to suppress warning 4996 |
| 2954 | // (deprecated function) there. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 2955 | #if GTEST_OS_WINDOWS |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 2956 | // We are on Windows. |
| 2957 | #pragma warning(push) // Saves the current warning state. |
| 2958 | #pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 2959 | xmlout = fopen(output_file_.c_str(), "w"); |
| 2960 | #pragma warning(pop) // Restores the warning state. |
| 2961 | #else // We are on Linux or Mac OS. |
| 2962 | xmlout = fopen(output_file_.c_str(), "w"); |
| 2963 | #endif // GTEST_OS_WINDOWS |
| 2964 | } |
| 2965 | if (xmlout == NULL) { |
| 2966 | // TODO(wan): report the reason of the failure. |
| 2967 | // |
| 2968 | // We don't do it for now as: |
| 2969 | // |
| 2970 | // 1. There is no urgent need for it. |
| 2971 | // 2. It's a bit involved to make the errno variable thread-safe on |
| 2972 | // all three operating systems (Linux, Windows, and Mac OS). |
| 2973 | // 3. To interpret the meaning of errno in a thread-safe way, |
| 2974 | // we need the strerror_r() function, which is not available on |
| 2975 | // Windows. |
| 2976 | fprintf(stderr, |
| 2977 | "Unable to open file \"%s\"\n", |
| 2978 | output_file_.c_str()); |
| 2979 | fflush(stderr); |
| 2980 | exit(EXIT_FAILURE); |
| 2981 | } |
| 2982 | PrintXmlUnitTest(xmlout, unit_test); |
| 2983 | fclose(xmlout); |
| 2984 | } |
| 2985 | |
| 2986 | // Returns an XML-escaped copy of the input string str. If is_attribute |
| 2987 | // is true, the text is meant to appear as an attribute value, and |
| 2988 | // normalizable whitespace is preserved by replacing it with character |
| 2989 | // references. |
| 2990 | // |
| 2991 | // Invalid XML characters in str, if any, are stripped from the output. |
| 2992 | // It is expected that most, if not all, of the text processed by this |
| 2993 | // module will consist of ordinary English text. |
| 2994 | // If this module is ever modified to produce version 1.1 XML output, |
| 2995 | // most invalid characters can be retained using character references. |
| 2996 | // TODO(wan): It might be nice to have a minimally invasive, human-readable |
| 2997 | // escaping scheme for invalid characters, rather than dropping them. |
| 2998 | internal::String XmlUnitTestResultPrinter::EscapeXml(const char* str, |
| 2999 | bool is_attribute) { |
| 3000 | Message m; |
| 3001 | |
| 3002 | if (str != NULL) { |
| 3003 | for (const char* src = str; *src; ++src) { |
| 3004 | switch (*src) { |
| 3005 | case '<': |
| 3006 | m << "<"; |
| 3007 | break; |
| 3008 | case '>': |
| 3009 | m << ">"; |
| 3010 | break; |
| 3011 | case '&': |
| 3012 | m << "&"; |
| 3013 | break; |
| 3014 | case '\'': |
| 3015 | if (is_attribute) |
| 3016 | m << "'"; |
| 3017 | else |
| 3018 | m << '\''; |
| 3019 | break; |
| 3020 | case '"': |
| 3021 | if (is_attribute) |
| 3022 | m << """; |
| 3023 | else |
| 3024 | m << '"'; |
| 3025 | break; |
| 3026 | default: |
| 3027 | if (IsValidXmlCharacter(*src)) { |
| 3028 | if (is_attribute && IsNormalizableWhitespace(*src)) |
| 3029 | m << internal::String::Format("&#x%02X;", unsigned(*src)); |
| 3030 | else |
| 3031 | m << *src; |
| 3032 | } |
| 3033 | break; |
| 3034 | } |
| 3035 | } |
| 3036 | } |
| 3037 | |
| 3038 | return m.GetString(); |
| 3039 | } |
| 3040 | |
| 3041 | |
| 3042 | // The following routines generate an XML representation of a UnitTest |
| 3043 | // object. |
| 3044 | // |
| 3045 | // This is how Google Test concepts map to the DTD: |
| 3046 | // |
| 3047 | // <testsuite name="AllTests"> <-- corresponds to a UnitTest object |
| 3048 | // <testsuite name="testcase-name"> <-- corresponds to a TestCase object |
| 3049 | // <testcase name="test-name"> <-- corresponds to a TestInfo object |
| 3050 | // <failure message="...">...</failure> |
| 3051 | // <failure message="...">...</failure> |
| 3052 | // <failure message="...">...</failure> |
| 3053 | // <-- individual assertion failures |
| 3054 | // </testcase> |
| 3055 | // </testsuite> |
| 3056 | // </testsuite> |
| 3057 | |
| 3058 | namespace internal { |
| 3059 | |
| 3060 | // Formats the given time in milliseconds as seconds. The returned |
| 3061 | // C-string is owned by this function and cannot be released by the |
| 3062 | // caller. Calling the function again invalidates the previous |
| 3063 | // result. |
| 3064 | const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) { |
| 3065 | static String str; |
| 3066 | str = (Message() << (ms/1000.0)).GetString(); |
| 3067 | return str.c_str(); |
| 3068 | } |
| 3069 | |
| 3070 | } // namespace internal |
| 3071 | |
| 3072 | // Prints an XML representation of a TestInfo object. |
| 3073 | // TODO(wan): There is also value in printing properties with the plain printer. |
| 3074 | void XmlUnitTestResultPrinter::PrintXmlTestInfo(FILE* out, |
| 3075 | const char* test_case_name, |
| 3076 | const TestInfo* test_info) { |
| 3077 | const internal::TestResult * const result = test_info->result(); |
| 3078 | const internal::List<TestPartResult> &results = result->test_part_results(); |
| 3079 | fprintf(out, |
| 3080 | " <testcase name=\"%s\" status=\"%s\" time=\"%s\" " |
| 3081 | "classname=\"%s\"%s", |
| 3082 | EscapeXmlAttribute(test_info->name()).c_str(), |
| 3083 | test_info->should_run() ? "run" : "notrun", |
| 3084 | internal::FormatTimeInMillisAsSeconds(result->elapsed_time()), |
| 3085 | EscapeXmlAttribute(test_case_name).c_str(), |
| 3086 | TestPropertiesAsXmlAttributes(result).c_str()); |
| 3087 | |
| 3088 | int failures = 0; |
| 3089 | for (const internal::ListNode<TestPartResult>* part_node = results.Head(); |
| 3090 | part_node != NULL; |
| 3091 | part_node = part_node->next()) { |
| 3092 | const TestPartResult& part = part_node->element(); |
| 3093 | if (part.failed()) { |
| 3094 | const internal::String message = |
| 3095 | internal::String::Format("%s:%d\n%s", part.file_name(), |
| 3096 | part.line_number(), part.message()); |
| 3097 | if (++failures == 1) |
| 3098 | fprintf(out, ">\n"); |
| 3099 | fprintf(out, |
| 3100 | " <failure message=\"%s\" type=\"\"><![CDATA[%s]]>" |
| 3101 | "</failure>\n", |
| 3102 | EscapeXmlAttribute(part.summary()).c_str(), message.c_str()); |
| 3103 | } |
| 3104 | } |
| 3105 | |
| 3106 | if (failures == 0) |
| 3107 | fprintf(out, " />\n"); |
| 3108 | else |
| 3109 | fprintf(out, " </testcase>\n"); |
| 3110 | } |
| 3111 | |
| 3112 | // Prints an XML representation of a TestCase object |
| 3113 | void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, |
| 3114 | const TestCase* test_case) { |
| 3115 | fprintf(out, |
| 3116 | " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" " |
| 3117 | "disabled=\"%d\" ", |
| 3118 | EscapeXmlAttribute(test_case->name()).c_str(), |
| 3119 | test_case->total_test_count(), |
| 3120 | test_case->failed_test_count(), |
| 3121 | test_case->disabled_test_count()); |
| 3122 | fprintf(out, |
| 3123 | "errors=\"0\" time=\"%s\">\n", |
| 3124 | internal::FormatTimeInMillisAsSeconds(test_case->elapsed_time())); |
| 3125 | for (const internal::ListNode<TestInfo*>* info_node = |
| 3126 | test_case->test_info_list().Head(); |
| 3127 | info_node != NULL; |
| 3128 | info_node = info_node->next()) { |
| 3129 | PrintXmlTestInfo(out, test_case->name(), info_node->element()); |
| 3130 | } |
| 3131 | fprintf(out, " </testsuite>\n"); |
| 3132 | } |
| 3133 | |
| 3134 | // Prints an XML summary of unit_test to output stream out. |
| 3135 | void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, |
| 3136 | const UnitTest* unit_test) { |
| 3137 | const internal::UnitTestImpl* const impl = unit_test->impl(); |
| 3138 | fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); |
| 3139 | fprintf(out, |
| 3140 | "<testsuite tests=\"%d\" failures=\"%d\" disabled=\"%d\" " |
| 3141 | "errors=\"0\" time=\"%s\" ", |
| 3142 | impl->total_test_count(), |
| 3143 | impl->failed_test_count(), |
| 3144 | impl->disabled_test_count(), |
| 3145 | internal::FormatTimeInMillisAsSeconds(impl->elapsed_time())); |
| 3146 | fprintf(out, "name=\"AllTests\">\n"); |
| 3147 | for (const internal::ListNode<TestCase*>* case_node = |
| 3148 | impl->test_cases()->Head(); |
| 3149 | case_node != NULL; |
| 3150 | case_node = case_node->next()) { |
| 3151 | PrintXmlTestCase(out, case_node->element()); |
| 3152 | } |
| 3153 | fprintf(out, "</testsuite>\n"); |
| 3154 | } |
| 3155 | |
| 3156 | // Produces a string representing the test properties in a result as space |
| 3157 | // delimited XML attributes based on the property key="value" pairs. |
| 3158 | internal::String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( |
| 3159 | const internal::TestResult* result) { |
| 3160 | using internal::TestProperty; |
| 3161 | Message attributes; |
| 3162 | const internal::List<TestProperty>& properties = result->test_properties(); |
| 3163 | for (const internal::ListNode<TestProperty>* property_node = |
| 3164 | properties.Head(); |
| 3165 | property_node != NULL; |
| 3166 | property_node = property_node->next()) { |
| 3167 | const TestProperty& property = property_node->element(); |
| 3168 | attributes << " " << property.key() << "=" |
| 3169 | << "\"" << EscapeXmlAttribute(property.value()) << "\""; |
| 3170 | } |
| 3171 | return attributes.GetString(); |
| 3172 | } |
| 3173 | |
| 3174 | // End XmlUnitTestResultPrinter |
| 3175 | |
| 3176 | namespace internal { |
| 3177 | |
| 3178 | // Class ScopedTrace |
| 3179 | |
| 3180 | // Pushes the given source file location and message onto a per-thread |
| 3181 | // trace stack maintained by Google Test. |
| 3182 | // L < UnitTest::mutex_ |
| 3183 | ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { |
| 3184 | TraceInfo trace; |
| 3185 | trace.file = file; |
| 3186 | trace.line = line; |
| 3187 | trace.message = message.GetString(); |
| 3188 | |
| 3189 | UnitTest::GetInstance()->PushGTestTrace(trace); |
| 3190 | } |
| 3191 | |
| 3192 | // Pops the info pushed by the c'tor. |
| 3193 | // L < UnitTest::mutex_ |
| 3194 | ScopedTrace::~ScopedTrace() { |
| 3195 | UnitTest::GetInstance()->PopGTestTrace(); |
| 3196 | } |
| 3197 | |
| 3198 | |
| 3199 | // class OsStackTraceGetter |
| 3200 | |
| 3201 | // Returns the current OS stack trace as a String. Parameters: |
| 3202 | // |
| 3203 | // max_depth - the maximum number of stack frames to be included |
| 3204 | // in the trace. |
| 3205 | // skip_count - the number of top frames to be skipped; doesn't count |
| 3206 | // against max_depth. |
| 3207 | // |
| 3208 | // L < mutex_ |
| 3209 | // We use "L < mutex_" to denote that the function may acquire mutex_. |
| 3210 | String OsStackTraceGetter::CurrentStackTrace(int, int) { |
| 3211 | return String(""); |
| 3212 | } |
| 3213 | |
| 3214 | // L < mutex_ |
| 3215 | void OsStackTraceGetter::UponLeavingGTest() { |
| 3216 | } |
| 3217 | |
| 3218 | const char* const |
| 3219 | OsStackTraceGetter::kElidedFramesMarker = |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3220 | "... " GTEST_NAME_ " internal frames ..."; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3221 | |
| 3222 | } // namespace internal |
| 3223 | |
| 3224 | // class UnitTest |
| 3225 | |
| 3226 | // Gets the singleton UnitTest object. The first time this method is |
| 3227 | // called, a UnitTest object is constructed and returned. Consecutive |
| 3228 | // calls will return the same object. |
| 3229 | // |
| 3230 | // We don't protect this under mutex_ as a user is not supposed to |
| 3231 | // call this before main() starts, from which point on the return |
| 3232 | // value will never change. |
| 3233 | UnitTest * UnitTest::GetInstance() { |
| 3234 | // When compiled with MSVC 7.1 in optimized mode, destroying the |
| 3235 | // UnitTest object upon exiting the program messes up the exit code, |
| 3236 | // causing successful tests to appear failed. We have to use a |
| 3237 | // different implementation in this case to bypass the compiler bug. |
| 3238 | // This implementation makes the compiler happy, at the cost of |
| 3239 | // leaking the UnitTest object. |
| 3240 | #if _MSC_VER == 1310 && !defined(_DEBUG) // MSVC 7.1 and optimized build. |
| 3241 | static UnitTest* const instance = new UnitTest; |
| 3242 | return instance; |
| 3243 | #else |
| 3244 | static UnitTest instance; |
| 3245 | return &instance; |
| 3246 | #endif // _MSC_VER==1310 && !defined(_DEBUG) |
| 3247 | } |
| 3248 | |
| 3249 | // Registers and returns a global test environment. When a test |
| 3250 | // program is run, all global test environments will be set-up in the |
| 3251 | // order they were registered. After all tests in the program have |
| 3252 | // finished, all global test environments will be torn-down in the |
| 3253 | // *reverse* order they were registered. |
| 3254 | // |
| 3255 | // The UnitTest object takes ownership of the given environment. |
| 3256 | // |
| 3257 | // We don't protect this under mutex_, as we only support calling it |
| 3258 | // from the main thread. |
| 3259 | Environment* UnitTest::AddEnvironment(Environment* env) { |
| 3260 | if (env == NULL) { |
| 3261 | return NULL; |
| 3262 | } |
| 3263 | |
| 3264 | impl_->environments()->PushBack(env); |
| 3265 | impl_->environments_in_reverse_order()->PushFront(env); |
| 3266 | return env; |
| 3267 | } |
| 3268 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3269 | #if GTEST_HAS_EXCEPTIONS |
| 3270 | // A failed Google Test assertion will throw an exception of this type |
| 3271 | // when exceptions are enabled. We derive it from std::runtime_error, |
| 3272 | // which is for errors presumably detectable only at run time. Since |
| 3273 | // std::runtime_error inherits from std::exception, many testing |
| 3274 | // frameworks know how to extract and print the message inside it. |
| 3275 | class GoogleTestFailureException : public ::std::runtime_error { |
| 3276 | public: |
| 3277 | explicit GoogleTestFailureException(const TestPartResult& failure) |
| 3278 | : runtime_error(PrintTestPartResultToString(failure).c_str()) {} |
| 3279 | }; |
| 3280 | #endif |
| 3281 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3282 | // Adds a TestPartResult to the current TestResult object. All Google Test |
| 3283 | // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call |
| 3284 | // this to report their results. The user code should use the |
| 3285 | // assertion macros instead of calling this directly. |
| 3286 | // L < mutex_ |
| 3287 | void UnitTest::AddTestPartResult(TestPartResultType result_type, |
| 3288 | const char* file_name, |
| 3289 | int line_number, |
| 3290 | const internal::String& message, |
| 3291 | const internal::String& os_stack_trace) { |
| 3292 | Message msg; |
| 3293 | msg << message; |
| 3294 | |
| 3295 | internal::MutexLock lock(&mutex_); |
| 3296 | if (impl_->gtest_trace_stack()->size() > 0) { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3297 | msg << "\n" << GTEST_NAME_ << " trace:"; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3298 | |
| 3299 | for (internal::ListNode<internal::TraceInfo>* node = |
| 3300 | impl_->gtest_trace_stack()->Head(); |
| 3301 | node != NULL; |
| 3302 | node = node->next()) { |
| 3303 | const internal::TraceInfo& trace = node->element(); |
| 3304 | msg << "\n" << trace.file << ":" << trace.line << ": " << trace.message; |
| 3305 | } |
| 3306 | } |
| 3307 | |
| 3308 | if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { |
| 3309 | msg << internal::kStackTraceMarker << os_stack_trace; |
| 3310 | } |
| 3311 | |
| 3312 | const TestPartResult result = |
| 3313 | TestPartResult(result_type, file_name, line_number, |
| 3314 | msg.GetString().c_str()); |
| 3315 | impl_->GetTestPartResultReporterForCurrentThread()-> |
| 3316 | ReportTestPartResult(result); |
| 3317 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3318 | if (result_type != TPRT_SUCCESS) { |
| 3319 | // gunit_break_on_failure takes precedence over |
| 3320 | // gunit_throw_on_failure. This allows a user to set the latter |
| 3321 | // in the code (perhaps in order to use Google Test assertions |
| 3322 | // with another testing framework) and specify the former on the |
| 3323 | // command line for debugging. |
| 3324 | if (GTEST_FLAG(break_on_failure)) { |
| 3325 | *static_cast<int*>(NULL) = 1; |
| 3326 | } else if (GTEST_FLAG(throw_on_failure)) { |
| 3327 | #if GTEST_HAS_EXCEPTIONS |
| 3328 | throw GoogleTestFailureException(result); |
| 3329 | #else |
| 3330 | // We cannot call abort() as it generates a pop-up in debug mode |
| 3331 | // that cannot be suppressed in VC 7.1 or below. |
| 3332 | exit(1); |
| 3333 | #endif |
| 3334 | } |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3335 | } |
| 3336 | } |
| 3337 | |
| 3338 | // Creates and adds a property to the current TestResult. If a property matching |
| 3339 | // the supplied value already exists, updates its value instead. |
| 3340 | void UnitTest::RecordPropertyForCurrentTest(const char* key, |
| 3341 | const char* value) { |
| 3342 | const internal::TestProperty test_property(key, value); |
| 3343 | impl_->current_test_result()->RecordProperty(test_property); |
| 3344 | } |
| 3345 | |
| 3346 | // Runs all tests in this UnitTest object and prints the result. |
| 3347 | // Returns 0 if successful, or 1 otherwise. |
| 3348 | // |
| 3349 | // We don't protect this under mutex_, as we only support calling it |
| 3350 | // from the main thread. |
| 3351 | int UnitTest::Run() { |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3352 | #if GTEST_OS_WINDOWS && !defined(__MINGW32__) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3353 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3354 | const bool in_death_test_child_process = |
| 3355 | internal::GTEST_FLAG(internal_run_death_test).GetLength() > 0; |
| 3356 | |
| 3357 | // Either the user wants Google Test to catch exceptions thrown by the |
| 3358 | // tests or this is executing in the context of death test child |
| 3359 | // process. In either case the user does not want to see pop-up dialogs |
| 3360 | // about crashes - they are expected.. |
| 3361 | if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) { |
| 3362 | // process. In either case the user does not want to see pop-up dialogs |
| 3363 | // about crashes - they are expected.. |
| 3364 | if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) { |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3365 | #if !defined(_WIN32_WCE) |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3366 | // SetErrorMode doesn't exist on CE. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3367 | SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | |
| 3368 | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3369 | #endif // _WIN32_WCE |
| 3370 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3371 | // Death test children can be terminated with _abort(). On Windows, |
| 3372 | // _abort() can show a dialog with a warning message. This forces the |
| 3373 | // abort message to go to stderr instead. |
| 3374 | _set_error_mode(_OUT_TO_STDERR); |
| 3375 | |
| 3376 | // In the debug version, Visual Studio pops up a separate dialog |
| 3377 | // offering a choice to debug the aborted program. We need to suppress |
| 3378 | // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement |
| 3379 | // executed. Google Test will notify the user of any unexpected |
| 3380 | // failure via stderr. |
| 3381 | #if _MSC_VER >= 1400 |
| 3382 | // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. |
| 3383 | // Users of prior VC versions shall suffer the agony and pain of |
| 3384 | // clicking through the countless debug dialogs. |
| 3385 | // TODO(vladl@google.com): find a way to suppress the abort dialog() in the |
| 3386 | // debug mode when compiled with VC 7.1 or lower. |
| 3387 | if (!GTEST_FLAG(break_on_failure)) |
| 3388 | _set_abort_behavior( |
| 3389 | 0x0, // Clear the following flags: |
| 3390 | _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. |
| 3391 | #endif // _MSC_VER >= 1400 |
| 3392 | } |
| 3393 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3394 | __try { |
| 3395 | return impl_->RunAllTests(); |
| 3396 | } __except(internal::UnitTestOptions::GTestShouldProcessSEH( |
| 3397 | GetExceptionCode())) { |
| 3398 | printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode()); |
| 3399 | fflush(stdout); |
| 3400 | return 1; |
| 3401 | } |
| 3402 | |
| 3403 | #else |
Julien Lerouge | e0a056b | 2009-02-12 08:02:35 +0000 | [diff] [blame] | 3404 | // We are on Linux, Mac OS or MingW. There is no exception of any kind. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3405 | |
| 3406 | return impl_->RunAllTests(); |
| 3407 | #endif // GTEST_OS_WINDOWS |
| 3408 | } |
| 3409 | |
| 3410 | // Returns the working directory when the first TEST() or TEST_F() was |
| 3411 | // executed. |
| 3412 | const char* UnitTest::original_working_dir() const { |
| 3413 | return impl_->original_working_dir_.c_str(); |
| 3414 | } |
| 3415 | |
| 3416 | // Returns the TestCase object for the test that's currently running, |
| 3417 | // or NULL if no test is running. |
| 3418 | // L < mutex_ |
| 3419 | const TestCase* UnitTest::current_test_case() const { |
| 3420 | internal::MutexLock lock(&mutex_); |
| 3421 | return impl_->current_test_case(); |
| 3422 | } |
| 3423 | |
| 3424 | // Returns the TestInfo object for the test that's currently running, |
| 3425 | // or NULL if no test is running. |
| 3426 | // L < mutex_ |
| 3427 | const TestInfo* UnitTest::current_test_info() const { |
| 3428 | internal::MutexLock lock(&mutex_); |
| 3429 | return impl_->current_test_info(); |
| 3430 | } |
| 3431 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3432 | #if GTEST_HAS_PARAM_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3433 | // Returns ParameterizedTestCaseRegistry object used to keep track of |
| 3434 | // value-parameterized tests and instantiate and register them. |
| 3435 | // L < mutex_ |
| 3436 | internal::ParameterizedTestCaseRegistry& |
| 3437 | UnitTest::parameterized_test_registry() { |
| 3438 | return impl_->parameterized_test_registry(); |
| 3439 | } |
| 3440 | #endif // GTEST_HAS_PARAM_TEST |
| 3441 | |
| 3442 | // Creates an empty UnitTest. |
| 3443 | UnitTest::UnitTest() { |
| 3444 | impl_ = new internal::UnitTestImpl(this); |
| 3445 | } |
| 3446 | |
| 3447 | // Destructor of UnitTest. |
| 3448 | UnitTest::~UnitTest() { |
| 3449 | delete impl_; |
| 3450 | } |
| 3451 | |
| 3452 | // Pushes a trace defined by SCOPED_TRACE() on to the per-thread |
| 3453 | // Google Test trace stack. |
| 3454 | // L < mutex_ |
| 3455 | void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { |
| 3456 | internal::MutexLock lock(&mutex_); |
| 3457 | impl_->gtest_trace_stack()->PushFront(trace); |
| 3458 | } |
| 3459 | |
| 3460 | // Pops a trace from the per-thread Google Test trace stack. |
| 3461 | // L < mutex_ |
| 3462 | void UnitTest::PopGTestTrace() { |
| 3463 | internal::MutexLock lock(&mutex_); |
| 3464 | impl_->gtest_trace_stack()->PopFront(NULL); |
| 3465 | } |
| 3466 | |
| 3467 | namespace internal { |
| 3468 | |
| 3469 | UnitTestImpl::UnitTestImpl(UnitTest* parent) |
| 3470 | : parent_(parent), |
| 3471 | #ifdef _MSC_VER |
| 3472 | #pragma warning(push) // Saves the current warning state. |
| 3473 | #pragma warning(disable:4355) // Temporarily disables warning 4355 |
| 3474 | // (using this in initializer). |
| 3475 | default_global_test_part_result_reporter_(this), |
| 3476 | default_per_thread_test_part_result_reporter_(this), |
| 3477 | #pragma warning(pop) // Restores the warning state again. |
| 3478 | #else |
| 3479 | default_global_test_part_result_reporter_(this), |
| 3480 | default_per_thread_test_part_result_reporter_(this), |
| 3481 | #endif // _MSC_VER |
| 3482 | global_test_part_result_repoter_( |
| 3483 | &default_global_test_part_result_reporter_), |
| 3484 | per_thread_test_part_result_reporter_( |
| 3485 | &default_per_thread_test_part_result_reporter_), |
| 3486 | test_cases_(), |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3487 | #if GTEST_HAS_PARAM_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3488 | parameterized_test_registry_(), |
| 3489 | parameterized_tests_registered_(false), |
| 3490 | #endif // GTEST_HAS_PARAM_TEST |
| 3491 | last_death_test_case_(NULL), |
| 3492 | current_test_case_(NULL), |
| 3493 | current_test_info_(NULL), |
| 3494 | ad_hoc_test_result_(), |
| 3495 | result_printer_(NULL), |
| 3496 | os_stack_trace_getter_(NULL), |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3497 | #if GTEST_HAS_DEATH_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3498 | elapsed_time_(0), |
| 3499 | internal_run_death_test_flag_(NULL), |
| 3500 | death_test_factory_(new DefaultDeathTestFactory) { |
| 3501 | #else |
| 3502 | elapsed_time_(0) { |
| 3503 | #endif // GTEST_HAS_DEATH_TEST |
| 3504 | } |
| 3505 | |
| 3506 | UnitTestImpl::~UnitTestImpl() { |
| 3507 | // Deletes every TestCase. |
| 3508 | test_cases_.ForEach(internal::Delete<TestCase>); |
| 3509 | |
| 3510 | // Deletes every Environment. |
| 3511 | environments_.ForEach(internal::Delete<Environment>); |
| 3512 | |
| 3513 | // Deletes the current test result printer. |
| 3514 | delete result_printer_; |
| 3515 | |
| 3516 | delete os_stack_trace_getter_; |
| 3517 | } |
| 3518 | |
| 3519 | // A predicate that checks the name of a TestCase against a known |
| 3520 | // value. |
| 3521 | // |
| 3522 | // This is used for implementation of the UnitTest class only. We put |
| 3523 | // it in the anonymous namespace to prevent polluting the outer |
| 3524 | // namespace. |
| 3525 | // |
| 3526 | // TestCaseNameIs is copyable. |
| 3527 | class TestCaseNameIs { |
| 3528 | public: |
| 3529 | // Constructor. |
| 3530 | explicit TestCaseNameIs(const String& name) |
| 3531 | : name_(name) {} |
| 3532 | |
| 3533 | // Returns true iff the name of test_case matches name_. |
| 3534 | bool operator()(const TestCase* test_case) const { |
| 3535 | return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; |
| 3536 | } |
| 3537 | |
| 3538 | private: |
| 3539 | String name_; |
| 3540 | }; |
| 3541 | |
| 3542 | // Finds and returns a TestCase with the given name. If one doesn't |
| 3543 | // exist, creates one and returns it. |
| 3544 | // |
| 3545 | // Arguments: |
| 3546 | // |
| 3547 | // test_case_name: name of the test case |
| 3548 | // set_up_tc: pointer to the function that sets up the test case |
| 3549 | // tear_down_tc: pointer to the function that tears down the test case |
| 3550 | TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, |
| 3551 | const char* comment, |
| 3552 | Test::SetUpTestCaseFunc set_up_tc, |
| 3553 | Test::TearDownTestCaseFunc tear_down_tc) { |
| 3554 | // Can we find a TestCase with the given name? |
| 3555 | internal::ListNode<TestCase*>* node = test_cases_.FindIf( |
| 3556 | TestCaseNameIs(test_case_name)); |
| 3557 | |
| 3558 | if (node == NULL) { |
| 3559 | // No. Let's create one. |
| 3560 | TestCase* const test_case = |
| 3561 | new TestCase(test_case_name, comment, set_up_tc, tear_down_tc); |
| 3562 | |
| 3563 | // Is this a death test case? |
| 3564 | if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), |
| 3565 | kDeathTestCaseFilter)) { |
| 3566 | // Yes. Inserts the test case after the last death test case |
| 3567 | // defined so far. |
| 3568 | node = test_cases_.InsertAfter(last_death_test_case_, test_case); |
| 3569 | last_death_test_case_ = node; |
| 3570 | } else { |
| 3571 | // No. Appends to the end of the list. |
| 3572 | test_cases_.PushBack(test_case); |
| 3573 | node = test_cases_.Last(); |
| 3574 | } |
| 3575 | } |
| 3576 | |
| 3577 | // Returns the TestCase found. |
| 3578 | return node->element(); |
| 3579 | } |
| 3580 | |
| 3581 | // Helpers for setting up / tearing down the given environment. They |
| 3582 | // are for use in the List::ForEach() method. |
| 3583 | static void SetUpEnvironment(Environment* env) { env->SetUp(); } |
| 3584 | static void TearDownEnvironment(Environment* env) { env->TearDown(); } |
| 3585 | |
| 3586 | // Runs all tests in this UnitTest object, prints the result, and |
| 3587 | // returns 0 if all tests are successful, or 1 otherwise. If any |
| 3588 | // exception is thrown during a test on Windows, this test is |
| 3589 | // considered to be failed, but the rest of the tests will still be |
| 3590 | // run. (We disable exceptions on Linux and Mac OS X, so the issue |
| 3591 | // doesn't apply there.) |
| 3592 | // When parameterized tests are enabled, it explands and registers |
| 3593 | // parameterized tests first in RegisterParameterizedTests(). |
| 3594 | // All other functions called from RunAllTests() may safely assume that |
| 3595 | // parameterized tests are ready to be counted and run. |
| 3596 | int UnitTestImpl::RunAllTests() { |
| 3597 | // Makes sure InitGoogleTest() was called. |
| 3598 | if (!GTestIsInitialized()) { |
| 3599 | printf("%s", |
| 3600 | "\nThis test program did NOT call ::testing::InitGoogleTest " |
| 3601 | "before calling RUN_ALL_TESTS(). Please fix it.\n"); |
| 3602 | return 1; |
| 3603 | } |
| 3604 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3605 | // Do not run any test if the --help flag was specified. |
| 3606 | if (g_help_flag) |
| 3607 | return 0; |
| 3608 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3609 | RegisterParameterizedTests(); |
| 3610 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3611 | // Even if sharding is not on, test runners may want to use the |
| 3612 | // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding |
| 3613 | // protocol. |
| 3614 | internal::WriteToShardStatusFileIfNeeded(); |
| 3615 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3616 | // Lists all the tests and exits if the --gtest_list_tests |
| 3617 | // flag was specified. |
| 3618 | if (GTEST_FLAG(list_tests)) { |
| 3619 | ListAllTests(); |
| 3620 | return 0; |
| 3621 | } |
| 3622 | |
| 3623 | // True iff we are in a subprocess for running a thread-safe-style |
| 3624 | // death test. |
| 3625 | bool in_subprocess_for_death_test = false; |
| 3626 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3627 | #if GTEST_HAS_DEATH_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3628 | internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); |
| 3629 | in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); |
| 3630 | #endif // GTEST_HAS_DEATH_TEST |
| 3631 | |
| 3632 | UnitTestEventListenerInterface * const printer = result_printer(); |
| 3633 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3634 | const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, |
| 3635 | in_subprocess_for_death_test); |
| 3636 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3637 | // Compares the full test names with the filter to decide which |
| 3638 | // tests to run. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3639 | const bool has_tests_to_run = FilterTests(should_shard |
| 3640 | ? HONOR_SHARDING_PROTOCOL |
| 3641 | : IGNORE_SHARDING_PROTOCOL) > 0; |
| 3642 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3643 | // True iff at least one test has failed. |
| 3644 | bool failed = false; |
| 3645 | |
| 3646 | // How many times to repeat the tests? We don't want to repeat them |
| 3647 | // when we are inside the subprocess of a death test. |
| 3648 | const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); |
| 3649 | // Repeats forever if the repeat count is negative. |
| 3650 | const bool forever = repeat < 0; |
| 3651 | for (int i = 0; forever || i != repeat; i++) { |
| 3652 | if (repeat != 1) { |
| 3653 | printf("\nRepeating all tests (iteration %d) . . .\n\n", i + 1); |
| 3654 | } |
| 3655 | |
| 3656 | // Tells the unit test event listener that the tests are about to |
| 3657 | // start. |
| 3658 | printer->OnUnitTestStart(parent_); |
| 3659 | |
| 3660 | const TimeInMillis start = GetTimeInMillis(); |
| 3661 | |
| 3662 | // Runs each test case if there is at least one test to run. |
| 3663 | if (has_tests_to_run) { |
| 3664 | // Sets up all environments beforehand. |
| 3665 | printer->OnGlobalSetUpStart(parent_); |
| 3666 | environments_.ForEach(SetUpEnvironment); |
| 3667 | printer->OnGlobalSetUpEnd(parent_); |
| 3668 | |
| 3669 | // Runs the tests only if there was no fatal failure during global |
| 3670 | // set-up. |
| 3671 | if (!Test::HasFatalFailure()) { |
| 3672 | test_cases_.ForEach(TestCase::RunTestCase); |
| 3673 | } |
| 3674 | |
| 3675 | // Tears down all environments in reverse order afterwards. |
| 3676 | printer->OnGlobalTearDownStart(parent_); |
| 3677 | environments_in_reverse_order_.ForEach(TearDownEnvironment); |
| 3678 | printer->OnGlobalTearDownEnd(parent_); |
| 3679 | } |
| 3680 | |
| 3681 | elapsed_time_ = GetTimeInMillis() - start; |
| 3682 | |
| 3683 | // Tells the unit test event listener that the tests have just |
| 3684 | // finished. |
| 3685 | printer->OnUnitTestEnd(parent_); |
| 3686 | |
| 3687 | // Gets the result and clears it. |
| 3688 | if (!Passed()) { |
| 3689 | failed = true; |
| 3690 | } |
| 3691 | ClearResult(); |
| 3692 | } |
| 3693 | |
| 3694 | // Returns 0 if all tests passed, or 1 other wise. |
| 3695 | return failed ? 1 : 0; |
| 3696 | } |
| 3697 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3698 | // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file |
| 3699 | // if the variable is present. If a file already exists at this location, this |
| 3700 | // function will write over it. If the variable is present, but the file cannot |
| 3701 | // be created, prints an error and exits. |
| 3702 | void WriteToShardStatusFileIfNeeded() { |
| 3703 | const char* const test_shard_file = GetEnv(kTestShardStatusFile); |
| 3704 | if (test_shard_file != NULL) { |
| 3705 | #ifdef _MSC_VER // MSVC 8 deprecates fopen(). |
| 3706 | #pragma warning(push) // Saves the current warning state. |
| 3707 | #pragma warning(disable:4996) // Temporarily disables warning on |
| 3708 | // deprecated functions. |
| 3709 | #endif |
| 3710 | FILE* const file = fopen(test_shard_file, "w"); |
| 3711 | #ifdef _MSC_VER |
| 3712 | #pragma warning(pop) // Restores the warning state. |
| 3713 | #endif |
| 3714 | if (file == NULL) { |
| 3715 | ColoredPrintf(COLOR_RED, |
| 3716 | "Could not write to the test shard status file \"%s\" " |
| 3717 | "specified by the %s environment variable.\n", |
| 3718 | test_shard_file, kTestShardStatusFile); |
| 3719 | fflush(stdout); |
| 3720 | exit(EXIT_FAILURE); |
| 3721 | } |
| 3722 | fclose(file); |
| 3723 | } |
| 3724 | } |
| 3725 | |
| 3726 | // Checks whether sharding is enabled by examining the relevant |
| 3727 | // environment variable values. If the variables are present, |
| 3728 | // but inconsistent (i.e., shard_index >= total_shards), prints |
| 3729 | // an error and exits. If in_subprocess_for_death_test, sharding is |
| 3730 | // disabled because it must only be applied to the original test |
| 3731 | // process. Otherwise, we could filter out death tests we intended to execute. |
| 3732 | bool ShouldShard(const char* total_shards_env, |
| 3733 | const char* shard_index_env, |
| 3734 | bool in_subprocess_for_death_test) { |
| 3735 | if (in_subprocess_for_death_test) { |
| 3736 | return false; |
| 3737 | } |
| 3738 | |
| 3739 | const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); |
| 3740 | const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); |
| 3741 | |
| 3742 | if (total_shards == -1 && shard_index == -1) { |
| 3743 | return false; |
| 3744 | } else if (total_shards == -1 && shard_index != -1) { |
| 3745 | const Message msg = Message() |
| 3746 | << "Invalid environment variables: you have " |
| 3747 | << kTestShardIndex << " = " << shard_index |
| 3748 | << ", but have left " << kTestTotalShards << " unset.\n"; |
| 3749 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 3750 | fflush(stdout); |
| 3751 | exit(EXIT_FAILURE); |
| 3752 | } else if (total_shards != -1 && shard_index == -1) { |
| 3753 | const Message msg = Message() |
| 3754 | << "Invalid environment variables: you have " |
| 3755 | << kTestTotalShards << " = " << total_shards |
| 3756 | << ", but have left " << kTestShardIndex << " unset.\n"; |
| 3757 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 3758 | fflush(stdout); |
| 3759 | exit(EXIT_FAILURE); |
| 3760 | } else if (shard_index < 0 || shard_index >= total_shards) { |
| 3761 | const Message msg = Message() |
| 3762 | << "Invalid environment variables: we require 0 <= " |
| 3763 | << kTestShardIndex << " < " << kTestTotalShards |
| 3764 | << ", but you have " << kTestShardIndex << "=" << shard_index |
| 3765 | << ", " << kTestTotalShards << "=" << total_shards << ".\n"; |
| 3766 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 3767 | fflush(stdout); |
| 3768 | exit(EXIT_FAILURE); |
| 3769 | } |
| 3770 | |
| 3771 | return total_shards > 1; |
| 3772 | } |
| 3773 | |
| 3774 | // Parses the environment variable var as an Int32. If it is unset, |
| 3775 | // returns default_val. If it is not an Int32, prints an error |
| 3776 | // and aborts. |
| 3777 | Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) { |
| 3778 | const char* str_val = GetEnv(var); |
| 3779 | if (str_val == NULL) { |
| 3780 | return default_val; |
| 3781 | } |
| 3782 | |
| 3783 | Int32 result; |
| 3784 | if (!ParseInt32(Message() << "The value of environment variable " << var, |
| 3785 | str_val, &result)) { |
| 3786 | exit(EXIT_FAILURE); |
| 3787 | } |
| 3788 | return result; |
| 3789 | } |
| 3790 | |
| 3791 | // Given the total number of shards, the shard index, and the test id, |
| 3792 | // returns true iff the test should be run on this shard. The test id is |
| 3793 | // some arbitrary but unique non-negative integer assigned to each test |
| 3794 | // method. Assumes that 0 <= shard_index < total_shards. |
| 3795 | bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { |
| 3796 | return (test_id % total_shards) == shard_index; |
| 3797 | } |
| 3798 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3799 | // Compares the name of each test with the user-specified filter to |
| 3800 | // decide whether the test should be run, then records the result in |
| 3801 | // each TestCase and TestInfo object. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3802 | // If shard_tests == true, further filters tests based on sharding |
| 3803 | // variables in the environment - see |
| 3804 | // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3805 | // Returns the number of tests that should run. |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3806 | int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { |
| 3807 | const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? |
| 3808 | Int32FromEnvOrDie(kTestTotalShards, -1) : -1; |
| 3809 | const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? |
| 3810 | Int32FromEnvOrDie(kTestShardIndex, -1) : -1; |
| 3811 | |
| 3812 | // num_runnable_tests are the number of tests that will |
| 3813 | // run across all shards (i.e., match filter and are not disabled). |
| 3814 | // num_selected_tests are the number of tests to be run on |
| 3815 | // this shard. |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3816 | int num_runnable_tests = 0; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3817 | int num_selected_tests = 0; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3818 | for (const internal::ListNode<TestCase *> *test_case_node = |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3819 | test_cases_.Head(); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3820 | test_case_node != NULL; |
| 3821 | test_case_node = test_case_node->next()) { |
| 3822 | TestCase * const test_case = test_case_node->element(); |
| 3823 | const String &test_case_name = test_case->name(); |
| 3824 | test_case->set_should_run(false); |
| 3825 | |
| 3826 | for (const internal::ListNode<TestInfo *> *test_info_node = |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3827 | test_case->test_info_list().Head(); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3828 | test_info_node != NULL; |
| 3829 | test_info_node = test_info_node->next()) { |
| 3830 | TestInfo * const test_info = test_info_node->element(); |
| 3831 | const String test_name(test_info->name()); |
| 3832 | // A test is disabled if test case name or test name matches |
| 3833 | // kDisableTestFilter. |
| 3834 | const bool is_disabled = |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3835 | internal::UnitTestOptions::MatchesFilter(test_case_name, |
| 3836 | kDisableTestFilter) || |
| 3837 | internal::UnitTestOptions::MatchesFilter(test_name, |
| 3838 | kDisableTestFilter); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3839 | test_info->impl()->set_is_disabled(is_disabled); |
| 3840 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3841 | const bool is_runnable = |
| 3842 | (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3843 | internal::UnitTestOptions::FilterMatchesTest(test_case_name, |
| 3844 | test_name); |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3845 | |
| 3846 | const bool is_selected = is_runnable && |
| 3847 | (shard_tests == IGNORE_SHARDING_PROTOCOL || |
| 3848 | ShouldRunTestOnShard(total_shards, shard_index, |
| 3849 | num_runnable_tests)); |
| 3850 | |
| 3851 | num_runnable_tests += is_runnable; |
| 3852 | num_selected_tests += is_selected; |
| 3853 | |
| 3854 | test_info->impl()->set_should_run(is_selected); |
| 3855 | test_case->set_should_run(test_case->should_run() || is_selected); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3856 | } |
| 3857 | } |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3858 | return num_selected_tests; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3859 | } |
| 3860 | |
| 3861 | // Lists all tests by name. |
| 3862 | void UnitTestImpl::ListAllTests() { |
| 3863 | for (const internal::ListNode<TestCase*>* test_case_node = test_cases_.Head(); |
| 3864 | test_case_node != NULL; |
| 3865 | test_case_node = test_case_node->next()) { |
| 3866 | const TestCase* const test_case = test_case_node->element(); |
| 3867 | |
| 3868 | // Prints the test case name following by an indented list of test nodes. |
| 3869 | printf("%s.\n", test_case->name()); |
| 3870 | |
| 3871 | for (const internal::ListNode<TestInfo*>* test_info_node = |
| 3872 | test_case->test_info_list().Head(); |
| 3873 | test_info_node != NULL; |
| 3874 | test_info_node = test_info_node->next()) { |
| 3875 | const TestInfo* const test_info = test_info_node->element(); |
| 3876 | |
| 3877 | printf(" %s\n", test_info->name()); |
| 3878 | } |
| 3879 | } |
| 3880 | fflush(stdout); |
| 3881 | } |
| 3882 | |
| 3883 | // Sets the unit test result printer. |
| 3884 | // |
| 3885 | // Does nothing if the input and the current printer object are the |
| 3886 | // same; otherwise, deletes the old printer object and makes the |
| 3887 | // input the current printer. |
| 3888 | void UnitTestImpl::set_result_printer( |
| 3889 | UnitTestEventListenerInterface* result_printer) { |
| 3890 | if (result_printer_ != result_printer) { |
| 3891 | delete result_printer_; |
| 3892 | result_printer_ = result_printer; |
| 3893 | } |
| 3894 | } |
| 3895 | |
| 3896 | // Returns the current unit test result printer if it is not NULL; |
| 3897 | // otherwise, creates an appropriate result printer, makes it the |
| 3898 | // current printer, and returns it. |
| 3899 | UnitTestEventListenerInterface* UnitTestImpl::result_printer() { |
| 3900 | if (result_printer_ != NULL) { |
| 3901 | return result_printer_; |
| 3902 | } |
| 3903 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3904 | #if GTEST_HAS_DEATH_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3905 | if (internal_run_death_test_flag_.get() != NULL) { |
| 3906 | result_printer_ = new NullUnitTestResultPrinter; |
| 3907 | return result_printer_; |
| 3908 | } |
| 3909 | #endif // GTEST_HAS_DEATH_TEST |
| 3910 | |
| 3911 | UnitTestEventsRepeater *repeater = new UnitTestEventsRepeater; |
| 3912 | const String& output_format = internal::UnitTestOptions::GetOutputFormat(); |
| 3913 | if (output_format == "xml") { |
| 3914 | repeater->AddListener(new XmlUnitTestResultPrinter( |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 3915 | internal::UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 3916 | } else if (output_format != "") { |
| 3917 | printf("WARNING: unrecognized output format \"%s\" ignored.\n", |
| 3918 | output_format.c_str()); |
| 3919 | fflush(stdout); |
| 3920 | } |
| 3921 | repeater->AddListener(new PrettyUnitTestResultPrinter); |
| 3922 | result_printer_ = repeater; |
| 3923 | return result_printer_; |
| 3924 | } |
| 3925 | |
| 3926 | // Sets the OS stack trace getter. |
| 3927 | // |
| 3928 | // Does nothing if the input and the current OS stack trace getter are |
| 3929 | // the same; otherwise, deletes the old getter and makes the input the |
| 3930 | // current getter. |
| 3931 | void UnitTestImpl::set_os_stack_trace_getter( |
| 3932 | OsStackTraceGetterInterface* getter) { |
| 3933 | if (os_stack_trace_getter_ != getter) { |
| 3934 | delete os_stack_trace_getter_; |
| 3935 | os_stack_trace_getter_ = getter; |
| 3936 | } |
| 3937 | } |
| 3938 | |
| 3939 | // Returns the current OS stack trace getter if it is not NULL; |
| 3940 | // otherwise, creates an OsStackTraceGetter, makes it the current |
| 3941 | // getter, and returns it. |
| 3942 | OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { |
| 3943 | if (os_stack_trace_getter_ == NULL) { |
| 3944 | os_stack_trace_getter_ = new OsStackTraceGetter; |
| 3945 | } |
| 3946 | |
| 3947 | return os_stack_trace_getter_; |
| 3948 | } |
| 3949 | |
| 3950 | // Returns the TestResult for the test that's currently running, or |
| 3951 | // the TestResult for the ad hoc test if no test is running. |
| 3952 | internal::TestResult* UnitTestImpl::current_test_result() { |
| 3953 | return current_test_info_ ? |
| 3954 | current_test_info_->impl()->result() : &ad_hoc_test_result_; |
| 3955 | } |
| 3956 | |
| 3957 | // TestInfoImpl constructor. The new instance assumes ownership of the test |
| 3958 | // factory object. |
| 3959 | TestInfoImpl::TestInfoImpl(TestInfo* parent, |
| 3960 | const char* test_case_name, |
| 3961 | const char* name, |
| 3962 | const char* test_case_comment, |
| 3963 | const char* comment, |
| 3964 | TypeId fixture_class_id, |
| 3965 | internal::TestFactoryBase* factory) : |
| 3966 | parent_(parent), |
| 3967 | test_case_name_(String(test_case_name)), |
| 3968 | name_(String(name)), |
| 3969 | test_case_comment_(String(test_case_comment)), |
| 3970 | comment_(String(comment)), |
| 3971 | fixture_class_id_(fixture_class_id), |
| 3972 | should_run_(false), |
| 3973 | is_disabled_(false), |
| 3974 | factory_(factory) { |
| 3975 | } |
| 3976 | |
| 3977 | // TestInfoImpl destructor. |
| 3978 | TestInfoImpl::~TestInfoImpl() { |
| 3979 | delete factory_; |
| 3980 | } |
| 3981 | |
| 3982 | // Returns the current OS stack trace as a String. |
| 3983 | // |
| 3984 | // The maximum number of stack frames to be included is specified by |
| 3985 | // the gtest_stack_trace_depth flag. The skip_count parameter |
| 3986 | // specifies the number of top frames to be skipped, which doesn't |
| 3987 | // count against the number of frames to be included. |
| 3988 | // |
| 3989 | // For example, if Foo() calls Bar(), which in turn calls |
| 3990 | // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in |
| 3991 | // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. |
| 3992 | String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count) { |
| 3993 | // We pass skip_count + 1 to skip this wrapper function in addition |
| 3994 | // to what the user really wants to skip. |
| 3995 | return unit_test->impl()->CurrentOsStackTraceExceptTop(skip_count + 1); |
| 3996 | } |
| 3997 | |
| 3998 | // Returns the number of failed test parts in the given test result object. |
| 3999 | int GetFailedPartCount(const TestResult* result) { |
| 4000 | return result->failed_part_count(); |
| 4001 | } |
| 4002 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4003 | // Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable |
| 4004 | // code warnings. |
| 4005 | namespace { |
| 4006 | class ClassUniqueToAlwaysTrue {}; |
| 4007 | } |
| 4008 | |
| 4009 | bool AlwaysTrue() { |
| 4010 | #if GTEST_HAS_EXCEPTIONS |
| 4011 | // This condition is always false so AlwaysTrue() never actually throws, |
| 4012 | // but it makes the compiler think that it may throw. |
| 4013 | if (atoi("42") == 36) // NOLINT |
| 4014 | throw ClassUniqueToAlwaysTrue(); |
| 4015 | #endif // GTEST_HAS_EXCEPTIONS |
| 4016 | return true; |
| 4017 | } |
| 4018 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4019 | // Parses a string as a command line flag. The string should have |
| 4020 | // the format "--flag=value". When def_optional is true, the "=value" |
| 4021 | // part can be omitted. |
| 4022 | // |
| 4023 | // Returns the value of the flag, or NULL if the parsing failed. |
| 4024 | const char* ParseFlagValue(const char* str, |
| 4025 | const char* flag, |
| 4026 | bool def_optional) { |
| 4027 | // str and flag must not be NULL. |
| 4028 | if (str == NULL || flag == NULL) return NULL; |
| 4029 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4030 | // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. |
| 4031 | const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4032 | const size_t flag_len = flag_str.GetLength(); |
| 4033 | if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; |
| 4034 | |
| 4035 | // Skips the flag name. |
| 4036 | const char* flag_end = str + flag_len; |
| 4037 | |
| 4038 | // When def_optional is true, it's OK to not have a "=value" part. |
| 4039 | if (def_optional && (flag_end[0] == '\0')) { |
| 4040 | return flag_end; |
| 4041 | } |
| 4042 | |
| 4043 | // If def_optional is true and there are more characters after the |
| 4044 | // flag name, or if def_optional is false, there must be a '=' after |
| 4045 | // the flag name. |
| 4046 | if (flag_end[0] != '=') return NULL; |
| 4047 | |
| 4048 | // Returns the string after "=". |
| 4049 | return flag_end + 1; |
| 4050 | } |
| 4051 | |
| 4052 | // Parses a string for a bool flag, in the form of either |
| 4053 | // "--flag=value" or "--flag". |
| 4054 | // |
| 4055 | // In the former case, the value is taken as true as long as it does |
| 4056 | // not start with '0', 'f', or 'F'. |
| 4057 | // |
| 4058 | // In the latter case, the value is taken as true. |
| 4059 | // |
| 4060 | // On success, stores the value of the flag in *value, and returns |
| 4061 | // true. On failure, returns false without changing *value. |
| 4062 | bool ParseBoolFlag(const char* str, const char* flag, bool* value) { |
| 4063 | // Gets the value of the flag as a string. |
| 4064 | const char* const value_str = ParseFlagValue(str, flag, true); |
| 4065 | |
| 4066 | // Aborts if the parsing failed. |
| 4067 | if (value_str == NULL) return false; |
| 4068 | |
| 4069 | // Converts the string value to a bool. |
| 4070 | *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); |
| 4071 | return true; |
| 4072 | } |
| 4073 | |
| 4074 | // Parses a string for an Int32 flag, in the form of |
| 4075 | // "--flag=value". |
| 4076 | // |
| 4077 | // On success, stores the value of the flag in *value, and returns |
| 4078 | // true. On failure, returns false without changing *value. |
| 4079 | bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { |
| 4080 | // Gets the value of the flag as a string. |
| 4081 | const char* const value_str = ParseFlagValue(str, flag, false); |
| 4082 | |
| 4083 | // Aborts if the parsing failed. |
| 4084 | if (value_str == NULL) return false; |
| 4085 | |
| 4086 | // Sets *value to the value of the flag. |
| 4087 | return ParseInt32(Message() << "The value of flag --" << flag, |
| 4088 | value_str, value); |
| 4089 | } |
| 4090 | |
| 4091 | // Parses a string for a string flag, in the form of |
| 4092 | // "--flag=value". |
| 4093 | // |
| 4094 | // On success, stores the value of the flag in *value, and returns |
| 4095 | // true. On failure, returns false without changing *value. |
| 4096 | bool ParseStringFlag(const char* str, const char* flag, String* value) { |
| 4097 | // Gets the value of the flag as a string. |
| 4098 | const char* const value_str = ParseFlagValue(str, flag, false); |
| 4099 | |
| 4100 | // Aborts if the parsing failed. |
| 4101 | if (value_str == NULL) return false; |
| 4102 | |
| 4103 | // Sets *value to the value of the flag. |
| 4104 | *value = value_str; |
| 4105 | return true; |
| 4106 | } |
| 4107 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4108 | // Prints a string containing code-encoded text. The following escape |
| 4109 | // sequences can be used in the string to control the text color: |
| 4110 | // |
| 4111 | // @@ prints a single '@' character. |
| 4112 | // @R changes the color to red. |
| 4113 | // @G changes the color to green. |
| 4114 | // @Y changes the color to yellow. |
| 4115 | // @D changes to the default terminal text color. |
| 4116 | // |
| 4117 | // TODO(wan@google.com): Write tests for this once we add stdout |
| 4118 | // capturing to Google Test. |
| 4119 | static void PrintColorEncoded(const char* str) { |
| 4120 | GTestColor color = COLOR_DEFAULT; // The current color. |
| 4121 | |
| 4122 | // Conceptually, we split the string into segments divided by escape |
| 4123 | // sequences. Then we print one segment at a time. At the end of |
| 4124 | // each iteration, the str pointer advances to the beginning of the |
| 4125 | // next segment. |
| 4126 | for (;;) { |
| 4127 | const char* p = strchr(str, '@'); |
| 4128 | if (p == NULL) { |
| 4129 | ColoredPrintf(color, "%s", str); |
| 4130 | return; |
| 4131 | } |
| 4132 | |
| 4133 | ColoredPrintf(color, "%s", String(str, p - str).c_str()); |
| 4134 | |
| 4135 | const char ch = p[1]; |
| 4136 | str = p + 2; |
| 4137 | if (ch == '@') { |
| 4138 | ColoredPrintf(color, "@"); |
| 4139 | } else if (ch == 'D') { |
| 4140 | color = COLOR_DEFAULT; |
| 4141 | } else if (ch == 'R') { |
| 4142 | color = COLOR_RED; |
| 4143 | } else if (ch == 'G') { |
| 4144 | color = COLOR_GREEN; |
| 4145 | } else if (ch == 'Y') { |
| 4146 | color = COLOR_YELLOW; |
| 4147 | } else { |
| 4148 | --str; |
| 4149 | } |
| 4150 | } |
| 4151 | } |
| 4152 | |
| 4153 | static const char kColorEncodedHelpMessage[] = |
| 4154 | "This program contains tests written using " GTEST_NAME_ ". You can use the\n" |
| 4155 | "following command line flags to control its behavior:\n" |
| 4156 | "\n" |
| 4157 | "Test Selection:\n" |
| 4158 | " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" |
| 4159 | " List the names of all tests instead of running them. The name of\n" |
| 4160 | " TEST(Foo, Bar) is \"Foo.Bar\".\n" |
| 4161 | " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" |
| 4162 | "[@G-@YNEGATIVE_PATTERNS]@D\n" |
| 4163 | " Run only the tests whose name matches one of the positive patterns but\n" |
| 4164 | " none of the negative patterns. '?' matches any single character; '*'\n" |
| 4165 | " matches any substring; ':' separates two patterns.\n" |
| 4166 | " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" |
| 4167 | " Run all disabled tests too.\n" |
| 4168 | " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" |
| 4169 | " Run the tests repeatedly; use a negative count to repeat forever.\n" |
| 4170 | "\n" |
| 4171 | "Test Output:\n" |
| 4172 | " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" |
| 4173 | " Enable/disable colored output. The default is @Gauto@D.\n" |
| 4174 | " -@G-" GTEST_FLAG_PREFIX_ "print_time@D\n" |
| 4175 | " Print the elapsed time of each test.\n" |
| 4176 | " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" |
| 4177 | GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" |
| 4178 | " Generate an XML report in the given directory or with the given file\n" |
| 4179 | " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" |
| 4180 | "\n" |
| 4181 | "Failure Behavior:\n" |
| 4182 | " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" |
| 4183 | " Turn assertion failures into debugger break-points.\n" |
| 4184 | " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" |
| 4185 | " Turn assertion failures into C++ exceptions.\n" |
| 4186 | #if GTEST_OS_WINDOWS |
| 4187 | " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n" |
| 4188 | " Suppress pop-ups caused by exceptions.\n" |
| 4189 | #endif // GTEST_OS_WINDOWS |
| 4190 | "\n" |
| 4191 | "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " |
| 4192 | "the corresponding\n" |
| 4193 | "environment variable of a flag (all letters in upper-case). For example, to\n" |
| 4194 | "print the elapsed time, you can either specify @G--" GTEST_FLAG_PREFIX_ |
| 4195 | "print_time@D or set the\n" |
| 4196 | "@G" GTEST_FLAG_PREFIX_UPPER_ "PRINT_TIME@D environment variable to a " |
| 4197 | "non-zero value.\n" |
| 4198 | "\n" |
| 4199 | "For more information, please read the " GTEST_NAME_ " documentation at\n" |
| 4200 | "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" |
| 4201 | "(not one in your own code or tests), please report it to\n" |
| 4202 | "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; |
| 4203 | |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4204 | // Parses the command line for Google Test flags, without initializing |
| 4205 | // other parts of Google Test. The type parameter CharType can be |
| 4206 | // instantiated to either char or wchar_t. |
| 4207 | template <typename CharType> |
| 4208 | void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { |
| 4209 | for (int i = 1; i < *argc; i++) { |
| 4210 | const String arg_string = StreamableToString(argv[i]); |
| 4211 | const char* const arg = arg_string.c_str(); |
| 4212 | |
| 4213 | using internal::ParseBoolFlag; |
| 4214 | using internal::ParseInt32Flag; |
| 4215 | using internal::ParseStringFlag; |
| 4216 | |
| 4217 | // Do we see a Google Test flag? |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4218 | if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, |
| 4219 | >EST_FLAG(also_run_disabled_tests)) || |
| 4220 | ParseBoolFlag(arg, kBreakOnFailureFlag, |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4221 | >EST_FLAG(break_on_failure)) || |
| 4222 | ParseBoolFlag(arg, kCatchExceptionsFlag, |
| 4223 | >EST_FLAG(catch_exceptions)) || |
| 4224 | ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || |
| 4225 | ParseStringFlag(arg, kDeathTestStyleFlag, |
| 4226 | >EST_FLAG(death_test_style)) || |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4227 | ParseBoolFlag(arg, kDeathTestUseFork, |
| 4228 | >EST_FLAG(death_test_use_fork)) || |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4229 | ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || |
| 4230 | ParseStringFlag(arg, kInternalRunDeathTestFlag, |
| 4231 | >EST_FLAG(internal_run_death_test)) || |
| 4232 | ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || |
| 4233 | ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || |
| 4234 | ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4235 | ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || |
| 4236 | ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)) |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4237 | ) { |
| 4238 | // Yes. Shift the remainder of the argv list left by one. Note |
| 4239 | // that argv has (*argc + 1) elements, the last one always being |
| 4240 | // NULL. The following loop moves the trailing NULL element as |
| 4241 | // well. |
| 4242 | for (int j = i; j != *argc; j++) { |
| 4243 | argv[j] = argv[j + 1]; |
| 4244 | } |
| 4245 | |
| 4246 | // Decrements the argument count. |
| 4247 | (*argc)--; |
| 4248 | |
| 4249 | // We also need to decrement the iterator as we just removed |
| 4250 | // an element. |
| 4251 | i--; |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4252 | } else if (arg_string == "--help" || arg_string == "-h" || |
| 4253 | arg_string == "-?" || arg_string == "/?") { |
| 4254 | g_help_flag = true; |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4255 | } |
| 4256 | } |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4257 | |
| 4258 | if (g_help_flag) { |
| 4259 | // We print the help here instead of in RUN_ALL_TESTS(), as the |
| 4260 | // latter may not be called at all if the user is using Google |
| 4261 | // Test with another testing framework. |
| 4262 | PrintColorEncoded(kColorEncodedHelpMessage); |
| 4263 | } |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4264 | } |
| 4265 | |
| 4266 | // Parses the command line for Google Test flags, without initializing |
| 4267 | // other parts of Google Test. |
| 4268 | void ParseGoogleTestFlagsOnly(int* argc, char** argv) { |
| 4269 | ParseGoogleTestFlagsOnlyImpl(argc, argv); |
| 4270 | } |
| 4271 | void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { |
| 4272 | ParseGoogleTestFlagsOnlyImpl(argc, argv); |
| 4273 | } |
| 4274 | |
| 4275 | // The internal implementation of InitGoogleTest(). |
| 4276 | // |
| 4277 | // The type parameter CharType can be instantiated to either char or |
| 4278 | // wchar_t. |
| 4279 | template <typename CharType> |
| 4280 | void InitGoogleTestImpl(int* argc, CharType** argv) { |
| 4281 | g_init_gtest_count++; |
| 4282 | |
| 4283 | // We don't want to run the initialization code twice. |
| 4284 | if (g_init_gtest_count != 1) return; |
| 4285 | |
| 4286 | if (*argc <= 0) return; |
| 4287 | |
| 4288 | internal::g_executable_path = internal::StreamableToString(argv[0]); |
| 4289 | |
Benjamin Kramer | e4b9c93 | 2010-06-02 22:01:25 +0000 | [diff] [blame^] | 4290 | #if GTEST_HAS_DEATH_TEST |
Misha Brukman | 7ae6ff4 | 2008-12-31 17:34:06 +0000 | [diff] [blame] | 4291 | g_argvs.clear(); |
| 4292 | for (int i = 0; i != *argc; i++) { |
| 4293 | g_argvs.push_back(StreamableToString(argv[i])); |
| 4294 | } |
| 4295 | #endif // GTEST_HAS_DEATH_TEST |
| 4296 | |
| 4297 | ParseGoogleTestFlagsOnly(argc, argv); |
| 4298 | } |
| 4299 | |
| 4300 | } // namespace internal |
| 4301 | |
| 4302 | // Initializes Google Test. This must be called before calling |
| 4303 | // RUN_ALL_TESTS(). In particular, it parses a command line for the |
| 4304 | // flags that Google Test recognizes. Whenever a Google Test flag is |
| 4305 | // seen, it is removed from argv, and *argc is decremented. |
| 4306 | // |
| 4307 | // No value is returned. Instead, the Google Test flag variables are |
| 4308 | // updated. |
| 4309 | // |
| 4310 | // Calling the function for the second time has no user-visible effect. |
| 4311 | void InitGoogleTest(int* argc, char** argv) { |
| 4312 | internal::InitGoogleTestImpl(argc, argv); |
| 4313 | } |
| 4314 | |
| 4315 | // This overloaded version can be used in Windows programs compiled in |
| 4316 | // UNICODE mode. |
| 4317 | void InitGoogleTest(int* argc, wchar_t** argv) { |
| 4318 | internal::InitGoogleTestImpl(argc, argv); |
| 4319 | } |
| 4320 | |
| 4321 | } // namespace testing |