Brian Silverman | f7f267a | 2017-02-04 16:16:08 -0800 | [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 <time.h> |
| 43 | #include <wchar.h> |
| 44 | #include <wctype.h> |
| 45 | |
| 46 | #include <algorithm> |
| 47 | #include <iomanip> |
| 48 | #include <limits> |
| 49 | #include <ostream> // NOLINT |
| 50 | #include <sstream> |
| 51 | #include <vector> |
| 52 | |
| 53 | #pragma GCC diagnostic ignored "-Wmissing-field-initializers" |
| 54 | |
| 55 | #if GTEST_OS_LINUX |
| 56 | |
| 57 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 58 | // gettimeofday(). |
| 59 | # define GTEST_HAS_GETTIMEOFDAY_ 1 |
| 60 | |
| 61 | # include <fcntl.h> // NOLINT |
| 62 | # include <limits.h> // NOLINT |
| 63 | # include <sched.h> // NOLINT |
| 64 | // Declares vsnprintf(). This header is not available on Windows. |
| 65 | # include <strings.h> // NOLINT |
| 66 | # include <sys/mman.h> // NOLINT |
| 67 | # include <sys/time.h> // NOLINT |
| 68 | # include <unistd.h> // NOLINT |
| 69 | # include <string> |
| 70 | |
| 71 | #elif GTEST_OS_SYMBIAN |
| 72 | # define GTEST_HAS_GETTIMEOFDAY_ 1 |
| 73 | # include <sys/time.h> // NOLINT |
| 74 | |
| 75 | #elif GTEST_OS_ZOS |
| 76 | # define GTEST_HAS_GETTIMEOFDAY_ 1 |
| 77 | # include <sys/time.h> // NOLINT |
| 78 | |
| 79 | // On z/OS we additionally need strings.h for strcasecmp. |
| 80 | # include <strings.h> // NOLINT |
| 81 | |
| 82 | #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. |
| 83 | |
| 84 | # include <windows.h> // NOLINT |
| 85 | |
| 86 | #elif GTEST_OS_WINDOWS // We are on Windows proper. |
| 87 | |
| 88 | # include <io.h> // NOLINT |
| 89 | # include <sys/timeb.h> // NOLINT |
| 90 | # include <sys/types.h> // NOLINT |
| 91 | # include <sys/stat.h> // NOLINT |
| 92 | |
| 93 | # if GTEST_OS_WINDOWS_MINGW |
| 94 | // MinGW has gettimeofday() but not _ftime64(). |
| 95 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 96 | // gettimeofday(). |
| 97 | // TODO(kenton@google.com): There are other ways to get the time on |
| 98 | // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW |
| 99 | // supports these. consider using them instead. |
| 100 | # define GTEST_HAS_GETTIMEOFDAY_ 1 |
| 101 | # include <sys/time.h> // NOLINT |
| 102 | # endif // GTEST_OS_WINDOWS_MINGW |
| 103 | |
| 104 | // cpplint thinks that the header is already included, so we want to |
| 105 | // silence it. |
| 106 | # include <windows.h> // NOLINT |
| 107 | |
| 108 | #else |
| 109 | |
| 110 | // Assume other platforms have gettimeofday(). |
| 111 | // TODO(kenton@google.com): Use autoconf to detect availability of |
| 112 | // gettimeofday(). |
| 113 | # define GTEST_HAS_GETTIMEOFDAY_ 1 |
| 114 | |
| 115 | // cpplint thinks that the header is already included, so we want to |
| 116 | // silence it. |
| 117 | # include <sys/time.h> // NOLINT |
| 118 | # include <unistd.h> // NOLINT |
| 119 | |
| 120 | #endif // GTEST_OS_LINUX |
| 121 | |
| 122 | #if GTEST_HAS_EXCEPTIONS |
| 123 | # include <stdexcept> |
| 124 | #endif |
| 125 | |
| 126 | #if GTEST_CAN_STREAM_RESULTS_ |
| 127 | # include <arpa/inet.h> // NOLINT |
| 128 | # include <netdb.h> // NOLINT |
| 129 | #endif |
| 130 | |
| 131 | // Indicates that this translation unit is part of Google Test's |
| 132 | // implementation. It must come before gtest-internal-inl.h is |
| 133 | // included, or there will be a compiler error. This trick is to |
| 134 | // prevent a user from accidentally including gtest-internal-inl.h in |
| 135 | // his code. |
| 136 | #define GTEST_IMPLEMENTATION_ 1 |
| 137 | #include "src/gtest-internal-inl.h" |
| 138 | #undef GTEST_IMPLEMENTATION_ |
| 139 | |
| 140 | #if GTEST_OS_WINDOWS |
| 141 | # define vsnprintf _vsnprintf |
| 142 | #endif // GTEST_OS_WINDOWS |
| 143 | |
| 144 | namespace testing { |
| 145 | |
| 146 | using internal::CountIf; |
| 147 | using internal::ForEach; |
| 148 | using internal::GetElementOr; |
| 149 | using internal::Shuffle; |
| 150 | |
| 151 | // Constants. |
| 152 | |
| 153 | // A test whose test case name or test name matches this filter is |
| 154 | // disabled and not run. |
| 155 | static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; |
| 156 | |
| 157 | // A test case whose name matches this filter is considered a death |
| 158 | // test case and will be run before test cases whose name doesn't |
| 159 | // match this filter. |
| 160 | static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; |
| 161 | |
| 162 | // A test filter that matches everything. |
| 163 | static const char kUniversalFilter[] = "*"; |
| 164 | |
| 165 | // The default output file for XML output. |
| 166 | static const char kDefaultOutputFile[] = "test_detail.xml"; |
| 167 | |
| 168 | // The environment variable name for the test shard index. |
| 169 | static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; |
| 170 | // The environment variable name for the total number of test shards. |
| 171 | static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; |
| 172 | // The environment variable name for the test shard status file. |
| 173 | static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; |
| 174 | |
| 175 | namespace internal { |
| 176 | |
| 177 | // The text used in failure messages to indicate the start of the |
| 178 | // stack trace. |
| 179 | const char kStackTraceMarker[] = "\nStack trace:\n"; |
| 180 | |
| 181 | // g_help_flag is true iff the --help flag or an equivalent form is |
| 182 | // specified on the command line. |
| 183 | bool g_help_flag = false; |
| 184 | |
| 185 | } // namespace internal |
| 186 | |
| 187 | static const char* GetDefaultFilter() { |
| 188 | return kUniversalFilter; |
| 189 | } |
| 190 | |
| 191 | GTEST_DEFINE_bool_( |
| 192 | also_run_disabled_tests, |
| 193 | internal::BoolFromGTestEnv("also_run_disabled_tests", false), |
| 194 | "Run disabled tests too, in addition to the tests normally being run."); |
| 195 | |
| 196 | GTEST_DEFINE_bool_( |
| 197 | break_on_failure, |
| 198 | internal::BoolFromGTestEnv("break_on_failure", false), |
| 199 | "True iff a failed assertion should be a debugger break-point."); |
| 200 | |
| 201 | GTEST_DEFINE_bool_( |
| 202 | catch_exceptions, |
| 203 | internal::BoolFromGTestEnv("catch_exceptions", true), |
| 204 | "True iff " GTEST_NAME_ |
| 205 | " should catch exceptions and treat them as test failures."); |
| 206 | |
| 207 | GTEST_DEFINE_string_( |
| 208 | color, |
| 209 | internal::StringFromGTestEnv("color", "auto"), |
| 210 | "Whether to use colors in the output. Valid values: yes, no, " |
| 211 | "and auto. 'auto' means to use colors if the output is " |
| 212 | "being sent to a terminal and the TERM environment variable " |
| 213 | "is set to a terminal type that supports colors."); |
| 214 | |
| 215 | GTEST_DEFINE_string_( |
| 216 | filter, |
| 217 | internal::StringFromGTestEnv("filter", GetDefaultFilter()), |
| 218 | "A colon-separated list of glob (not regex) patterns " |
| 219 | "for filtering the tests to run, optionally followed by a " |
| 220 | "'-' and a : separated list of negative patterns (tests to " |
| 221 | "exclude). A test is run if it matches one of the positive " |
| 222 | "patterns and does not match any of the negative patterns."); |
| 223 | |
| 224 | GTEST_DEFINE_bool_(list_tests, false, |
| 225 | "List all tests without running them."); |
| 226 | |
| 227 | GTEST_DEFINE_string_( |
| 228 | output, |
| 229 | internal::StringFromGTestEnv("output", ""), |
| 230 | "A format (currently must be \"xml\"), optionally followed " |
| 231 | "by a colon and an output file name or directory. A directory " |
| 232 | "is indicated by a trailing pathname separator. " |
| 233 | "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " |
| 234 | "If a directory is specified, output files will be created " |
| 235 | "within that directory, with file-names based on the test " |
| 236 | "executable's name and, if necessary, made unique by adding " |
| 237 | "digits."); |
| 238 | |
| 239 | GTEST_DEFINE_bool_( |
| 240 | print_time, |
| 241 | internal::BoolFromGTestEnv("print_time", true), |
| 242 | "True iff " GTEST_NAME_ |
| 243 | " should display elapsed time in text output."); |
| 244 | |
| 245 | GTEST_DEFINE_int32_( |
| 246 | random_seed, |
| 247 | internal::Int32FromGTestEnv("random_seed", 0), |
| 248 | "Random number seed to use when shuffling test orders. Must be in range " |
| 249 | "[1, 99999], or 0 to use a seed based on the current time."); |
| 250 | |
| 251 | GTEST_DEFINE_int32_( |
| 252 | repeat, |
| 253 | internal::Int32FromGTestEnv("repeat", 1), |
| 254 | "How many times to repeat each test. Specify a negative number " |
| 255 | "for repeating forever. Useful for shaking out flaky tests."); |
| 256 | |
| 257 | GTEST_DEFINE_bool_( |
| 258 | show_internal_stack_frames, false, |
| 259 | "True iff " GTEST_NAME_ " should include internal stack frames when " |
| 260 | "printing test failure stack traces."); |
| 261 | |
| 262 | GTEST_DEFINE_bool_( |
| 263 | shuffle, |
| 264 | internal::BoolFromGTestEnv("shuffle", false), |
| 265 | "True iff " GTEST_NAME_ |
| 266 | " should randomize tests' order on every run."); |
| 267 | |
| 268 | GTEST_DEFINE_int32_( |
| 269 | stack_trace_depth, |
| 270 | internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), |
| 271 | "The maximum number of stack frames to print when an " |
| 272 | "assertion fails. The valid range is 0 through 100, inclusive."); |
| 273 | |
| 274 | GTEST_DEFINE_string_( |
| 275 | stream_result_to, |
| 276 | internal::StringFromGTestEnv("stream_result_to", ""), |
| 277 | "This flag specifies the host name and the port number on which to stream " |
| 278 | "test results. Example: \"localhost:555\". The flag is effective only on " |
| 279 | "Linux."); |
| 280 | |
| 281 | GTEST_DEFINE_bool_( |
| 282 | throw_on_failure, |
| 283 | internal::BoolFromGTestEnv("throw_on_failure", false), |
| 284 | "When this flag is specified, a failed assertion will throw an exception " |
| 285 | "if exceptions are enabled or exit the program with a non-zero code " |
| 286 | "otherwise."); |
| 287 | |
| 288 | namespace internal { |
| 289 | |
| 290 | // Generates a random number from [0, range), using a Linear |
| 291 | // Congruential Generator (LCG). Crashes if 'range' is 0 or greater |
| 292 | // than kMaxRange. |
| 293 | UInt32 Random::Generate(UInt32 range) { |
| 294 | // These constants are the same as are used in glibc's rand(3). |
| 295 | state_ = (1103515245U*state_ + 12345U) % kMaxRange; |
| 296 | |
| 297 | GTEST_CHECK_(range > 0) |
| 298 | << "Cannot generate a number in the range [0, 0)."; |
| 299 | GTEST_CHECK_(range <= kMaxRange) |
| 300 | << "Generation of a number in [0, " << range << ") was requested, " |
| 301 | << "but this can only generate numbers in [0, " << kMaxRange << ")."; |
| 302 | |
| 303 | // Converting via modulus introduces a bit of downward bias, but |
| 304 | // it's simple, and a linear congruential generator isn't too good |
| 305 | // to begin with. |
| 306 | return state_ % range; |
| 307 | } |
| 308 | |
| 309 | // GTestIsInitialized() returns true iff the user has initialized |
| 310 | // Google Test. Useful for catching the user mistake of not initializing |
| 311 | // Google Test before calling RUN_ALL_TESTS(). |
| 312 | // |
| 313 | // A user must call testing::InitGoogleTest() to initialize Google |
| 314 | // Test. g_init_gtest_count is set to the number of times |
| 315 | // InitGoogleTest() has been called. We don't protect this variable |
| 316 | // under a mutex as it is only accessed in the main thread. |
| 317 | GTEST_API_ int g_init_gtest_count = 0; |
| 318 | static bool GTestIsInitialized() { return g_init_gtest_count != 0; } |
| 319 | |
| 320 | // Iterates over a vector of TestCases, keeping a running sum of the |
| 321 | // results of calling a given int-returning method on each. |
| 322 | // Returns the sum. |
| 323 | static int SumOverTestCaseList(const std::vector<TestCase*>& case_list, |
| 324 | int (TestCase::*method)() const) { |
| 325 | int sum = 0; |
| 326 | for (size_t i = 0; i < case_list.size(); i++) { |
| 327 | sum += (case_list[i]->*method)(); |
| 328 | } |
| 329 | return sum; |
| 330 | } |
| 331 | |
| 332 | // Returns true iff the test case passed. |
| 333 | static bool TestCasePassed(const TestCase* test_case) { |
| 334 | return test_case->should_run() && test_case->Passed(); |
| 335 | } |
| 336 | |
| 337 | // Returns true iff the test case failed. |
| 338 | static bool TestCaseFailed(const TestCase* test_case) { |
| 339 | return test_case->should_run() && test_case->Failed(); |
| 340 | } |
| 341 | |
| 342 | // Returns true iff test_case contains at least one test that should |
| 343 | // run. |
| 344 | static bool ShouldRunTestCase(const TestCase* test_case) { |
| 345 | return test_case->should_run(); |
| 346 | } |
| 347 | |
| 348 | // AssertHelper constructor. |
| 349 | AssertHelper::AssertHelper(TestPartResult::Type type, |
| 350 | const char* file, |
| 351 | int line, |
| 352 | const char* message) |
| 353 | : data_(new AssertHelperData(type, file, line, message)) { |
| 354 | } |
| 355 | |
| 356 | AssertHelper::~AssertHelper() { |
| 357 | delete data_; |
| 358 | } |
| 359 | |
| 360 | // Message assignment, for assertion streaming support. |
| 361 | void AssertHelper::operator=(const Message& message) const { |
| 362 | UnitTest::GetInstance()-> |
| 363 | AddTestPartResult(data_->type, data_->file, data_->line, |
| 364 | AppendUserMessage(data_->message, message), |
| 365 | UnitTest::GetInstance()->impl() |
| 366 | ->CurrentOsStackTraceExceptTop(1) |
| 367 | // Skips the stack frame for this function itself. |
| 368 | ); // NOLINT |
| 369 | } |
| 370 | |
| 371 | // Mutex for linked pointers. |
| 372 | GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); |
| 373 | |
| 374 | // Application pathname gotten in InitGoogleTest. |
| 375 | std::string g_executable_path; |
| 376 | |
| 377 | // Returns the current application's name, removing directory path if that |
| 378 | // is present. |
| 379 | FilePath GetCurrentExecutableName() { |
| 380 | FilePath result; |
| 381 | |
| 382 | #if GTEST_OS_WINDOWS |
| 383 | result.Set(FilePath(g_executable_path).RemoveExtension("exe")); |
| 384 | #else |
| 385 | result.Set(FilePath(g_executable_path)); |
| 386 | #endif // GTEST_OS_WINDOWS |
| 387 | |
| 388 | return result.RemoveDirectoryName(); |
| 389 | } |
| 390 | |
| 391 | // Functions for processing the gtest_output flag. |
| 392 | |
| 393 | // Returns the output format, or "" for normal printed output. |
| 394 | std::string UnitTestOptions::GetOutputFormat() { |
| 395 | const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); |
| 396 | if (gtest_output_flag == NULL) return std::string(""); |
| 397 | |
| 398 | const char* const colon = strchr(gtest_output_flag, ':'); |
| 399 | return (colon == NULL) ? |
| 400 | std::string(gtest_output_flag) : |
| 401 | std::string(gtest_output_flag, colon - gtest_output_flag); |
| 402 | } |
| 403 | |
| 404 | // Returns the name of the requested output file, or the default if none |
| 405 | // was explicitly specified. |
| 406 | std::string UnitTestOptions::GetAbsolutePathToOutputFile() { |
| 407 | const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); |
| 408 | if (gtest_output_flag == NULL) |
| 409 | return ""; |
| 410 | |
| 411 | const char* const colon = strchr(gtest_output_flag, ':'); |
| 412 | if (colon == NULL) |
| 413 | return internal::FilePath::ConcatPaths( |
| 414 | internal::FilePath( |
| 415 | UnitTest::GetInstance()->original_working_dir()), |
| 416 | internal::FilePath(kDefaultOutputFile)).string(); |
| 417 | |
| 418 | internal::FilePath output_name(colon + 1); |
| 419 | if (!output_name.IsAbsolutePath()) |
| 420 | // TODO(wan@google.com): on Windows \some\path is not an absolute |
| 421 | // path (as its meaning depends on the current drive), yet the |
| 422 | // following logic for turning it into an absolute path is wrong. |
| 423 | // Fix it. |
| 424 | output_name = internal::FilePath::ConcatPaths( |
| 425 | internal::FilePath(UnitTest::GetInstance()->original_working_dir()), |
| 426 | internal::FilePath(colon + 1)); |
| 427 | |
| 428 | if (!output_name.IsDirectory()) |
| 429 | return output_name.string(); |
| 430 | |
| 431 | internal::FilePath result(internal::FilePath::GenerateUniqueFileName( |
| 432 | output_name, internal::GetCurrentExecutableName(), |
| 433 | GetOutputFormat().c_str())); |
| 434 | return result.string(); |
| 435 | } |
| 436 | |
| 437 | // Returns true iff the wildcard pattern matches the string. The |
| 438 | // first ':' or '\0' character in pattern marks the end of it. |
| 439 | // |
| 440 | // This recursive algorithm isn't very efficient, but is clear and |
| 441 | // works well enough for matching test names, which are short. |
| 442 | bool UnitTestOptions::PatternMatchesString(const char *pattern, |
| 443 | const char *str) { |
| 444 | switch (*pattern) { |
| 445 | case '\0': |
| 446 | case ':': // Either ':' or '\0' marks the end of the pattern. |
| 447 | return *str == '\0'; |
| 448 | case '?': // Matches any single character. |
| 449 | return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); |
| 450 | case '*': // Matches any string (possibly empty) of characters. |
| 451 | return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || |
| 452 | PatternMatchesString(pattern + 1, str); |
| 453 | default: // Non-special character. Matches itself. |
| 454 | return *pattern == *str && |
| 455 | PatternMatchesString(pattern + 1, str + 1); |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | bool UnitTestOptions::MatchesFilter( |
| 460 | const std::string& name, const char* filter) { |
| 461 | const char *cur_pattern = filter; |
| 462 | for (;;) { |
| 463 | if (PatternMatchesString(cur_pattern, name.c_str())) { |
| 464 | return true; |
| 465 | } |
| 466 | |
| 467 | // Finds the next pattern in the filter. |
| 468 | cur_pattern = strchr(cur_pattern, ':'); |
| 469 | |
| 470 | // Returns if no more pattern can be found. |
| 471 | if (cur_pattern == NULL) { |
| 472 | return false; |
| 473 | } |
| 474 | |
| 475 | // Skips the pattern separater (the ':' character). |
| 476 | cur_pattern++; |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | // Returns true iff the user-specified filter matches the test case |
| 481 | // name and the test name. |
| 482 | bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, |
| 483 | const std::string &test_name) { |
| 484 | const std::string& full_name = test_case_name + "." + test_name.c_str(); |
| 485 | |
| 486 | // Split --gtest_filter at '-', if there is one, to separate into |
| 487 | // positive filter and negative filter portions |
| 488 | const char* const p = GTEST_FLAG(filter).c_str(); |
| 489 | const char* const dash = strchr(p, '-'); |
| 490 | std::string positive; |
| 491 | std::string negative; |
| 492 | if (dash == NULL) { |
| 493 | positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter |
| 494 | negative = ""; |
| 495 | } else { |
| 496 | positive = std::string(p, dash); // Everything up to the dash |
| 497 | negative = std::string(dash + 1); // Everything after the dash |
| 498 | if (positive.empty()) { |
| 499 | // Treat '-test1' as the same as '*-test1' |
| 500 | positive = kUniversalFilter; |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | // A filter is a colon-separated list of patterns. It matches a |
| 505 | // test if any pattern in it matches the test. |
| 506 | return (MatchesFilter(full_name, positive.c_str()) && |
| 507 | !MatchesFilter(full_name, negative.c_str())); |
| 508 | } |
| 509 | |
| 510 | #if GTEST_HAS_SEH |
| 511 | // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the |
| 512 | // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. |
| 513 | // This function is useful as an __except condition. |
| 514 | int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { |
| 515 | // Google Test should handle a SEH exception if: |
| 516 | // 1. the user wants it to, AND |
| 517 | // 2. this is not a breakpoint exception, AND |
| 518 | // 3. this is not a C++ exception (VC++ implements them via SEH, |
| 519 | // apparently). |
| 520 | // |
| 521 | // SEH exception code for C++ exceptions. |
| 522 | // (see http://support.microsoft.com/kb/185294 for more information). |
| 523 | const DWORD kCxxExceptionCode = 0xe06d7363; |
| 524 | |
| 525 | bool should_handle = true; |
| 526 | |
| 527 | if (!GTEST_FLAG(catch_exceptions)) |
| 528 | should_handle = false; |
| 529 | else if (exception_code == EXCEPTION_BREAKPOINT) |
| 530 | should_handle = false; |
| 531 | else if (exception_code == kCxxExceptionCode) |
| 532 | should_handle = false; |
| 533 | |
| 534 | return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; |
| 535 | } |
| 536 | #endif // GTEST_HAS_SEH |
| 537 | |
| 538 | } // namespace internal |
| 539 | |
| 540 | // The c'tor sets this object as the test part result reporter used by |
| 541 | // Google Test. The 'result' parameter specifies where to report the |
| 542 | // results. Intercepts only failures from the current thread. |
| 543 | ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( |
| 544 | TestPartResultArray* result) |
| 545 | : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), |
| 546 | result_(result) { |
| 547 | Init(); |
| 548 | } |
| 549 | |
| 550 | // The c'tor sets this object as the test part result reporter used by |
| 551 | // Google Test. The 'result' parameter specifies where to report the |
| 552 | // results. |
| 553 | ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( |
| 554 | InterceptMode intercept_mode, TestPartResultArray* result) |
| 555 | : intercept_mode_(intercept_mode), |
| 556 | result_(result) { |
| 557 | Init(); |
| 558 | } |
| 559 | |
| 560 | void ScopedFakeTestPartResultReporter::Init() { |
| 561 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 562 | if (intercept_mode_ == INTERCEPT_ALL_THREADS) { |
| 563 | old_reporter_ = impl->GetGlobalTestPartResultReporter(); |
| 564 | impl->SetGlobalTestPartResultReporter(this); |
| 565 | } else { |
| 566 | old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); |
| 567 | impl->SetTestPartResultReporterForCurrentThread(this); |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | // The d'tor restores the test part result reporter used by Google Test |
| 572 | // before. |
| 573 | ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { |
| 574 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 575 | if (intercept_mode_ == INTERCEPT_ALL_THREADS) { |
| 576 | impl->SetGlobalTestPartResultReporter(old_reporter_); |
| 577 | } else { |
| 578 | impl->SetTestPartResultReporterForCurrentThread(old_reporter_); |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | // Increments the test part result count and remembers the result. |
| 583 | // This method is from the TestPartResultReporterInterface interface. |
| 584 | void ScopedFakeTestPartResultReporter::ReportTestPartResult( |
| 585 | const TestPartResult& result) { |
| 586 | result_->Append(result); |
| 587 | } |
| 588 | |
| 589 | namespace internal { |
| 590 | |
| 591 | // Returns the type ID of ::testing::Test. We should always call this |
| 592 | // instead of GetTypeId< ::testing::Test>() to get the type ID of |
| 593 | // testing::Test. This is to work around a suspected linker bug when |
| 594 | // using Google Test as a framework on Mac OS X. The bug causes |
| 595 | // GetTypeId< ::testing::Test>() to return different values depending |
| 596 | // on whether the call is from the Google Test framework itself or |
| 597 | // from user test code. GetTestTypeId() is guaranteed to always |
| 598 | // return the same value, as it always calls GetTypeId<>() from the |
| 599 | // gtest.cc, which is within the Google Test framework. |
| 600 | TypeId GetTestTypeId() { |
| 601 | return GetTypeId<Test>(); |
| 602 | } |
| 603 | |
| 604 | // The value of GetTestTypeId() as seen from within the Google Test |
| 605 | // library. This is solely for testing GetTestTypeId(). |
| 606 | extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); |
| 607 | |
| 608 | // This predicate-formatter checks that 'results' contains a test part |
| 609 | // failure of the given type and that the failure message contains the |
| 610 | // given substring. |
| 611 | AssertionResult HasOneFailure(const char* /* results_expr */, |
| 612 | const char* /* type_expr */, |
| 613 | const char* /* substr_expr */, |
| 614 | const TestPartResultArray& results, |
| 615 | TestPartResult::Type type, |
| 616 | const string& substr) { |
| 617 | const std::string expected(type == TestPartResult::kFatalFailure ? |
| 618 | "1 fatal failure" : |
| 619 | "1 non-fatal failure"); |
| 620 | Message msg; |
| 621 | if (results.size() != 1) { |
| 622 | msg << "Expected: " << expected << "\n" |
| 623 | << " Actual: " << results.size() << " failures"; |
| 624 | for (int i = 0; i < results.size(); i++) { |
| 625 | msg << "\n" << results.GetTestPartResult(i); |
| 626 | } |
| 627 | return AssertionFailure() << msg; |
| 628 | } |
| 629 | |
| 630 | const TestPartResult& r = results.GetTestPartResult(0); |
| 631 | if (r.type() != type) { |
| 632 | return AssertionFailure() << "Expected: " << expected << "\n" |
| 633 | << " Actual:\n" |
| 634 | << r; |
| 635 | } |
| 636 | |
| 637 | if (strstr(r.message(), substr.c_str()) == NULL) { |
| 638 | return AssertionFailure() << "Expected: " << expected << " containing \"" |
| 639 | << substr << "\"\n" |
| 640 | << " Actual:\n" |
| 641 | << r; |
| 642 | } |
| 643 | |
| 644 | return AssertionSuccess(); |
| 645 | } |
| 646 | |
| 647 | // The constructor of SingleFailureChecker remembers where to look up |
| 648 | // test part results, what type of failure we expect, and what |
| 649 | // substring the failure message should contain. |
| 650 | SingleFailureChecker:: SingleFailureChecker( |
| 651 | const TestPartResultArray* results, |
| 652 | TestPartResult::Type type, |
| 653 | const string& substr) |
| 654 | : results_(results), |
| 655 | type_(type), |
| 656 | substr_(substr) {} |
| 657 | |
| 658 | // The destructor of SingleFailureChecker verifies that the given |
| 659 | // TestPartResultArray contains exactly one failure that has the given |
| 660 | // type and contains the given substring. If that's not the case, a |
| 661 | // non-fatal failure will be generated. |
| 662 | SingleFailureChecker::~SingleFailureChecker() { |
| 663 | EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); |
| 664 | } |
| 665 | |
| 666 | DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( |
| 667 | UnitTestImpl* unit_test) : unit_test_(unit_test) {} |
| 668 | |
| 669 | void DefaultGlobalTestPartResultReporter::ReportTestPartResult( |
| 670 | const TestPartResult& result) { |
| 671 | unit_test_->current_test_result()->AddTestPartResult(result); |
| 672 | unit_test_->listeners()->repeater()->OnTestPartResult(result); |
| 673 | } |
| 674 | |
| 675 | DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( |
| 676 | UnitTestImpl* unit_test) : unit_test_(unit_test) {} |
| 677 | |
| 678 | void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( |
| 679 | const TestPartResult& result) { |
| 680 | unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); |
| 681 | } |
| 682 | |
| 683 | // Returns the global test part result reporter. |
| 684 | TestPartResultReporterInterface* |
| 685 | UnitTestImpl::GetGlobalTestPartResultReporter() { |
| 686 | internal::MutexLock lock(&global_test_part_result_reporter_mutex_); |
| 687 | return global_test_part_result_repoter_; |
| 688 | } |
| 689 | |
| 690 | // Sets the global test part result reporter. |
| 691 | void UnitTestImpl::SetGlobalTestPartResultReporter( |
| 692 | TestPartResultReporterInterface* reporter) { |
| 693 | internal::MutexLock lock(&global_test_part_result_reporter_mutex_); |
| 694 | global_test_part_result_repoter_ = reporter; |
| 695 | } |
| 696 | |
| 697 | // Returns the test part result reporter for the current thread. |
| 698 | TestPartResultReporterInterface* |
| 699 | UnitTestImpl::GetTestPartResultReporterForCurrentThread() { |
| 700 | return per_thread_test_part_result_reporter_.get(); |
| 701 | } |
| 702 | |
| 703 | // Sets the test part result reporter for the current thread. |
| 704 | void UnitTestImpl::SetTestPartResultReporterForCurrentThread( |
| 705 | TestPartResultReporterInterface* reporter) { |
| 706 | per_thread_test_part_result_reporter_.set(reporter); |
| 707 | } |
| 708 | |
| 709 | // Gets the number of successful test cases. |
| 710 | int UnitTestImpl::successful_test_case_count() const { |
| 711 | return CountIf(test_cases_, TestCasePassed); |
| 712 | } |
| 713 | |
| 714 | // Gets the number of failed test cases. |
| 715 | int UnitTestImpl::failed_test_case_count() const { |
| 716 | return CountIf(test_cases_, TestCaseFailed); |
| 717 | } |
| 718 | |
| 719 | // Gets the number of all test cases. |
| 720 | int UnitTestImpl::total_test_case_count() const { |
| 721 | return static_cast<int>(test_cases_.size()); |
| 722 | } |
| 723 | |
| 724 | // Gets the number of all test cases that contain at least one test |
| 725 | // that should run. |
| 726 | int UnitTestImpl::test_case_to_run_count() const { |
| 727 | return CountIf(test_cases_, ShouldRunTestCase); |
| 728 | } |
| 729 | |
| 730 | // Gets the number of successful tests. |
| 731 | int UnitTestImpl::successful_test_count() const { |
| 732 | return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); |
| 733 | } |
| 734 | |
| 735 | // Gets the number of failed tests. |
| 736 | int UnitTestImpl::failed_test_count() const { |
| 737 | return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); |
| 738 | } |
| 739 | |
| 740 | // Gets the number of disabled tests that will be reported in the XML report. |
| 741 | int UnitTestImpl::reportable_disabled_test_count() const { |
| 742 | return SumOverTestCaseList(test_cases_, |
| 743 | &TestCase::reportable_disabled_test_count); |
| 744 | } |
| 745 | |
| 746 | // Gets the number of disabled tests. |
| 747 | int UnitTestImpl::disabled_test_count() const { |
| 748 | return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); |
| 749 | } |
| 750 | |
| 751 | // Gets the number of tests to be printed in the XML report. |
| 752 | int UnitTestImpl::reportable_test_count() const { |
| 753 | return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); |
| 754 | } |
| 755 | |
| 756 | // Gets the number of all tests. |
| 757 | int UnitTestImpl::total_test_count() const { |
| 758 | return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); |
| 759 | } |
| 760 | |
| 761 | // Gets the number of tests that should run. |
| 762 | int UnitTestImpl::test_to_run_count() const { |
| 763 | return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); |
| 764 | } |
| 765 | |
| 766 | // Returns the current OS stack trace as an std::string. |
| 767 | // |
| 768 | // The maximum number of stack frames to be included is specified by |
| 769 | // the gtest_stack_trace_depth flag. The skip_count parameter |
| 770 | // specifies the number of top frames to be skipped, which doesn't |
| 771 | // count against the number of frames to be included. |
| 772 | // |
| 773 | // For example, if Foo() calls Bar(), which in turn calls |
| 774 | // CurrentOsStackTraceExceptTop(1), Foo() will be included in the |
| 775 | // trace but Bar() and CurrentOsStackTraceExceptTop() won't. |
| 776 | std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { |
| 777 | (void)skip_count; |
| 778 | return ""; |
| 779 | } |
| 780 | |
| 781 | // Returns the current time in milliseconds. |
| 782 | TimeInMillis GetTimeInMillis() { |
| 783 | #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) |
| 784 | // Difference between 1970-01-01 and 1601-01-01 in milliseconds. |
| 785 | // http://analogous.blogspot.com/2005/04/epoch.html |
| 786 | const TimeInMillis kJavaEpochToWinFileTimeDelta = |
| 787 | static_cast<TimeInMillis>(116444736UL) * 100000UL; |
| 788 | const DWORD kTenthMicrosInMilliSecond = 10000; |
| 789 | |
| 790 | SYSTEMTIME now_systime; |
| 791 | FILETIME now_filetime; |
| 792 | ULARGE_INTEGER now_int64; |
| 793 | // TODO(kenton@google.com): Shouldn't this just use |
| 794 | // GetSystemTimeAsFileTime()? |
| 795 | GetSystemTime(&now_systime); |
| 796 | if (SystemTimeToFileTime(&now_systime, &now_filetime)) { |
| 797 | now_int64.LowPart = now_filetime.dwLowDateTime; |
| 798 | now_int64.HighPart = now_filetime.dwHighDateTime; |
| 799 | now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - |
| 800 | kJavaEpochToWinFileTimeDelta; |
| 801 | return now_int64.QuadPart; |
| 802 | } |
| 803 | return 0; |
| 804 | #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ |
| 805 | __timeb64 now; |
| 806 | |
| 807 | // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 |
| 808 | // (deprecated function) there. |
| 809 | // TODO(kenton@google.com): Use GetTickCount()? Or use |
| 810 | // SystemTimeToFileTime() |
| 811 | GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) |
| 812 | _ftime64(&now); |
| 813 | GTEST_DISABLE_MSC_WARNINGS_POP_() |
| 814 | |
| 815 | return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; |
| 816 | #elif GTEST_HAS_GETTIMEOFDAY_ |
| 817 | struct timeval now; |
| 818 | gettimeofday(&now, NULL); |
| 819 | return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; |
| 820 | #else |
| 821 | # error "Don't know how to get the current time on your system." |
| 822 | #endif |
| 823 | } |
| 824 | |
| 825 | // Utilities |
| 826 | |
| 827 | // class String. |
| 828 | |
| 829 | #if GTEST_OS_WINDOWS_MOBILE |
| 830 | // Creates a UTF-16 wide string from the given ANSI string, allocating |
| 831 | // memory using new. The caller is responsible for deleting the return |
| 832 | // value using delete[]. Returns the wide string, or NULL if the |
| 833 | // input is NULL. |
| 834 | LPCWSTR String::AnsiToUtf16(const char* ansi) { |
| 835 | if (!ansi) return NULL; |
| 836 | const int length = strlen(ansi); |
| 837 | const int unicode_length = |
| 838 | MultiByteToWideChar(CP_ACP, 0, ansi, length, |
| 839 | NULL, 0); |
| 840 | WCHAR* unicode = new WCHAR[unicode_length + 1]; |
| 841 | MultiByteToWideChar(CP_ACP, 0, ansi, length, |
| 842 | unicode, unicode_length); |
| 843 | unicode[unicode_length] = 0; |
| 844 | return unicode; |
| 845 | } |
| 846 | |
| 847 | // Creates an ANSI string from the given wide string, allocating |
| 848 | // memory using new. The caller is responsible for deleting the return |
| 849 | // value using delete[]. Returns the ANSI string, or NULL if the |
| 850 | // input is NULL. |
| 851 | const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { |
| 852 | if (!utf16_str) return NULL; |
| 853 | const int ansi_length = |
| 854 | WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, |
| 855 | NULL, 0, NULL, NULL); |
| 856 | char* ansi = new char[ansi_length + 1]; |
| 857 | WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, |
| 858 | ansi, ansi_length, NULL, NULL); |
| 859 | ansi[ansi_length] = 0; |
| 860 | return ansi; |
| 861 | } |
| 862 | |
| 863 | #endif // GTEST_OS_WINDOWS_MOBILE |
| 864 | |
| 865 | // Compares two C strings. Returns true iff they have the same content. |
| 866 | // |
| 867 | // Unlike strcmp(), this function can handle NULL argument(s). A NULL |
| 868 | // C string is considered different to any non-NULL C string, |
| 869 | // including the empty string. |
| 870 | bool String::CStringEquals(const char * lhs, const char * rhs) { |
| 871 | if ( lhs == NULL ) return rhs == NULL; |
| 872 | |
| 873 | if ( rhs == NULL ) return false; |
| 874 | |
| 875 | return strcmp(lhs, rhs) == 0; |
| 876 | } |
| 877 | |
| 878 | #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING |
| 879 | |
| 880 | // Converts an array of wide chars to a narrow string using the UTF-8 |
| 881 | // encoding, and streams the result to the given Message object. |
| 882 | static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, |
| 883 | Message* msg) { |
| 884 | for (size_t i = 0; i != length; ) { // NOLINT |
| 885 | if (wstr[i] != L'\0') { |
| 886 | *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); |
| 887 | while (i != length && wstr[i] != L'\0') |
| 888 | i++; |
| 889 | } else { |
| 890 | *msg << '\0'; |
| 891 | i++; |
| 892 | } |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING |
| 897 | |
| 898 | } // namespace internal |
| 899 | |
| 900 | // Constructs an empty Message. |
| 901 | // We allocate the stringstream separately because otherwise each use of |
| 902 | // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's |
| 903 | // stack frame leading to huge stack frames in some cases; gcc does not reuse |
| 904 | // the stack space. |
| 905 | Message::Message() : ss_(new ::std::stringstream) { |
| 906 | // By default, we want there to be enough precision when printing |
| 907 | // a double to a Message. |
| 908 | *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); |
| 909 | } |
| 910 | |
| 911 | // These two overloads allow streaming a wide C string to a Message |
| 912 | // using the UTF-8 encoding. |
| 913 | Message& Message::operator <<(const wchar_t* wide_c_str) { |
| 914 | return *this << internal::String::ShowWideCString(wide_c_str); |
| 915 | } |
| 916 | Message& Message::operator <<(wchar_t* wide_c_str) { |
| 917 | return *this << internal::String::ShowWideCString(wide_c_str); |
| 918 | } |
| 919 | |
| 920 | #if GTEST_HAS_STD_WSTRING |
| 921 | // Converts the given wide string to a narrow string using the UTF-8 |
| 922 | // encoding, and streams the result to this Message object. |
| 923 | Message& Message::operator <<(const ::std::wstring& wstr) { |
| 924 | internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); |
| 925 | return *this; |
| 926 | } |
| 927 | #endif // GTEST_HAS_STD_WSTRING |
| 928 | |
| 929 | #if GTEST_HAS_GLOBAL_WSTRING |
| 930 | // Converts the given wide string to a narrow string using the UTF-8 |
| 931 | // encoding, and streams the result to this Message object. |
| 932 | Message& Message::operator <<(const ::wstring& wstr) { |
| 933 | internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); |
| 934 | return *this; |
| 935 | } |
| 936 | #endif // GTEST_HAS_GLOBAL_WSTRING |
| 937 | |
| 938 | // Gets the text streamed to this object so far as an std::string. |
| 939 | // Each '\0' character in the buffer is replaced with "\\0". |
| 940 | std::string Message::GetString() const { |
| 941 | return internal::StringStreamToString(ss_.get()); |
| 942 | } |
| 943 | |
| 944 | // AssertionResult constructors. |
| 945 | // Used in EXPECT_TRUE/FALSE(assertion_result). |
| 946 | AssertionResult::AssertionResult(const AssertionResult& other) |
| 947 | : success_(other.success_), |
| 948 | message_(other.message_.get() != NULL ? |
| 949 | new ::std::string(*other.message_) : |
| 950 | static_cast< ::std::string*>(NULL)) { |
| 951 | } |
| 952 | |
| 953 | // Swaps two AssertionResults. |
| 954 | void AssertionResult::swap(AssertionResult& other) { |
| 955 | using std::swap; |
| 956 | swap(success_, other.success_); |
| 957 | swap(message_, other.message_); |
| 958 | } |
| 959 | |
| 960 | // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. |
| 961 | AssertionResult AssertionResult::operator!() const { |
| 962 | AssertionResult negation(!success_); |
| 963 | if (message_.get() != NULL) |
| 964 | negation << *message_; |
| 965 | return negation; |
| 966 | } |
| 967 | |
| 968 | // Makes a successful assertion result. |
| 969 | AssertionResult AssertionSuccess() { |
| 970 | return AssertionResult(true); |
| 971 | } |
| 972 | |
| 973 | // Makes a failed assertion result. |
| 974 | AssertionResult AssertionFailure() { |
| 975 | return AssertionResult(false); |
| 976 | } |
| 977 | |
| 978 | // Makes a failed assertion result with the given failure message. |
| 979 | // Deprecated; use AssertionFailure() << message. |
| 980 | AssertionResult AssertionFailure(const Message& message) { |
| 981 | return AssertionFailure() << message; |
| 982 | } |
| 983 | |
| 984 | namespace internal { |
| 985 | |
| 986 | // Constructs and returns the message for an equality assertion |
| 987 | // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. |
| 988 | // |
| 989 | // The first four parameters are the expressions used in the assertion |
| 990 | // and their values, as strings. For example, for ASSERT_EQ(foo, bar) |
| 991 | // where foo is 5 and bar is 6, we have: |
| 992 | // |
| 993 | // expected_expression: "foo" |
| 994 | // actual_expression: "bar" |
| 995 | // expected_value: "5" |
| 996 | // actual_value: "6" |
| 997 | // |
| 998 | // The ignoring_case parameter is true iff the assertion is a |
| 999 | // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will |
| 1000 | // be inserted into the message. |
| 1001 | AssertionResult EqFailure(const char* expected_expression, |
| 1002 | const char* actual_expression, |
| 1003 | const std::string& expected_value, |
| 1004 | const std::string& actual_value, |
| 1005 | bool ignoring_case) { |
| 1006 | Message msg; |
| 1007 | msg << "Value of: " << actual_expression; |
| 1008 | if (actual_value != actual_expression) { |
| 1009 | msg << "\n Actual: " << actual_value; |
| 1010 | } |
| 1011 | |
| 1012 | msg << "\nExpected: " << expected_expression; |
| 1013 | if (ignoring_case) { |
| 1014 | msg << " (ignoring case)"; |
| 1015 | } |
| 1016 | if (expected_value != expected_expression) { |
| 1017 | msg << "\nWhich is: " << expected_value; |
| 1018 | } |
| 1019 | |
| 1020 | return AssertionFailure() << msg; |
| 1021 | } |
| 1022 | |
| 1023 | // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. |
| 1024 | std::string GetBoolAssertionFailureMessage( |
| 1025 | const AssertionResult& assertion_result, |
| 1026 | const char* expression_text, |
| 1027 | const char* actual_predicate_value, |
| 1028 | const char* expected_predicate_value) { |
| 1029 | const char* actual_message = assertion_result.message(); |
| 1030 | Message msg; |
| 1031 | msg << "Value of: " << expression_text |
| 1032 | << "\n Actual: " << actual_predicate_value; |
| 1033 | if (actual_message[0] != '\0') |
| 1034 | msg << " (" << actual_message << ")"; |
| 1035 | msg << "\nExpected: " << expected_predicate_value; |
| 1036 | return msg.GetString(); |
| 1037 | } |
| 1038 | |
| 1039 | // Helper function for implementing ASSERT_NEAR. |
| 1040 | AssertionResult DoubleNearPredFormat(const char* expr1, |
| 1041 | const char* expr2, |
| 1042 | const char* abs_error_expr, |
| 1043 | double val1, |
| 1044 | double val2, |
| 1045 | double abs_error) { |
| 1046 | const double diff = fabs(val1 - val2); |
| 1047 | if (diff <= abs_error) return AssertionSuccess(); |
| 1048 | |
| 1049 | // TODO(wan): do not print the value of an expression if it's |
| 1050 | // already a literal. |
| 1051 | return AssertionFailure() |
| 1052 | << "The difference between " << expr1 << " and " << expr2 |
| 1053 | << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" |
| 1054 | << expr1 << " evaluates to " << val1 << ",\n" |
| 1055 | << expr2 << " evaluates to " << val2 << ", and\n" |
| 1056 | << abs_error_expr << " evaluates to " << abs_error << "."; |
| 1057 | } |
| 1058 | |
| 1059 | |
| 1060 | // Helper template for implementing FloatLE() and DoubleLE(). |
| 1061 | template <typename RawType> |
| 1062 | AssertionResult FloatingPointLE(const char* expr1, |
| 1063 | const char* expr2, |
| 1064 | RawType val1, |
| 1065 | RawType val2) { |
| 1066 | // Returns success if val1 is less than val2, |
| 1067 | if (val1 < val2) { |
| 1068 | return AssertionSuccess(); |
| 1069 | } |
| 1070 | |
| 1071 | // or if val1 is almost equal to val2. |
| 1072 | const FloatingPoint<RawType> lhs(val1), rhs(val2); |
| 1073 | if (lhs.AlmostEquals(rhs)) { |
| 1074 | return AssertionSuccess(); |
| 1075 | } |
| 1076 | |
| 1077 | // Note that the above two checks will both fail if either val1 or |
| 1078 | // val2 is NaN, as the IEEE floating-point standard requires that |
| 1079 | // any predicate involving a NaN must return false. |
| 1080 | |
| 1081 | ::std::stringstream val1_ss; |
| 1082 | val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) |
| 1083 | << val1; |
| 1084 | |
| 1085 | ::std::stringstream val2_ss; |
| 1086 | val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) |
| 1087 | << val2; |
| 1088 | |
| 1089 | return AssertionFailure() |
| 1090 | << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" |
| 1091 | << " Actual: " << StringStreamToString(&val1_ss) << " vs " |
| 1092 | << StringStreamToString(&val2_ss); |
| 1093 | } |
| 1094 | |
| 1095 | } // namespace internal |
| 1096 | |
| 1097 | // Asserts that val1 is less than, or almost equal to, val2. Fails |
| 1098 | // otherwise. In particular, it fails if either val1 or val2 is NaN. |
| 1099 | AssertionResult FloatLE(const char* expr1, const char* expr2, |
| 1100 | float val1, float val2) { |
| 1101 | return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); |
| 1102 | } |
| 1103 | |
| 1104 | // Asserts that val1 is less than, or almost equal to, val2. Fails |
| 1105 | // otherwise. In particular, it fails if either val1 or val2 is NaN. |
| 1106 | AssertionResult DoubleLE(const char* expr1, const char* expr2, |
| 1107 | double val1, double val2) { |
| 1108 | return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); |
| 1109 | } |
| 1110 | |
| 1111 | namespace internal { |
| 1112 | |
| 1113 | // The helper function for {ASSERT|EXPECT}_EQ with int or enum |
| 1114 | // arguments. |
| 1115 | AssertionResult CmpHelperEQ(const char* expected_expression, |
| 1116 | const char* actual_expression, |
| 1117 | BiggestInt expected, |
| 1118 | BiggestInt actual) { |
| 1119 | if (expected == actual) { |
| 1120 | return AssertionSuccess(); |
| 1121 | } |
| 1122 | |
| 1123 | return EqFailure(expected_expression, |
| 1124 | actual_expression, |
| 1125 | FormatForComparisonFailureMessage(expected, actual), |
| 1126 | FormatForComparisonFailureMessage(actual, expected), |
| 1127 | false); |
| 1128 | } |
| 1129 | |
| 1130 | // A macro for implementing the helper functions needed to implement |
| 1131 | // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here |
| 1132 | // just to avoid copy-and-paste of similar code. |
| 1133 | #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ |
| 1134 | AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ |
| 1135 | BiggestInt val1, BiggestInt val2) {\ |
| 1136 | if (val1 op val2) {\ |
| 1137 | return AssertionSuccess();\ |
| 1138 | } else {\ |
| 1139 | return AssertionFailure() \ |
| 1140 | << "Expected: (" << expr1 << ") " #op " (" << expr2\ |
| 1141 | << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ |
| 1142 | << " vs " << FormatForComparisonFailureMessage(val2, val1);\ |
| 1143 | }\ |
| 1144 | } |
| 1145 | |
| 1146 | // Implements the helper function for {ASSERT|EXPECT}_NE with int or |
| 1147 | // enum arguments. |
| 1148 | GTEST_IMPL_CMP_HELPER_(NE, !=) |
| 1149 | // Implements the helper function for {ASSERT|EXPECT}_LE with int or |
| 1150 | // enum arguments. |
| 1151 | GTEST_IMPL_CMP_HELPER_(LE, <=) |
| 1152 | // Implements the helper function for {ASSERT|EXPECT}_LT with int or |
| 1153 | // enum arguments. |
| 1154 | GTEST_IMPL_CMP_HELPER_(LT, < ) |
| 1155 | // Implements the helper function for {ASSERT|EXPECT}_GE with int or |
| 1156 | // enum arguments. |
| 1157 | GTEST_IMPL_CMP_HELPER_(GE, >=) |
| 1158 | // Implements the helper function for {ASSERT|EXPECT}_GT with int or |
| 1159 | // enum arguments. |
| 1160 | GTEST_IMPL_CMP_HELPER_(GT, > ) |
| 1161 | |
| 1162 | #undef GTEST_IMPL_CMP_HELPER_ |
| 1163 | |
| 1164 | // The helper function for {ASSERT|EXPECT}_STREQ. |
| 1165 | AssertionResult CmpHelperSTREQ(const char* expected_expression, |
| 1166 | const char* actual_expression, |
| 1167 | const char* expected, |
| 1168 | const char* actual) { |
| 1169 | if (String::CStringEquals(expected, actual)) { |
| 1170 | return AssertionSuccess(); |
| 1171 | } |
| 1172 | |
| 1173 | return EqFailure(expected_expression, |
| 1174 | actual_expression, |
| 1175 | PrintToString(expected), |
| 1176 | PrintToString(actual), |
| 1177 | false); |
| 1178 | } |
| 1179 | |
| 1180 | // The helper function for {ASSERT|EXPECT}_STRCASEEQ. |
| 1181 | AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, |
| 1182 | const char* actual_expression, |
| 1183 | const char* expected, |
| 1184 | const char* actual) { |
| 1185 | if (String::CaseInsensitiveCStringEquals(expected, actual)) { |
| 1186 | return AssertionSuccess(); |
| 1187 | } |
| 1188 | |
| 1189 | return EqFailure(expected_expression, |
| 1190 | actual_expression, |
| 1191 | PrintToString(expected), |
| 1192 | PrintToString(actual), |
| 1193 | true); |
| 1194 | } |
| 1195 | |
| 1196 | // The helper function for {ASSERT|EXPECT}_STRNE. |
| 1197 | AssertionResult CmpHelperSTRNE(const char* s1_expression, |
| 1198 | const char* s2_expression, |
| 1199 | const char* s1, |
| 1200 | const char* s2) { |
| 1201 | if (!String::CStringEquals(s1, s2)) { |
| 1202 | return AssertionSuccess(); |
| 1203 | } else { |
| 1204 | return AssertionFailure() << "Expected: (" << s1_expression << ") != (" |
| 1205 | << s2_expression << "), actual: \"" |
| 1206 | << s1 << "\" vs \"" << s2 << "\""; |
| 1207 | } |
| 1208 | } |
| 1209 | |
| 1210 | // The helper function for {ASSERT|EXPECT}_STRCASENE. |
| 1211 | AssertionResult CmpHelperSTRCASENE(const char* s1_expression, |
| 1212 | const char* s2_expression, |
| 1213 | const char* s1, |
| 1214 | const char* s2) { |
| 1215 | if (!String::CaseInsensitiveCStringEquals(s1, s2)) { |
| 1216 | return AssertionSuccess(); |
| 1217 | } else { |
| 1218 | return AssertionFailure() |
| 1219 | << "Expected: (" << s1_expression << ") != (" |
| 1220 | << s2_expression << ") (ignoring case), actual: \"" |
| 1221 | << s1 << "\" vs \"" << s2 << "\""; |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | } // namespace internal |
| 1226 | |
| 1227 | namespace { |
| 1228 | |
| 1229 | // Helper functions for implementing IsSubString() and IsNotSubstring(). |
| 1230 | |
| 1231 | // This group of overloaded functions return true iff needle is a |
| 1232 | // substring of haystack. NULL is considered a substring of itself |
| 1233 | // only. |
| 1234 | |
| 1235 | bool IsSubstringPred(const char* needle, const char* haystack) { |
| 1236 | if (needle == NULL || haystack == NULL) |
| 1237 | return needle == haystack; |
| 1238 | |
| 1239 | return strstr(haystack, needle) != NULL; |
| 1240 | } |
| 1241 | |
| 1242 | bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { |
| 1243 | if (needle == NULL || haystack == NULL) |
| 1244 | return needle == haystack; |
| 1245 | |
| 1246 | return wcsstr(haystack, needle) != NULL; |
| 1247 | } |
| 1248 | |
| 1249 | // StringType here can be either ::std::string or ::std::wstring. |
| 1250 | template <typename StringType> |
| 1251 | bool IsSubstringPred(const StringType& needle, |
| 1252 | const StringType& haystack) { |
| 1253 | return haystack.find(needle) != StringType::npos; |
| 1254 | } |
| 1255 | |
| 1256 | // This function implements either IsSubstring() or IsNotSubstring(), |
| 1257 | // depending on the value of the expected_to_be_substring parameter. |
| 1258 | // StringType here can be const char*, const wchar_t*, ::std::string, |
| 1259 | // or ::std::wstring. |
| 1260 | template <typename StringType> |
| 1261 | AssertionResult IsSubstringImpl( |
| 1262 | bool expected_to_be_substring, |
| 1263 | const char* needle_expr, const char* haystack_expr, |
| 1264 | const StringType& needle, const StringType& haystack) { |
| 1265 | if (IsSubstringPred(needle, haystack) == expected_to_be_substring) |
| 1266 | return AssertionSuccess(); |
| 1267 | |
| 1268 | const bool is_wide_string = sizeof(needle[0]) > 1; |
| 1269 | const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; |
| 1270 | return AssertionFailure() |
| 1271 | << "Value of: " << needle_expr << "\n" |
| 1272 | << " Actual: " << begin_string_quote << needle << "\"\n" |
| 1273 | << "Expected: " << (expected_to_be_substring ? "" : "not ") |
| 1274 | << "a substring of " << haystack_expr << "\n" |
| 1275 | << "Which is: " << begin_string_quote << haystack << "\""; |
| 1276 | } |
| 1277 | |
| 1278 | } // namespace |
| 1279 | |
| 1280 | // IsSubstring() and IsNotSubstring() check whether needle is a |
| 1281 | // substring of haystack (NULL is considered a substring of itself |
| 1282 | // only), and return an appropriate error message when they fail. |
| 1283 | |
| 1284 | AssertionResult IsSubstring( |
| 1285 | const char* needle_expr, const char* haystack_expr, |
| 1286 | const char* needle, const char* haystack) { |
| 1287 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1288 | } |
| 1289 | |
| 1290 | AssertionResult IsSubstring( |
| 1291 | const char* needle_expr, const char* haystack_expr, |
| 1292 | const wchar_t* needle, const wchar_t* haystack) { |
| 1293 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1294 | } |
| 1295 | |
| 1296 | AssertionResult IsNotSubstring( |
| 1297 | const char* needle_expr, const char* haystack_expr, |
| 1298 | const char* needle, const char* haystack) { |
| 1299 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1300 | } |
| 1301 | |
| 1302 | AssertionResult IsNotSubstring( |
| 1303 | const char* needle_expr, const char* haystack_expr, |
| 1304 | const wchar_t* needle, const wchar_t* haystack) { |
| 1305 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1306 | } |
| 1307 | |
| 1308 | AssertionResult IsSubstring( |
| 1309 | const char* needle_expr, const char* haystack_expr, |
| 1310 | const ::std::string& needle, const ::std::string& haystack) { |
| 1311 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1312 | } |
| 1313 | |
| 1314 | AssertionResult IsNotSubstring( |
| 1315 | const char* needle_expr, const char* haystack_expr, |
| 1316 | const ::std::string& needle, const ::std::string& haystack) { |
| 1317 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1318 | } |
| 1319 | |
| 1320 | #if GTEST_HAS_STD_WSTRING |
| 1321 | AssertionResult IsSubstring( |
| 1322 | const char* needle_expr, const char* haystack_expr, |
| 1323 | const ::std::wstring& needle, const ::std::wstring& haystack) { |
| 1324 | return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); |
| 1325 | } |
| 1326 | |
| 1327 | AssertionResult IsNotSubstring( |
| 1328 | const char* needle_expr, const char* haystack_expr, |
| 1329 | const ::std::wstring& needle, const ::std::wstring& haystack) { |
| 1330 | return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); |
| 1331 | } |
| 1332 | #endif // GTEST_HAS_STD_WSTRING |
| 1333 | |
| 1334 | namespace internal { |
| 1335 | |
| 1336 | #if GTEST_OS_WINDOWS |
| 1337 | |
| 1338 | namespace { |
| 1339 | |
| 1340 | // Helper function for IsHRESULT{SuccessFailure} predicates |
| 1341 | AssertionResult HRESULTFailureHelper(const char* expr, |
| 1342 | const char* expected, |
| 1343 | long hr) { // NOLINT |
| 1344 | # if GTEST_OS_WINDOWS_MOBILE |
| 1345 | |
| 1346 | // Windows CE doesn't support FormatMessage. |
| 1347 | const char error_text[] = ""; |
| 1348 | |
| 1349 | # else |
| 1350 | |
| 1351 | // Looks up the human-readable system message for the HRESULT code |
| 1352 | // and since we're not passing any params to FormatMessage, we don't |
| 1353 | // want inserts expanded. |
| 1354 | const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | |
| 1355 | FORMAT_MESSAGE_IGNORE_INSERTS; |
| 1356 | const DWORD kBufSize = 4096; |
| 1357 | // Gets the system's human readable message string for this HRESULT. |
| 1358 | char error_text[kBufSize] = { '\0' }; |
| 1359 | DWORD message_length = ::FormatMessageA(kFlags, |
| 1360 | 0, // no source, we're asking system |
| 1361 | hr, // the error |
| 1362 | 0, // no line width restrictions |
| 1363 | error_text, // output buffer |
| 1364 | kBufSize, // buf size |
| 1365 | NULL); // no arguments for inserts |
| 1366 | // Trims tailing white space (FormatMessage leaves a trailing CR-LF) |
| 1367 | for (; message_length && IsSpace(error_text[message_length - 1]); |
| 1368 | --message_length) { |
| 1369 | error_text[message_length - 1] = '\0'; |
| 1370 | } |
| 1371 | |
| 1372 | # endif // GTEST_OS_WINDOWS_MOBILE |
| 1373 | |
| 1374 | const std::string error_hex("0x" + String::FormatHexInt(hr)); |
| 1375 | return ::testing::AssertionFailure() |
| 1376 | << "Expected: " << expr << " " << expected << ".\n" |
| 1377 | << " Actual: " << error_hex << " " << error_text << "\n"; |
| 1378 | } |
| 1379 | |
| 1380 | } // namespace |
| 1381 | |
| 1382 | AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT |
| 1383 | if (SUCCEEDED(hr)) { |
| 1384 | return AssertionSuccess(); |
| 1385 | } |
| 1386 | return HRESULTFailureHelper(expr, "succeeds", hr); |
| 1387 | } |
| 1388 | |
| 1389 | AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT |
| 1390 | if (FAILED(hr)) { |
| 1391 | return AssertionSuccess(); |
| 1392 | } |
| 1393 | return HRESULTFailureHelper(expr, "fails", hr); |
| 1394 | } |
| 1395 | |
| 1396 | #endif // GTEST_OS_WINDOWS |
| 1397 | |
| 1398 | // Utility functions for encoding Unicode text (wide strings) in |
| 1399 | // UTF-8. |
| 1400 | |
| 1401 | // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 |
| 1402 | // like this: |
| 1403 | // |
| 1404 | // Code-point length Encoding |
| 1405 | // 0 - 7 bits 0xxxxxxx |
| 1406 | // 8 - 11 bits 110xxxxx 10xxxxxx |
| 1407 | // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx |
| 1408 | // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 1409 | |
| 1410 | // The maximum code-point a one-byte UTF-8 sequence can represent. |
| 1411 | const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; |
| 1412 | |
| 1413 | // The maximum code-point a two-byte UTF-8 sequence can represent. |
| 1414 | const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; |
| 1415 | |
| 1416 | // The maximum code-point a three-byte UTF-8 sequence can represent. |
| 1417 | const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; |
| 1418 | |
| 1419 | // The maximum code-point a four-byte UTF-8 sequence can represent. |
| 1420 | const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; |
| 1421 | |
| 1422 | // Chops off the n lowest bits from a bit pattern. Returns the n |
| 1423 | // lowest bits. As a side effect, the original bit pattern will be |
| 1424 | // shifted to the right by n bits. |
| 1425 | inline UInt32 ChopLowBits(UInt32* bits, int n) { |
| 1426 | const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); |
| 1427 | *bits >>= n; |
| 1428 | return low_bits; |
| 1429 | } |
| 1430 | |
| 1431 | // Converts a Unicode code point to a narrow string in UTF-8 encoding. |
| 1432 | // code_point parameter is of type UInt32 because wchar_t may not be |
| 1433 | // wide enough to contain a code point. |
| 1434 | // If the code_point is not a valid Unicode code point |
| 1435 | // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted |
| 1436 | // to "(Invalid Unicode 0xXXXXXXXX)". |
| 1437 | std::string CodePointToUtf8(UInt32 code_point) { |
| 1438 | if (code_point > kMaxCodePoint4) { |
| 1439 | return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; |
| 1440 | } |
| 1441 | |
| 1442 | char str[5]; // Big enough for the largest valid code point. |
| 1443 | if (code_point <= kMaxCodePoint1) { |
| 1444 | str[1] = '\0'; |
| 1445 | str[0] = static_cast<char>(code_point); // 0xxxxxxx |
| 1446 | } else if (code_point <= kMaxCodePoint2) { |
| 1447 | str[2] = '\0'; |
| 1448 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1449 | str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx |
| 1450 | } else if (code_point <= kMaxCodePoint3) { |
| 1451 | str[3] = '\0'; |
| 1452 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1453 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1454 | str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx |
| 1455 | } else { // code_point <= kMaxCodePoint4 |
| 1456 | str[4] = '\0'; |
| 1457 | str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1458 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1459 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 1460 | str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx |
| 1461 | } |
| 1462 | return str; |
| 1463 | } |
| 1464 | |
| 1465 | // The following two functions only make sense if the the system |
| 1466 | // uses UTF-16 for wide string encoding. All supported systems |
| 1467 | // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. |
| 1468 | |
| 1469 | // Determines if the arguments constitute UTF-16 surrogate pair |
| 1470 | // and thus should be combined into a single Unicode code point |
| 1471 | // using CreateCodePointFromUtf16SurrogatePair. |
| 1472 | inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { |
| 1473 | return sizeof(wchar_t) == 2 && |
| 1474 | (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; |
| 1475 | } |
| 1476 | |
| 1477 | // Creates a Unicode code point from UTF16 surrogate pair. |
| 1478 | inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, |
| 1479 | wchar_t second) { |
| 1480 | const UInt32 mask = (1 << 10) - 1; |
| 1481 | return (sizeof(wchar_t) == 2) ? |
| 1482 | (((first & mask) << 10) | (second & mask)) + 0x10000 : |
| 1483 | // This function should not be called when the condition is |
| 1484 | // false, but we provide a sensible default in case it is. |
| 1485 | static_cast<UInt32>(first); |
| 1486 | } |
| 1487 | |
| 1488 | // Converts a wide string to a narrow string in UTF-8 encoding. |
| 1489 | // The wide string is assumed to have the following encoding: |
| 1490 | // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) |
| 1491 | // UTF-32 if sizeof(wchar_t) == 4 (on Linux) |
| 1492 | // Parameter str points to a null-terminated wide string. |
| 1493 | // Parameter num_chars may additionally limit the number |
| 1494 | // of wchar_t characters processed. -1 is used when the entire string |
| 1495 | // should be processed. |
| 1496 | // If the string contains code points that are not valid Unicode code points |
| 1497 | // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output |
| 1498 | // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding |
| 1499 | // and contains invalid UTF-16 surrogate pairs, values in those pairs |
| 1500 | // will be encoded as individual Unicode characters from Basic Normal Plane. |
| 1501 | std::string WideStringToUtf8(const wchar_t* str, int num_chars) { |
| 1502 | if (num_chars == -1) |
| 1503 | num_chars = static_cast<int>(wcslen(str)); |
| 1504 | |
| 1505 | ::std::stringstream stream; |
| 1506 | for (int i = 0; i < num_chars; ++i) { |
| 1507 | UInt32 unicode_code_point; |
| 1508 | |
| 1509 | if (str[i] == L'\0') { |
| 1510 | break; |
| 1511 | } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { |
| 1512 | unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], |
| 1513 | str[i + 1]); |
| 1514 | i++; |
| 1515 | } else { |
| 1516 | unicode_code_point = static_cast<UInt32>(str[i]); |
| 1517 | } |
| 1518 | |
| 1519 | stream << CodePointToUtf8(unicode_code_point); |
| 1520 | } |
| 1521 | return StringStreamToString(&stream); |
| 1522 | } |
| 1523 | |
| 1524 | // Converts a wide C string to an std::string using the UTF-8 encoding. |
| 1525 | // NULL will be converted to "(null)". |
| 1526 | std::string String::ShowWideCString(const wchar_t * wide_c_str) { |
| 1527 | if (wide_c_str == NULL) return "(null)"; |
| 1528 | |
| 1529 | return internal::WideStringToUtf8(wide_c_str, -1); |
| 1530 | } |
| 1531 | |
| 1532 | // Compares two wide C strings. Returns true iff they have the same |
| 1533 | // content. |
| 1534 | // |
| 1535 | // Unlike wcscmp(), this function can handle NULL argument(s). A NULL |
| 1536 | // C string is considered different to any non-NULL C string, |
| 1537 | // including the empty string. |
| 1538 | bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { |
| 1539 | if (lhs == NULL) return rhs == NULL; |
| 1540 | |
| 1541 | if (rhs == NULL) return false; |
| 1542 | |
| 1543 | return wcscmp(lhs, rhs) == 0; |
| 1544 | } |
| 1545 | |
| 1546 | // Helper function for *_STREQ on wide strings. |
| 1547 | AssertionResult CmpHelperSTREQ(const char* expected_expression, |
| 1548 | const char* actual_expression, |
| 1549 | const wchar_t* expected, |
| 1550 | const wchar_t* actual) { |
| 1551 | if (String::WideCStringEquals(expected, actual)) { |
| 1552 | return AssertionSuccess(); |
| 1553 | } |
| 1554 | |
| 1555 | return EqFailure(expected_expression, |
| 1556 | actual_expression, |
| 1557 | PrintToString(expected), |
| 1558 | PrintToString(actual), |
| 1559 | false); |
| 1560 | } |
| 1561 | |
| 1562 | // Helper function for *_STRNE on wide strings. |
| 1563 | AssertionResult CmpHelperSTRNE(const char* s1_expression, |
| 1564 | const char* s2_expression, |
| 1565 | const wchar_t* s1, |
| 1566 | const wchar_t* s2) { |
| 1567 | if (!String::WideCStringEquals(s1, s2)) { |
| 1568 | return AssertionSuccess(); |
| 1569 | } |
| 1570 | |
| 1571 | return AssertionFailure() << "Expected: (" << s1_expression << ") != (" |
| 1572 | << s2_expression << "), actual: " |
| 1573 | << PrintToString(s1) |
| 1574 | << " vs " << PrintToString(s2); |
| 1575 | } |
| 1576 | |
| 1577 | // Compares two C strings, ignoring case. Returns true iff they have |
| 1578 | // the same content. |
| 1579 | // |
| 1580 | // Unlike strcasecmp(), this function can handle NULL argument(s). A |
| 1581 | // NULL C string is considered different to any non-NULL C string, |
| 1582 | // including the empty string. |
| 1583 | bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { |
| 1584 | if (lhs == NULL) |
| 1585 | return rhs == NULL; |
| 1586 | if (rhs == NULL) |
| 1587 | return false; |
| 1588 | return posix::StrCaseCmp(lhs, rhs) == 0; |
| 1589 | } |
| 1590 | |
| 1591 | // Compares two wide C strings, ignoring case. Returns true iff they |
| 1592 | // have the same content. |
| 1593 | // |
| 1594 | // Unlike wcscasecmp(), this function can handle NULL argument(s). |
| 1595 | // A NULL C string is considered different to any non-NULL wide C string, |
| 1596 | // including the empty string. |
| 1597 | // NB: The implementations on different platforms slightly differ. |
| 1598 | // On windows, this method uses _wcsicmp which compares according to LC_CTYPE |
| 1599 | // environment variable. On GNU platform this method uses wcscasecmp |
| 1600 | // which compares according to LC_CTYPE category of the current locale. |
| 1601 | // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the |
| 1602 | // current locale. |
| 1603 | bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, |
| 1604 | const wchar_t* rhs) { |
| 1605 | if (lhs == NULL) return rhs == NULL; |
| 1606 | |
| 1607 | if (rhs == NULL) return false; |
| 1608 | |
| 1609 | #if GTEST_OS_WINDOWS |
| 1610 | return _wcsicmp(lhs, rhs) == 0; |
| 1611 | #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID |
| 1612 | return wcscasecmp(lhs, rhs) == 0; |
| 1613 | #else |
| 1614 | // Android, Mac OS X and Cygwin don't define wcscasecmp. |
| 1615 | // Other unknown OSes may not define it either. |
| 1616 | wint_t left, right; |
| 1617 | do { |
| 1618 | left = towlower(*lhs++); |
| 1619 | right = towlower(*rhs++); |
| 1620 | } while (left && left == right); |
| 1621 | return left == right; |
| 1622 | #endif // OS selector |
| 1623 | } |
| 1624 | |
| 1625 | // Returns true iff str ends with the given suffix, ignoring case. |
| 1626 | // Any string is considered to end with an empty suffix. |
| 1627 | bool String::EndsWithCaseInsensitive( |
| 1628 | const std::string& str, const std::string& suffix) { |
| 1629 | const size_t str_len = str.length(); |
| 1630 | const size_t suffix_len = suffix.length(); |
| 1631 | return (str_len >= suffix_len) && |
| 1632 | CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, |
| 1633 | suffix.c_str()); |
| 1634 | } |
| 1635 | |
| 1636 | // Formats an int value as "%02d". |
| 1637 | std::string String::FormatIntWidth2(int value) { |
| 1638 | std::stringstream ss; |
| 1639 | ss << std::setfill('0') << std::setw(2) << value; |
| 1640 | return ss.str(); |
| 1641 | } |
| 1642 | |
| 1643 | // Formats an int value as "%X". |
| 1644 | std::string String::FormatHexInt(int value) { |
| 1645 | std::stringstream ss; |
| 1646 | ss << std::hex << std::uppercase << value; |
| 1647 | return ss.str(); |
| 1648 | } |
| 1649 | |
| 1650 | // Formats a byte as "%02X". |
| 1651 | std::string String::FormatByte(unsigned char value) { |
| 1652 | std::stringstream ss; |
| 1653 | ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase |
| 1654 | << static_cast<unsigned int>(value); |
| 1655 | return ss.str(); |
| 1656 | } |
| 1657 | |
| 1658 | // Converts the buffer in a stringstream to an std::string, converting NUL |
| 1659 | // bytes to "\\0" along the way. |
| 1660 | std::string StringStreamToString(::std::stringstream* ss) { |
| 1661 | const ::std::string& str = ss->str(); |
| 1662 | const char* const start = str.c_str(); |
| 1663 | const char* const end = start + str.length(); |
| 1664 | |
| 1665 | std::string result; |
| 1666 | result.reserve(2 * (end - start)); |
| 1667 | for (const char* ch = start; ch != end; ++ch) { |
| 1668 | if (*ch == '\0') { |
| 1669 | result += "\\0"; // Replaces NUL with "\\0"; |
| 1670 | } else { |
| 1671 | result += *ch; |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | return result; |
| 1676 | } |
| 1677 | |
| 1678 | // Appends the user-supplied message to the Google-Test-generated message. |
| 1679 | std::string AppendUserMessage(const std::string& gtest_msg, |
| 1680 | const Message& user_msg) { |
| 1681 | // Appends the user message if it's non-empty. |
| 1682 | const std::string user_msg_string = user_msg.GetString(); |
| 1683 | if (user_msg_string.empty()) { |
| 1684 | return gtest_msg; |
| 1685 | } |
| 1686 | |
| 1687 | return gtest_msg + "\n" + user_msg_string; |
| 1688 | } |
| 1689 | |
| 1690 | } // namespace internal |
| 1691 | |
| 1692 | // class TestResult |
| 1693 | |
| 1694 | // Creates an empty TestResult. |
| 1695 | TestResult::TestResult() |
| 1696 | : death_test_count_(0), |
| 1697 | elapsed_time_(0) { |
| 1698 | } |
| 1699 | |
| 1700 | // D'tor. |
| 1701 | TestResult::~TestResult() { |
| 1702 | } |
| 1703 | |
| 1704 | // Returns the i-th test part result among all the results. i can |
| 1705 | // range from 0 to total_part_count() - 1. If i is not in that range, |
| 1706 | // aborts the program. |
| 1707 | const TestPartResult& TestResult::GetTestPartResult(int i) const { |
| 1708 | if (i < 0 || i >= total_part_count()) |
| 1709 | internal::posix::Abort(); |
| 1710 | return test_part_results_.at(i); |
| 1711 | } |
| 1712 | |
| 1713 | // Returns the i-th test property. i can range from 0 to |
| 1714 | // test_property_count() - 1. If i is not in that range, aborts the |
| 1715 | // program. |
| 1716 | const TestProperty& TestResult::GetTestProperty(int i) const { |
| 1717 | if (i < 0 || i >= test_property_count()) |
| 1718 | internal::posix::Abort(); |
| 1719 | return test_properties_.at(i); |
| 1720 | } |
| 1721 | |
| 1722 | // Clears the test part results. |
| 1723 | void TestResult::ClearTestPartResults() { |
| 1724 | test_part_results_.clear(); |
| 1725 | } |
| 1726 | |
| 1727 | // Adds a test part result to the list. |
| 1728 | void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { |
| 1729 | test_part_results_.push_back(test_part_result); |
| 1730 | } |
| 1731 | |
| 1732 | // Adds a test property to the list. If a property with the same key as the |
| 1733 | // supplied property is already represented, the value of this test_property |
| 1734 | // replaces the old value for that key. |
| 1735 | void TestResult::RecordProperty(const std::string& xml_element, |
| 1736 | const TestProperty& test_property) { |
| 1737 | if (!ValidateTestProperty(xml_element, test_property)) { |
| 1738 | return; |
| 1739 | } |
| 1740 | internal::MutexLock lock(&test_properites_mutex_); |
| 1741 | const std::vector<TestProperty>::iterator property_with_matching_key = |
| 1742 | std::find_if(test_properties_.begin(), test_properties_.end(), |
| 1743 | internal::TestPropertyKeyIs(test_property.key())); |
| 1744 | if (property_with_matching_key == test_properties_.end()) { |
| 1745 | test_properties_.push_back(test_property); |
| 1746 | return; |
| 1747 | } |
| 1748 | property_with_matching_key->SetValue(test_property.value()); |
| 1749 | } |
| 1750 | |
| 1751 | // The list of reserved attributes used in the <testsuites> element of XML |
| 1752 | // output. |
| 1753 | static const char* const kReservedTestSuitesAttributes[] = { |
| 1754 | "disabled", |
| 1755 | "errors", |
| 1756 | "failures", |
| 1757 | "name", |
| 1758 | "random_seed", |
| 1759 | "tests", |
| 1760 | "time", |
| 1761 | "timestamp" |
| 1762 | }; |
| 1763 | |
| 1764 | // The list of reserved attributes used in the <testsuite> element of XML |
| 1765 | // output. |
| 1766 | static const char* const kReservedTestSuiteAttributes[] = { |
| 1767 | "disabled", |
| 1768 | "errors", |
| 1769 | "failures", |
| 1770 | "name", |
| 1771 | "tests", |
| 1772 | "time" |
| 1773 | }; |
| 1774 | |
| 1775 | // The list of reserved attributes used in the <testcase> element of XML output. |
| 1776 | static const char* const kReservedTestCaseAttributes[] = { |
| 1777 | "classname", |
| 1778 | "name", |
| 1779 | "status", |
| 1780 | "time", |
| 1781 | "type_param", |
| 1782 | "value_param" |
| 1783 | }; |
| 1784 | |
| 1785 | template <int kSize> |
| 1786 | std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { |
| 1787 | return std::vector<std::string>(array, array + kSize); |
| 1788 | } |
| 1789 | |
| 1790 | static std::vector<std::string> GetReservedAttributesForElement( |
| 1791 | const std::string& xml_element) { |
| 1792 | if (xml_element == "testsuites") { |
| 1793 | return ArrayAsVector(kReservedTestSuitesAttributes); |
| 1794 | } else if (xml_element == "testsuite") { |
| 1795 | return ArrayAsVector(kReservedTestSuiteAttributes); |
| 1796 | } else if (xml_element == "testcase") { |
| 1797 | return ArrayAsVector(kReservedTestCaseAttributes); |
| 1798 | } else { |
| 1799 | GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; |
| 1800 | } |
| 1801 | // This code is unreachable but some compilers may not realizes that. |
| 1802 | return std::vector<std::string>(); |
| 1803 | } |
| 1804 | |
| 1805 | static std::string FormatWordList(const std::vector<std::string>& words) { |
| 1806 | Message word_list; |
| 1807 | for (size_t i = 0; i < words.size(); ++i) { |
| 1808 | if (i > 0 && words.size() > 2) { |
| 1809 | word_list << ", "; |
| 1810 | } |
| 1811 | if (i == words.size() - 1) { |
| 1812 | word_list << "and "; |
| 1813 | } |
| 1814 | word_list << "'" << words[i] << "'"; |
| 1815 | } |
| 1816 | return word_list.GetString(); |
| 1817 | } |
| 1818 | |
| 1819 | bool ValidateTestPropertyName(const std::string& property_name, |
| 1820 | const std::vector<std::string>& reserved_names) { |
| 1821 | if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != |
| 1822 | reserved_names.end()) { |
| 1823 | ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name |
| 1824 | << " (" << FormatWordList(reserved_names) |
| 1825 | << " are reserved by " << GTEST_NAME_ << ")"; |
| 1826 | return false; |
| 1827 | } |
| 1828 | return true; |
| 1829 | } |
| 1830 | |
| 1831 | // Adds a failure if the key is a reserved attribute of the element named |
| 1832 | // xml_element. Returns true if the property is valid. |
| 1833 | bool TestResult::ValidateTestProperty(const std::string& xml_element, |
| 1834 | const TestProperty& test_property) { |
| 1835 | return ValidateTestPropertyName(test_property.key(), |
| 1836 | GetReservedAttributesForElement(xml_element)); |
| 1837 | } |
| 1838 | |
| 1839 | // Clears the object. |
| 1840 | void TestResult::Clear() { |
| 1841 | test_part_results_.clear(); |
| 1842 | test_properties_.clear(); |
| 1843 | death_test_count_ = 0; |
| 1844 | elapsed_time_ = 0; |
| 1845 | } |
| 1846 | |
| 1847 | // Returns true iff the test failed. |
| 1848 | bool TestResult::Failed() const { |
| 1849 | for (int i = 0; i < total_part_count(); ++i) { |
| 1850 | if (GetTestPartResult(i).failed()) |
| 1851 | return true; |
| 1852 | } |
| 1853 | return false; |
| 1854 | } |
| 1855 | |
| 1856 | // Returns true iff the test part fatally failed. |
| 1857 | static bool TestPartFatallyFailed(const TestPartResult& result) { |
| 1858 | return result.fatally_failed(); |
| 1859 | } |
| 1860 | |
| 1861 | // Returns true iff the test fatally failed. |
| 1862 | bool TestResult::HasFatalFailure() const { |
| 1863 | return CountIf(test_part_results_, TestPartFatallyFailed) > 0; |
| 1864 | } |
| 1865 | |
| 1866 | // Returns true iff the test part non-fatally failed. |
| 1867 | static bool TestPartNonfatallyFailed(const TestPartResult& result) { |
| 1868 | return result.nonfatally_failed(); |
| 1869 | } |
| 1870 | |
| 1871 | // Returns true iff the test has a non-fatal failure. |
| 1872 | bool TestResult::HasNonfatalFailure() const { |
| 1873 | return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; |
| 1874 | } |
| 1875 | |
| 1876 | // Gets the number of all test parts. This is the sum of the number |
| 1877 | // of successful test parts and the number of failed test parts. |
| 1878 | int TestResult::total_part_count() const { |
| 1879 | return static_cast<int>(test_part_results_.size()); |
| 1880 | } |
| 1881 | |
| 1882 | // Returns the number of the test properties. |
| 1883 | int TestResult::test_property_count() const { |
| 1884 | return static_cast<int>(test_properties_.size()); |
| 1885 | } |
| 1886 | |
| 1887 | // class Test |
| 1888 | |
| 1889 | // Creates a Test object. |
| 1890 | |
| 1891 | // The c'tor saves the values of all Google Test flags. |
| 1892 | Test::Test() |
| 1893 | : gtest_flag_saver_(new internal::GTestFlagSaver) { |
| 1894 | } |
| 1895 | |
| 1896 | // The d'tor restores the values of all Google Test flags. |
| 1897 | Test::~Test() { |
| 1898 | delete gtest_flag_saver_; |
| 1899 | } |
| 1900 | |
| 1901 | // Sets up the test fixture. |
| 1902 | // |
| 1903 | // A sub-class may override this. |
| 1904 | void Test::SetUp() { |
| 1905 | } |
| 1906 | |
| 1907 | // Tears down the test fixture. |
| 1908 | // |
| 1909 | // A sub-class may override this. |
| 1910 | void Test::TearDown() { |
| 1911 | } |
| 1912 | |
| 1913 | // Allows user supplied key value pairs to be recorded for later output. |
| 1914 | void Test::RecordProperty(const std::string& key, const std::string& value) { |
| 1915 | UnitTest::GetInstance()->RecordProperty(key, value); |
| 1916 | } |
| 1917 | |
| 1918 | // Allows user supplied key value pairs to be recorded for later output. |
| 1919 | void Test::RecordProperty(const std::string& key, int value) { |
| 1920 | Message value_message; |
| 1921 | value_message << value; |
| 1922 | RecordProperty(key, value_message.GetString().c_str()); |
| 1923 | } |
| 1924 | |
| 1925 | namespace internal { |
| 1926 | |
| 1927 | void ReportFailureInUnknownLocation(TestPartResult::Type result_type, |
| 1928 | const std::string& message) { |
| 1929 | // This function is a friend of UnitTest and as such has access to |
| 1930 | // AddTestPartResult. |
| 1931 | UnitTest::GetInstance()->AddTestPartResult( |
| 1932 | result_type, |
| 1933 | NULL, // No info about the source file where the exception occurred. |
| 1934 | -1, // We have no info on which line caused the exception. |
| 1935 | message, |
| 1936 | ""); // No stack trace, either. |
| 1937 | } |
| 1938 | |
| 1939 | } // namespace internal |
| 1940 | |
| 1941 | // Google Test requires all tests in the same test case to use the same test |
| 1942 | // fixture class. This function checks if the current test has the |
| 1943 | // same fixture class as the first test in the current test case. If |
| 1944 | // yes, it returns true; otherwise it generates a Google Test failure and |
| 1945 | // returns false. |
| 1946 | bool Test::HasSameFixtureClass() { |
| 1947 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 1948 | const TestCase* const test_case = impl->current_test_case(); |
| 1949 | |
| 1950 | // Info about the first test in the current test case. |
| 1951 | const TestInfo* const first_test_info = test_case->test_info_list()[0]; |
| 1952 | const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; |
| 1953 | const char* const first_test_name = first_test_info->name(); |
| 1954 | |
| 1955 | // Info about the current test. |
| 1956 | const TestInfo* const this_test_info = impl->current_test_info(); |
| 1957 | const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; |
| 1958 | const char* const this_test_name = this_test_info->name(); |
| 1959 | |
| 1960 | if (this_fixture_id != first_fixture_id) { |
| 1961 | // Is the first test defined using TEST? |
| 1962 | const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); |
| 1963 | // Is this test defined using TEST? |
| 1964 | const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); |
| 1965 | |
| 1966 | if (first_is_TEST || this_is_TEST) { |
| 1967 | // The user mixed TEST and TEST_F in this test case - we'll tell |
| 1968 | // him/her how to fix it. |
| 1969 | |
| 1970 | // Gets the name of the TEST and the name of the TEST_F. Note |
| 1971 | // that first_is_TEST and this_is_TEST cannot both be true, as |
| 1972 | // the fixture IDs are different for the two tests. |
| 1973 | const char* const TEST_name = |
| 1974 | first_is_TEST ? first_test_name : this_test_name; |
| 1975 | const char* const TEST_F_name = |
| 1976 | first_is_TEST ? this_test_name : first_test_name; |
| 1977 | |
| 1978 | ADD_FAILURE() |
| 1979 | << "All tests in the same test case must use the same test fixture\n" |
| 1980 | << "class, so mixing TEST_F and TEST in the same test case is\n" |
| 1981 | << "illegal. In test case " << this_test_info->test_case_name() |
| 1982 | << ",\n" |
| 1983 | << "test " << TEST_F_name << " is defined using TEST_F but\n" |
| 1984 | << "test " << TEST_name << " is defined using TEST. You probably\n" |
| 1985 | << "want to change the TEST to TEST_F or move it to another test\n" |
| 1986 | << "case."; |
| 1987 | } else { |
| 1988 | // The user defined two fixture classes with the same name in |
| 1989 | // two namespaces - we'll tell him/her how to fix it. |
| 1990 | ADD_FAILURE() |
| 1991 | << "All tests in the same test case must use the same test fixture\n" |
| 1992 | << "class. However, in test case " |
| 1993 | << this_test_info->test_case_name() << ",\n" |
| 1994 | << "you defined test " << first_test_name |
| 1995 | << " and test " << this_test_name << "\n" |
| 1996 | << "using two different test fixture classes. This can happen if\n" |
| 1997 | << "the two classes are from different namespaces or translation\n" |
| 1998 | << "units and have the same name. You should probably rename one\n" |
| 1999 | << "of the classes to put the tests into different test cases."; |
| 2000 | } |
| 2001 | return false; |
| 2002 | } |
| 2003 | |
| 2004 | return true; |
| 2005 | } |
| 2006 | |
| 2007 | #if GTEST_HAS_SEH |
| 2008 | |
| 2009 | // Adds an "exception thrown" fatal failure to the current test. This |
| 2010 | // function returns its result via an output parameter pointer because VC++ |
| 2011 | // prohibits creation of objects with destructors on stack in functions |
| 2012 | // using __try (see error C2712). |
| 2013 | static std::string* FormatSehExceptionMessage(DWORD exception_code, |
| 2014 | const char* location) { |
| 2015 | Message message; |
| 2016 | message << "SEH exception with code 0x" << std::setbase(16) << |
| 2017 | exception_code << std::setbase(10) << " thrown in " << location << "."; |
| 2018 | |
| 2019 | return new std::string(message.GetString()); |
| 2020 | } |
| 2021 | |
| 2022 | #endif // GTEST_HAS_SEH |
| 2023 | |
| 2024 | namespace internal { |
| 2025 | |
| 2026 | #if GTEST_HAS_EXCEPTIONS |
| 2027 | |
| 2028 | // Adds an "exception thrown" fatal failure to the current test. |
| 2029 | static std::string FormatCxxExceptionMessage(const char* description, |
| 2030 | const char* location) { |
| 2031 | Message message; |
| 2032 | if (description != NULL) { |
| 2033 | message << "C++ exception with description \"" << description << "\""; |
| 2034 | } else { |
| 2035 | message << "Unknown C++ exception"; |
| 2036 | } |
| 2037 | message << " thrown in " << location << "."; |
| 2038 | |
| 2039 | return message.GetString(); |
| 2040 | } |
| 2041 | |
| 2042 | static std::string PrintTestPartResultToString( |
| 2043 | const TestPartResult& test_part_result); |
| 2044 | |
| 2045 | GoogleTestFailureException::GoogleTestFailureException( |
| 2046 | const TestPartResult& failure) |
| 2047 | : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} |
| 2048 | |
| 2049 | #endif // GTEST_HAS_EXCEPTIONS |
| 2050 | |
| 2051 | // We put these helper functions in the internal namespace as IBM's xlC |
| 2052 | // compiler rejects the code if they were declared static. |
| 2053 | |
| 2054 | // Runs the given method and handles SEH exceptions it throws, when |
| 2055 | // SEH is supported; returns the 0-value for type Result in case of an |
| 2056 | // SEH exception. (Microsoft compilers cannot handle SEH and C++ |
| 2057 | // exceptions in the same function. Therefore, we provide a separate |
| 2058 | // wrapper function for handling SEH exceptions.) |
| 2059 | template <class T, typename Result> |
| 2060 | Result HandleSehExceptionsInMethodIfSupported( |
| 2061 | T* object, Result (T::*method)(), const char* location) { |
| 2062 | #if GTEST_HAS_SEH |
| 2063 | __try { |
| 2064 | return (object->*method)(); |
| 2065 | } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT |
| 2066 | GetExceptionCode())) { |
| 2067 | // We create the exception message on the heap because VC++ prohibits |
| 2068 | // creation of objects with destructors on stack in functions using __try |
| 2069 | // (see error C2712). |
| 2070 | std::string* exception_message = FormatSehExceptionMessage( |
| 2071 | GetExceptionCode(), location); |
| 2072 | internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, |
| 2073 | *exception_message); |
| 2074 | delete exception_message; |
| 2075 | return static_cast<Result>(0); |
| 2076 | } |
| 2077 | #else |
| 2078 | (void)location; |
| 2079 | return (object->*method)(); |
| 2080 | #endif // GTEST_HAS_SEH |
| 2081 | } |
| 2082 | |
| 2083 | // Runs the given method and catches and reports C++ and/or SEH-style |
| 2084 | // exceptions, if they are supported; returns the 0-value for type |
| 2085 | // Result in case of an SEH exception. |
| 2086 | template <class T, typename Result> |
| 2087 | Result HandleExceptionsInMethodIfSupported( |
| 2088 | T* object, Result (T::*method)(), const char* location) { |
| 2089 | // NOTE: The user code can affect the way in which Google Test handles |
| 2090 | // exceptions by setting GTEST_FLAG(catch_exceptions), but only before |
| 2091 | // RUN_ALL_TESTS() starts. It is technically possible to check the flag |
| 2092 | // after the exception is caught and either report or re-throw the |
| 2093 | // exception based on the flag's value: |
| 2094 | // |
| 2095 | // try { |
| 2096 | // // Perform the test method. |
| 2097 | // } catch (...) { |
| 2098 | // if (GTEST_FLAG(catch_exceptions)) |
| 2099 | // // Report the exception as failure. |
| 2100 | // else |
| 2101 | // throw; // Re-throws the original exception. |
| 2102 | // } |
| 2103 | // |
| 2104 | // However, the purpose of this flag is to allow the program to drop into |
| 2105 | // the debugger when the exception is thrown. On most platforms, once the |
| 2106 | // control enters the catch block, the exception origin information is |
| 2107 | // lost and the debugger will stop the program at the point of the |
| 2108 | // re-throw in this function -- instead of at the point of the original |
| 2109 | // throw statement in the code under test. For this reason, we perform |
| 2110 | // the check early, sacrificing the ability to affect Google Test's |
| 2111 | // exception handling in the method where the exception is thrown. |
| 2112 | if (internal::GetUnitTestImpl()->catch_exceptions()) { |
| 2113 | #if GTEST_HAS_EXCEPTIONS |
| 2114 | try { |
| 2115 | return HandleSehExceptionsInMethodIfSupported(object, method, location); |
| 2116 | } catch (const internal::GoogleTestFailureException&) { // NOLINT |
| 2117 | // This exception type can only be thrown by a failed Google |
| 2118 | // Test assertion with the intention of letting another testing |
| 2119 | // framework catch it. Therefore we just re-throw it. |
| 2120 | throw; |
| 2121 | } catch (const std::exception& e) { // NOLINT |
| 2122 | internal::ReportFailureInUnknownLocation( |
| 2123 | TestPartResult::kFatalFailure, |
| 2124 | FormatCxxExceptionMessage(e.what(), location)); |
| 2125 | } catch (...) { // NOLINT |
| 2126 | internal::ReportFailureInUnknownLocation( |
| 2127 | TestPartResult::kFatalFailure, |
| 2128 | FormatCxxExceptionMessage(NULL, location)); |
| 2129 | } |
| 2130 | return static_cast<Result>(0); |
| 2131 | #else |
| 2132 | return HandleSehExceptionsInMethodIfSupported(object, method, location); |
| 2133 | #endif // GTEST_HAS_EXCEPTIONS |
| 2134 | } else { |
| 2135 | return (object->*method)(); |
| 2136 | } |
| 2137 | } |
| 2138 | |
| 2139 | } // namespace internal |
| 2140 | |
| 2141 | // Runs the test and updates the test result. |
| 2142 | void Test::Run() { |
| 2143 | if (!HasSameFixtureClass()) return; |
| 2144 | |
| 2145 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 2146 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2147 | internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); |
| 2148 | // We will run the test only if SetUp() was successful. |
| 2149 | if (!HasFatalFailure()) { |
| 2150 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2151 | internal::HandleExceptionsInMethodIfSupported( |
| 2152 | this, &Test::TestBody, "the test body"); |
| 2153 | } |
| 2154 | |
| 2155 | // However, we want to clean up as much as possible. Hence we will |
| 2156 | // always call TearDown(), even if SetUp() or the test body has |
| 2157 | // failed. |
| 2158 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2159 | internal::HandleExceptionsInMethodIfSupported( |
| 2160 | this, &Test::TearDown, "TearDown()"); |
| 2161 | } |
| 2162 | |
| 2163 | // Returns true iff the current test has a fatal failure. |
| 2164 | bool Test::HasFatalFailure() { |
| 2165 | return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); |
| 2166 | } |
| 2167 | |
| 2168 | // Returns true iff the current test has a non-fatal failure. |
| 2169 | bool Test::HasNonfatalFailure() { |
| 2170 | return internal::GetUnitTestImpl()->current_test_result()-> |
| 2171 | HasNonfatalFailure(); |
| 2172 | } |
| 2173 | |
| 2174 | // class TestInfo |
| 2175 | |
| 2176 | // Constructs a TestInfo object. It assumes ownership of the test factory |
| 2177 | // object. |
| 2178 | TestInfo::TestInfo(const std::string& a_test_case_name, |
| 2179 | const std::string& a_name, |
| 2180 | const char* a_type_param, |
| 2181 | const char* a_value_param, |
| 2182 | internal::TypeId fixture_class_id, |
| 2183 | internal::TestFactoryBase* factory) |
| 2184 | : test_case_name_(a_test_case_name), |
| 2185 | name_(a_name), |
| 2186 | type_param_(a_type_param ? new std::string(a_type_param) : NULL), |
| 2187 | value_param_(a_value_param ? new std::string(a_value_param) : NULL), |
| 2188 | fixture_class_id_(fixture_class_id), |
| 2189 | should_run_(false), |
| 2190 | is_disabled_(false), |
| 2191 | matches_filter_(false), |
| 2192 | factory_(factory), |
| 2193 | result_() {} |
| 2194 | |
| 2195 | // Destructs a TestInfo object. |
| 2196 | TestInfo::~TestInfo() { delete factory_; } |
| 2197 | |
| 2198 | namespace internal { |
| 2199 | |
| 2200 | // Creates a new TestInfo object and registers it with Google Test; |
| 2201 | // returns the created object. |
| 2202 | // |
| 2203 | // Arguments: |
| 2204 | // |
| 2205 | // test_case_name: name of the test case |
| 2206 | // name: name of the test |
| 2207 | // type_param: the name of the test's type parameter, or NULL if |
| 2208 | // this is not a typed or a type-parameterized test. |
| 2209 | // value_param: text representation of the test's value parameter, |
| 2210 | // or NULL if this is not a value-parameterized test. |
| 2211 | // fixture_class_id: ID of the test fixture class |
| 2212 | // set_up_tc: pointer to the function that sets up the test case |
| 2213 | // tear_down_tc: pointer to the function that tears down the test case |
| 2214 | // factory: pointer to the factory that creates a test object. |
| 2215 | // The newly created TestInfo instance will assume |
| 2216 | // ownership of the factory object. |
| 2217 | TestInfo* MakeAndRegisterTestInfo( |
| 2218 | const char* test_case_name, |
| 2219 | const char* name, |
| 2220 | const char* type_param, |
| 2221 | const char* value_param, |
| 2222 | TypeId fixture_class_id, |
| 2223 | SetUpTestCaseFunc set_up_tc, |
| 2224 | TearDownTestCaseFunc tear_down_tc, |
| 2225 | TestFactoryBase* factory) { |
| 2226 | TestInfo* const test_info = |
| 2227 | new TestInfo(test_case_name, name, type_param, value_param, |
| 2228 | fixture_class_id, factory); |
| 2229 | GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); |
| 2230 | return test_info; |
| 2231 | } |
| 2232 | |
| 2233 | #if GTEST_HAS_PARAM_TEST |
| 2234 | void ReportInvalidTestCaseType(const char* test_case_name, |
| 2235 | const char* file, int line) { |
| 2236 | Message errors; |
| 2237 | errors |
| 2238 | << "Attempted redefinition of test case " << test_case_name << ".\n" |
| 2239 | << "All tests in the same test case must use the same test fixture\n" |
| 2240 | << "class. However, in test case " << test_case_name << ", you tried\n" |
| 2241 | << "to define a test using a fixture class different from the one\n" |
| 2242 | << "used earlier. This can happen if the two fixture classes are\n" |
| 2243 | << "from different namespaces and have the same name. You should\n" |
| 2244 | << "probably rename one of the classes to put the tests into different\n" |
| 2245 | << "test cases."; |
| 2246 | |
| 2247 | fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), |
| 2248 | errors.GetString().c_str()); |
| 2249 | } |
| 2250 | #endif // GTEST_HAS_PARAM_TEST |
| 2251 | |
| 2252 | } // namespace internal |
| 2253 | |
| 2254 | namespace { |
| 2255 | |
| 2256 | // A predicate that checks the test name of a TestInfo against a known |
| 2257 | // value. |
| 2258 | // |
| 2259 | // This is used for implementation of the TestCase class only. We put |
| 2260 | // it in the anonymous namespace to prevent polluting the outer |
| 2261 | // namespace. |
| 2262 | // |
| 2263 | // TestNameIs is copyable. |
| 2264 | class TestNameIs { |
| 2265 | public: |
| 2266 | // Constructor. |
| 2267 | // |
| 2268 | // TestNameIs has NO default constructor. |
| 2269 | explicit TestNameIs(const char* name) |
| 2270 | : name_(name) {} |
| 2271 | |
| 2272 | // Returns true iff the test name of test_info matches name_. |
| 2273 | bool operator()(const TestInfo * test_info) const { |
| 2274 | return test_info && test_info->name() == name_; |
| 2275 | } |
| 2276 | |
| 2277 | private: |
| 2278 | std::string name_; |
| 2279 | }; |
| 2280 | |
| 2281 | } // namespace |
| 2282 | |
| 2283 | namespace internal { |
| 2284 | |
| 2285 | // This method expands all parameterized tests registered with macros TEST_P |
| 2286 | // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. |
| 2287 | // This will be done just once during the program runtime. |
| 2288 | void UnitTestImpl::RegisterParameterizedTests() { |
| 2289 | #if GTEST_HAS_PARAM_TEST |
| 2290 | if (!parameterized_tests_registered_) { |
| 2291 | parameterized_test_registry_.RegisterTests(); |
| 2292 | parameterized_tests_registered_ = true; |
| 2293 | } |
| 2294 | #endif |
| 2295 | } |
| 2296 | |
| 2297 | } // namespace internal |
| 2298 | |
| 2299 | // Creates the test object, runs it, records its result, and then |
| 2300 | // deletes it. |
| 2301 | void TestInfo::Run() { |
| 2302 | if (!should_run_) return; |
| 2303 | |
| 2304 | // Tells UnitTest where to store test result. |
| 2305 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 2306 | impl->set_current_test_info(this); |
| 2307 | |
| 2308 | TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); |
| 2309 | |
| 2310 | // Notifies the unit test event listeners that a test is about to start. |
| 2311 | repeater->OnTestStart(*this); |
| 2312 | |
| 2313 | const TimeInMillis start = internal::GetTimeInMillis(); |
| 2314 | |
| 2315 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2316 | |
| 2317 | // Creates the test object. |
| 2318 | Test* const test = internal::HandleExceptionsInMethodIfSupported( |
| 2319 | factory_, &internal::TestFactoryBase::CreateTest, |
| 2320 | "the test fixture's constructor"); |
| 2321 | |
| 2322 | // Runs the test only if the test object was created and its |
| 2323 | // constructor didn't generate a fatal failure. |
| 2324 | if ((test != NULL) && !Test::HasFatalFailure()) { |
| 2325 | // This doesn't throw as all user code that can throw are wrapped into |
| 2326 | // exception handling code. |
| 2327 | test->Run(); |
| 2328 | } |
| 2329 | |
| 2330 | // Deletes the test object. |
| 2331 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2332 | internal::HandleExceptionsInMethodIfSupported( |
| 2333 | test, &Test::DeleteSelf_, "the test fixture's destructor"); |
| 2334 | |
| 2335 | result_.set_elapsed_time(internal::GetTimeInMillis() - start); |
| 2336 | |
| 2337 | // Notifies the unit test event listener that a test has just finished. |
| 2338 | repeater->OnTestEnd(*this); |
| 2339 | |
| 2340 | // Tells UnitTest to stop associating assertion results to this |
| 2341 | // test. |
| 2342 | impl->set_current_test_info(NULL); |
| 2343 | } |
| 2344 | |
| 2345 | // class TestCase |
| 2346 | |
| 2347 | // Gets the number of successful tests in this test case. |
| 2348 | int TestCase::successful_test_count() const { |
| 2349 | return CountIf(test_info_list_, TestPassed); |
| 2350 | } |
| 2351 | |
| 2352 | // Gets the number of failed tests in this test case. |
| 2353 | int TestCase::failed_test_count() const { |
| 2354 | return CountIf(test_info_list_, TestFailed); |
| 2355 | } |
| 2356 | |
| 2357 | // Gets the number of disabled tests that will be reported in the XML report. |
| 2358 | int TestCase::reportable_disabled_test_count() const { |
| 2359 | return CountIf(test_info_list_, TestReportableDisabled); |
| 2360 | } |
| 2361 | |
| 2362 | // Gets the number of disabled tests in this test case. |
| 2363 | int TestCase::disabled_test_count() const { |
| 2364 | return CountIf(test_info_list_, TestDisabled); |
| 2365 | } |
| 2366 | |
| 2367 | // Gets the number of tests to be printed in the XML report. |
| 2368 | int TestCase::reportable_test_count() const { |
| 2369 | return CountIf(test_info_list_, TestReportable); |
| 2370 | } |
| 2371 | |
| 2372 | // Get the number of tests in this test case that should run. |
| 2373 | int TestCase::test_to_run_count() const { |
| 2374 | return CountIf(test_info_list_, ShouldRunTest); |
| 2375 | } |
| 2376 | |
| 2377 | // Gets the number of all tests. |
| 2378 | int TestCase::total_test_count() const { |
| 2379 | return static_cast<int>(test_info_list_.size()); |
| 2380 | } |
| 2381 | |
| 2382 | // Creates a TestCase with the given name. |
| 2383 | // |
| 2384 | // Arguments: |
| 2385 | // |
| 2386 | // name: name of the test case |
| 2387 | // a_type_param: the name of the test case's type parameter, or NULL if |
| 2388 | // this is not a typed or a type-parameterized test case. |
| 2389 | // set_up_tc: pointer to the function that sets up the test case |
| 2390 | // tear_down_tc: pointer to the function that tears down the test case |
| 2391 | TestCase::TestCase(const char* a_name, const char* a_type_param, |
| 2392 | Test::SetUpTestCaseFunc set_up_tc, |
| 2393 | Test::TearDownTestCaseFunc tear_down_tc) |
| 2394 | : name_(a_name), |
| 2395 | type_param_(a_type_param ? new std::string(a_type_param) : NULL), |
| 2396 | set_up_tc_(set_up_tc), |
| 2397 | tear_down_tc_(tear_down_tc), |
| 2398 | should_run_(false), |
| 2399 | elapsed_time_(0) { |
| 2400 | } |
| 2401 | |
| 2402 | // Destructor of TestCase. |
| 2403 | TestCase::~TestCase() { |
| 2404 | // Deletes every Test in the collection. |
| 2405 | ForEach(test_info_list_, internal::Delete<TestInfo>); |
| 2406 | } |
| 2407 | |
| 2408 | // Returns the i-th test among all the tests. i can range from 0 to |
| 2409 | // total_test_count() - 1. If i is not in that range, returns NULL. |
| 2410 | const TestInfo* TestCase::GetTestInfo(int i) const { |
| 2411 | const int index = GetElementOr(test_indices_, i, -1); |
| 2412 | return index < 0 ? NULL : test_info_list_[index]; |
| 2413 | } |
| 2414 | |
| 2415 | // Returns the i-th test among all the tests. i can range from 0 to |
| 2416 | // total_test_count() - 1. If i is not in that range, returns NULL. |
| 2417 | TestInfo* TestCase::GetMutableTestInfo(int i) { |
| 2418 | const int index = GetElementOr(test_indices_, i, -1); |
| 2419 | return index < 0 ? NULL : test_info_list_[index]; |
| 2420 | } |
| 2421 | |
| 2422 | // Adds a test to this test case. Will delete the test upon |
| 2423 | // destruction of the TestCase object. |
| 2424 | void TestCase::AddTestInfo(TestInfo * test_info) { |
| 2425 | test_info_list_.push_back(test_info); |
| 2426 | test_indices_.push_back(static_cast<int>(test_indices_.size())); |
| 2427 | } |
| 2428 | |
| 2429 | // Runs every test in this TestCase. |
| 2430 | void TestCase::Run() { |
| 2431 | if (!should_run_) return; |
| 2432 | |
| 2433 | internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); |
| 2434 | impl->set_current_test_case(this); |
| 2435 | |
| 2436 | TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); |
| 2437 | |
| 2438 | repeater->OnTestCaseStart(*this); |
| 2439 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2440 | internal::HandleExceptionsInMethodIfSupported( |
| 2441 | this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); |
| 2442 | |
| 2443 | const internal::TimeInMillis start = internal::GetTimeInMillis(); |
| 2444 | for (int i = 0; i < total_test_count(); i++) { |
| 2445 | GetMutableTestInfo(i)->Run(); |
| 2446 | } |
| 2447 | elapsed_time_ = internal::GetTimeInMillis() - start; |
| 2448 | |
| 2449 | impl->os_stack_trace_getter()->UponLeavingGTest(); |
| 2450 | internal::HandleExceptionsInMethodIfSupported( |
| 2451 | this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); |
| 2452 | |
| 2453 | repeater->OnTestCaseEnd(*this); |
| 2454 | impl->set_current_test_case(NULL); |
| 2455 | } |
| 2456 | |
| 2457 | // Clears the results of all tests in this test case. |
| 2458 | void TestCase::ClearResult() { |
| 2459 | ad_hoc_test_result_.Clear(); |
| 2460 | ForEach(test_info_list_, TestInfo::ClearTestResult); |
| 2461 | } |
| 2462 | |
| 2463 | // Shuffles the tests in this test case. |
| 2464 | void TestCase::ShuffleTests(internal::Random* random) { |
| 2465 | Shuffle(random, &test_indices_); |
| 2466 | } |
| 2467 | |
| 2468 | // Restores the test order to before the first shuffle. |
| 2469 | void TestCase::UnshuffleTests() { |
| 2470 | for (size_t i = 0; i < test_indices_.size(); i++) { |
| 2471 | test_indices_[i] = static_cast<int>(i); |
| 2472 | } |
| 2473 | } |
| 2474 | |
| 2475 | // Formats a countable noun. Depending on its quantity, either the |
| 2476 | // singular form or the plural form is used. e.g. |
| 2477 | // |
| 2478 | // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". |
| 2479 | // FormatCountableNoun(5, "book", "books") returns "5 books". |
| 2480 | static std::string FormatCountableNoun(int count, |
| 2481 | const char * singular_form, |
| 2482 | const char * plural_form) { |
| 2483 | return internal::StreamableToString(count) + " " + |
| 2484 | (count == 1 ? singular_form : plural_form); |
| 2485 | } |
| 2486 | |
| 2487 | // Formats the count of tests. |
| 2488 | static std::string FormatTestCount(int test_count) { |
| 2489 | return FormatCountableNoun(test_count, "test", "tests"); |
| 2490 | } |
| 2491 | |
| 2492 | // Formats the count of test cases. |
| 2493 | static std::string FormatTestCaseCount(int test_case_count) { |
| 2494 | return FormatCountableNoun(test_case_count, "test case", "test cases"); |
| 2495 | } |
| 2496 | |
| 2497 | // Converts a TestPartResult::Type enum to human-friendly string |
| 2498 | // representation. Both kNonFatalFailure and kFatalFailure are translated |
| 2499 | // to "Failure", as the user usually doesn't care about the difference |
| 2500 | // between the two when viewing the test result. |
| 2501 | static const char * TestPartResultTypeToString(TestPartResult::Type type) { |
| 2502 | switch (type) { |
| 2503 | case TestPartResult::kSuccess: |
| 2504 | return "Success"; |
| 2505 | |
| 2506 | case TestPartResult::kNonFatalFailure: |
| 2507 | case TestPartResult::kFatalFailure: |
| 2508 | #ifdef _MSC_VER |
| 2509 | return "error: "; |
| 2510 | #else |
| 2511 | return "Failure\n"; |
| 2512 | #endif |
| 2513 | default: |
| 2514 | return "Unknown result type"; |
| 2515 | } |
| 2516 | } |
| 2517 | |
| 2518 | namespace internal { |
| 2519 | |
| 2520 | // Prints a TestPartResult to an std::string. |
| 2521 | static std::string PrintTestPartResultToString( |
| 2522 | const TestPartResult& test_part_result) { |
| 2523 | return (Message() |
| 2524 | << internal::FormatFileLocation(test_part_result.file_name(), |
| 2525 | test_part_result.line_number()) |
| 2526 | << " " << TestPartResultTypeToString(test_part_result.type()) |
| 2527 | << test_part_result.message()).GetString(); |
| 2528 | } |
| 2529 | |
| 2530 | // Prints a TestPartResult. |
| 2531 | static void PrintTestPartResult(const TestPartResult& test_part_result) { |
| 2532 | const std::string& result = |
| 2533 | PrintTestPartResultToString(test_part_result); |
| 2534 | printf("%s\n", result.c_str()); |
| 2535 | fflush(stdout); |
| 2536 | // If the test program runs in Visual Studio or a debugger, the |
| 2537 | // following statements add the test part result message to the Output |
| 2538 | // window such that the user can double-click on it to jump to the |
| 2539 | // corresponding source code location; otherwise they do nothing. |
| 2540 | #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE |
| 2541 | // We don't call OutputDebugString*() on Windows Mobile, as printing |
| 2542 | // to stdout is done by OutputDebugString() there already - we don't |
| 2543 | // want the same message printed twice. |
| 2544 | ::OutputDebugStringA(result.c_str()); |
| 2545 | ::OutputDebugStringA("\n"); |
| 2546 | #endif |
| 2547 | } |
| 2548 | |
| 2549 | // class PrettyUnitTestResultPrinter |
| 2550 | |
| 2551 | enum GTestColor { |
| 2552 | COLOR_DEFAULT, |
| 2553 | COLOR_RED, |
| 2554 | COLOR_GREEN, |
| 2555 | COLOR_YELLOW |
| 2556 | }; |
| 2557 | |
| 2558 | #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ |
| 2559 | !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT |
| 2560 | |
| 2561 | // Returns the character attribute for the given color. |
| 2562 | WORD GetColorAttribute(GTestColor color) { |
| 2563 | switch (color) { |
| 2564 | case COLOR_RED: return FOREGROUND_RED; |
| 2565 | case COLOR_GREEN: return FOREGROUND_GREEN; |
| 2566 | case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; |
| 2567 | default: return 0; |
| 2568 | } |
| 2569 | } |
| 2570 | |
| 2571 | #else |
| 2572 | |
| 2573 | // Returns the ANSI color code for the given color. COLOR_DEFAULT is |
| 2574 | // an invalid input. |
| 2575 | const char* GetAnsiColorCode(GTestColor color) { |
| 2576 | switch (color) { |
| 2577 | case COLOR_RED: return "1"; |
| 2578 | case COLOR_GREEN: return "2"; |
| 2579 | case COLOR_YELLOW: return "3"; |
| 2580 | default: return NULL; |
| 2581 | }; |
| 2582 | } |
| 2583 | |
| 2584 | #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE |
| 2585 | |
| 2586 | // Returns true iff Google Test should use colors in the output. |
| 2587 | bool ShouldUseColor(bool stdout_is_tty) { |
| 2588 | const char* const gtest_color = GTEST_FLAG(color).c_str(); |
| 2589 | |
| 2590 | if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { |
| 2591 | #if GTEST_OS_WINDOWS |
| 2592 | // On Windows the TERM variable is usually not set, but the |
| 2593 | // console there does support colors. |
| 2594 | return stdout_is_tty; |
| 2595 | #else |
| 2596 | // On non-Windows platforms, we rely on the TERM variable. |
| 2597 | const char* const term = posix::GetEnv("TERM"); |
| 2598 | const bool term_supports_color = |
| 2599 | String::CStringEquals(term, "xterm") || |
| 2600 | String::CStringEquals(term, "xterm-color") || |
| 2601 | String::CStringEquals(term, "xterm-256color") || |
| 2602 | String::CStringEquals(term, "screen") || |
| 2603 | String::CStringEquals(term, "screen-256color") || |
| 2604 | String::CStringEquals(term, "linux") || |
| 2605 | String::CStringEquals(term, "cygwin"); |
| 2606 | return stdout_is_tty && term_supports_color; |
| 2607 | #endif // GTEST_OS_WINDOWS |
| 2608 | } |
| 2609 | |
| 2610 | return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || |
| 2611 | String::CaseInsensitiveCStringEquals(gtest_color, "true") || |
| 2612 | String::CaseInsensitiveCStringEquals(gtest_color, "t") || |
| 2613 | String::CStringEquals(gtest_color, "1"); |
| 2614 | // We take "yes", "true", "t", and "1" as meaning "yes". If the |
| 2615 | // value is neither one of these nor "auto", we treat it as "no" to |
| 2616 | // be conservative. |
| 2617 | } |
| 2618 | |
| 2619 | // Helpers for printing colored strings to stdout. Note that on Windows, we |
| 2620 | // cannot simply emit special characters and have the terminal change colors. |
| 2621 | // This routine must actually emit the characters rather than return a string |
| 2622 | // that would be colored when printed, as can be done on Linux. |
| 2623 | void ColoredPrintf(GTestColor color, const char* fmt, ...) { |
| 2624 | va_list args; |
| 2625 | va_start(args, fmt); |
| 2626 | |
| 2627 | #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ |
| 2628 | GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT |
| 2629 | const bool use_color = false; |
| 2630 | #else |
| 2631 | static const bool in_color_mode = |
| 2632 | ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); |
| 2633 | const bool use_color = in_color_mode && (color != COLOR_DEFAULT); |
| 2634 | #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS |
| 2635 | // The '!= 0' comparison is necessary to satisfy MSVC 7.1. |
| 2636 | |
| 2637 | if (!use_color) { |
| 2638 | vprintf(fmt, args); |
| 2639 | va_end(args); |
| 2640 | return; |
| 2641 | } |
| 2642 | |
| 2643 | #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ |
| 2644 | !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT |
| 2645 | const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); |
| 2646 | |
| 2647 | // Gets the current text color. |
| 2648 | CONSOLE_SCREEN_BUFFER_INFO buffer_info; |
| 2649 | GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); |
| 2650 | const WORD old_color_attrs = buffer_info.wAttributes; |
| 2651 | |
| 2652 | // We need to flush the stream buffers into the console before each |
| 2653 | // SetConsoleTextAttribute call lest it affect the text that is already |
| 2654 | // printed but has not yet reached the console. |
| 2655 | fflush(stdout); |
| 2656 | SetConsoleTextAttribute(stdout_handle, |
| 2657 | GetColorAttribute(color) | FOREGROUND_INTENSITY); |
| 2658 | vprintf(fmt, args); |
| 2659 | |
| 2660 | fflush(stdout); |
| 2661 | // Restores the text color. |
| 2662 | SetConsoleTextAttribute(stdout_handle, old_color_attrs); |
| 2663 | #else |
| 2664 | printf("\033[0;3%sm", GetAnsiColorCode(color)); |
| 2665 | vprintf(fmt, args); |
| 2666 | printf("\033[m"); // Resets the terminal to default. |
| 2667 | #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE |
| 2668 | va_end(args); |
| 2669 | } |
| 2670 | |
| 2671 | // Text printed in Google Test's text output and --gunit_list_tests |
| 2672 | // output to label the type parameter and value parameter for a test. |
| 2673 | static const char kTypeParamLabel[] = "TypeParam"; |
| 2674 | static const char kValueParamLabel[] = "GetParam()"; |
| 2675 | |
| 2676 | void PrintFullTestCommentIfPresent(const TestInfo& test_info) { |
| 2677 | const char* const type_param = test_info.type_param(); |
| 2678 | const char* const value_param = test_info.value_param(); |
| 2679 | |
| 2680 | if (type_param != NULL || value_param != NULL) { |
| 2681 | printf(", where "); |
| 2682 | if (type_param != NULL) { |
| 2683 | printf("%s = %s", kTypeParamLabel, type_param); |
| 2684 | if (value_param != NULL) |
| 2685 | printf(" and "); |
| 2686 | } |
| 2687 | if (value_param != NULL) { |
| 2688 | printf("%s = %s", kValueParamLabel, value_param); |
| 2689 | } |
| 2690 | } |
| 2691 | } |
| 2692 | |
| 2693 | // This class implements the TestEventListener interface. |
| 2694 | // |
| 2695 | // Class PrettyUnitTestResultPrinter is copyable. |
| 2696 | class PrettyUnitTestResultPrinter : public TestEventListener { |
| 2697 | public: |
| 2698 | PrettyUnitTestResultPrinter() {} |
| 2699 | static void PrintTestName(const char * test_case, const char * test) { |
| 2700 | printf("%s.%s", test_case, test); |
| 2701 | } |
| 2702 | |
| 2703 | // The following methods override what's in the TestEventListener class. |
| 2704 | virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} |
| 2705 | virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); |
| 2706 | virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); |
| 2707 | virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} |
| 2708 | virtual void OnTestCaseStart(const TestCase& test_case); |
| 2709 | virtual void OnTestStart(const TestInfo& test_info); |
| 2710 | virtual void OnTestPartResult(const TestPartResult& result); |
| 2711 | virtual void OnTestEnd(const TestInfo& test_info); |
| 2712 | virtual void OnTestCaseEnd(const TestCase& test_case); |
| 2713 | virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); |
| 2714 | virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} |
| 2715 | virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); |
| 2716 | virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} |
| 2717 | |
| 2718 | private: |
| 2719 | static void PrintFailedTests(const UnitTest& unit_test); |
| 2720 | }; |
| 2721 | |
| 2722 | // Fired before each iteration of tests starts. |
| 2723 | void PrettyUnitTestResultPrinter::OnTestIterationStart( |
| 2724 | const UnitTest& unit_test, int iteration) { |
| 2725 | if (GTEST_FLAG(repeat) != 1) |
| 2726 | printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); |
| 2727 | |
| 2728 | const char* const filter = GTEST_FLAG(filter).c_str(); |
| 2729 | |
| 2730 | // Prints the filter if it's not *. This reminds the user that some |
| 2731 | // tests may be skipped. |
| 2732 | if (!String::CStringEquals(filter, kUniversalFilter)) { |
| 2733 | ColoredPrintf(COLOR_YELLOW, |
| 2734 | "Note: %s filter = %s\n", GTEST_NAME_, filter); |
| 2735 | } |
| 2736 | |
| 2737 | if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { |
| 2738 | const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); |
| 2739 | ColoredPrintf(COLOR_YELLOW, |
| 2740 | "Note: This is test shard %d of %s.\n", |
| 2741 | static_cast<int>(shard_index) + 1, |
| 2742 | internal::posix::GetEnv(kTestTotalShards)); |
| 2743 | } |
| 2744 | |
| 2745 | if (GTEST_FLAG(shuffle)) { |
| 2746 | ColoredPrintf(COLOR_YELLOW, |
| 2747 | "Note: Randomizing tests' orders with a seed of %d .\n", |
| 2748 | unit_test.random_seed()); |
| 2749 | } |
| 2750 | |
| 2751 | ColoredPrintf(COLOR_GREEN, "[==========] "); |
| 2752 | printf("Running %s from %s.\n", |
| 2753 | FormatTestCount(unit_test.test_to_run_count()).c_str(), |
| 2754 | FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); |
| 2755 | fflush(stdout); |
| 2756 | } |
| 2757 | |
| 2758 | void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( |
| 2759 | const UnitTest& /*unit_test*/) { |
| 2760 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2761 | printf("Global test environment set-up.\n"); |
| 2762 | fflush(stdout); |
| 2763 | } |
| 2764 | |
| 2765 | void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { |
| 2766 | const std::string counts = |
| 2767 | FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); |
| 2768 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2769 | printf("%s from %s", counts.c_str(), test_case.name()); |
| 2770 | if (test_case.type_param() == NULL) { |
| 2771 | printf("\n"); |
| 2772 | } else { |
| 2773 | printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); |
| 2774 | } |
| 2775 | fflush(stdout); |
| 2776 | } |
| 2777 | |
| 2778 | void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { |
| 2779 | ColoredPrintf(COLOR_GREEN, "[ RUN ] "); |
| 2780 | PrintTestName(test_info.test_case_name(), test_info.name()); |
| 2781 | printf("\n"); |
| 2782 | fflush(stdout); |
| 2783 | } |
| 2784 | |
| 2785 | // Called after an assertion failure. |
| 2786 | void PrettyUnitTestResultPrinter::OnTestPartResult( |
| 2787 | const TestPartResult& result) { |
| 2788 | // If the test part succeeded, we don't need to do anything. |
| 2789 | if (result.type() == TestPartResult::kSuccess) |
| 2790 | return; |
| 2791 | |
| 2792 | // Print failure message from the assertion (e.g. expected this and got that). |
| 2793 | PrintTestPartResult(result); |
| 2794 | fflush(stdout); |
| 2795 | } |
| 2796 | |
| 2797 | void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { |
| 2798 | if (test_info.result()->Passed()) { |
| 2799 | ColoredPrintf(COLOR_GREEN, "[ OK ] "); |
| 2800 | } else { |
| 2801 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2802 | } |
| 2803 | PrintTestName(test_info.test_case_name(), test_info.name()); |
| 2804 | if (test_info.result()->Failed()) |
| 2805 | PrintFullTestCommentIfPresent(test_info); |
| 2806 | |
| 2807 | if (GTEST_FLAG(print_time)) { |
| 2808 | printf(" (%s ms)\n", internal::StreamableToString( |
| 2809 | test_info.result()->elapsed_time()).c_str()); |
| 2810 | } else { |
| 2811 | printf("\n"); |
| 2812 | } |
| 2813 | fflush(stdout); |
| 2814 | } |
| 2815 | |
| 2816 | void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { |
| 2817 | if (!GTEST_FLAG(print_time)) return; |
| 2818 | |
| 2819 | const std::string counts = |
| 2820 | FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); |
| 2821 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2822 | printf("%s from %s (%s ms total)\n\n", |
| 2823 | counts.c_str(), test_case.name(), |
| 2824 | internal::StreamableToString(test_case.elapsed_time()).c_str()); |
| 2825 | fflush(stdout); |
| 2826 | } |
| 2827 | |
| 2828 | void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( |
| 2829 | const UnitTest& /*unit_test*/) { |
| 2830 | ColoredPrintf(COLOR_GREEN, "[----------] "); |
| 2831 | printf("Global test environment tear-down\n"); |
| 2832 | fflush(stdout); |
| 2833 | } |
| 2834 | |
| 2835 | // Internal helper for printing the list of failed tests. |
| 2836 | void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { |
| 2837 | const int failed_test_count = unit_test.failed_test_count(); |
| 2838 | if (failed_test_count == 0) { |
| 2839 | return; |
| 2840 | } |
| 2841 | |
| 2842 | for (int i = 0; i < unit_test.total_test_case_count(); ++i) { |
| 2843 | const TestCase& test_case = *unit_test.GetTestCase(i); |
| 2844 | if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { |
| 2845 | continue; |
| 2846 | } |
| 2847 | for (int j = 0; j < test_case.total_test_count(); ++j) { |
| 2848 | const TestInfo& test_info = *test_case.GetTestInfo(j); |
| 2849 | if (!test_info.should_run() || test_info.result()->Passed()) { |
| 2850 | continue; |
| 2851 | } |
| 2852 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2853 | printf("%s.%s", test_case.name(), test_info.name()); |
| 2854 | PrintFullTestCommentIfPresent(test_info); |
| 2855 | printf("\n"); |
| 2856 | } |
| 2857 | } |
| 2858 | } |
| 2859 | |
| 2860 | void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, |
| 2861 | int /*iteration*/) { |
| 2862 | ColoredPrintf(COLOR_GREEN, "[==========] "); |
| 2863 | printf("%s from %s ran.", |
| 2864 | FormatTestCount(unit_test.test_to_run_count()).c_str(), |
| 2865 | FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); |
| 2866 | if (GTEST_FLAG(print_time)) { |
| 2867 | printf(" (%s ms total)", |
| 2868 | internal::StreamableToString(unit_test.elapsed_time()).c_str()); |
| 2869 | } |
| 2870 | printf("\n"); |
| 2871 | ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); |
| 2872 | printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); |
| 2873 | |
| 2874 | int num_failures = unit_test.failed_test_count(); |
| 2875 | if (!unit_test.Passed()) { |
| 2876 | const int failed_test_count = unit_test.failed_test_count(); |
| 2877 | ColoredPrintf(COLOR_RED, "[ FAILED ] "); |
| 2878 | printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); |
| 2879 | PrintFailedTests(unit_test); |
| 2880 | printf("\n%2d FAILED %s\n", num_failures, |
| 2881 | num_failures == 1 ? "TEST" : "TESTS"); |
| 2882 | } |
| 2883 | |
| 2884 | int num_disabled = unit_test.reportable_disabled_test_count(); |
| 2885 | if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { |
| 2886 | if (!num_failures) { |
| 2887 | printf("\n"); // Add a spacer if no FAILURE banner is displayed. |
| 2888 | } |
| 2889 | ColoredPrintf(COLOR_YELLOW, |
| 2890 | " YOU HAVE %d DISABLED %s\n\n", |
| 2891 | num_disabled, |
| 2892 | num_disabled == 1 ? "TEST" : "TESTS"); |
| 2893 | } |
| 2894 | // Ensure that Google Test output is printed before, e.g., heapchecker output. |
| 2895 | fflush(stdout); |
| 2896 | } |
| 2897 | |
| 2898 | // End PrettyUnitTestResultPrinter |
| 2899 | |
| 2900 | // class TestEventRepeater |
| 2901 | // |
| 2902 | // This class forwards events to other event listeners. |
| 2903 | class TestEventRepeater : public TestEventListener { |
| 2904 | public: |
| 2905 | TestEventRepeater() : forwarding_enabled_(true) {} |
| 2906 | virtual ~TestEventRepeater(); |
| 2907 | void Append(TestEventListener *listener); |
| 2908 | TestEventListener* Release(TestEventListener* listener); |
| 2909 | |
| 2910 | // Controls whether events will be forwarded to listeners_. Set to false |
| 2911 | // in death test child processes. |
| 2912 | bool forwarding_enabled() const { return forwarding_enabled_; } |
| 2913 | void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } |
| 2914 | |
| 2915 | virtual void OnTestProgramStart(const UnitTest& unit_test); |
| 2916 | virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); |
| 2917 | virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); |
| 2918 | virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); |
| 2919 | virtual void OnTestCaseStart(const TestCase& test_case); |
| 2920 | virtual void OnTestStart(const TestInfo& test_info); |
| 2921 | virtual void OnTestPartResult(const TestPartResult& result); |
| 2922 | virtual void OnTestEnd(const TestInfo& test_info); |
| 2923 | virtual void OnTestCaseEnd(const TestCase& test_case); |
| 2924 | virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); |
| 2925 | virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); |
| 2926 | virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); |
| 2927 | virtual void OnTestProgramEnd(const UnitTest& unit_test); |
| 2928 | |
| 2929 | private: |
| 2930 | // Controls whether events will be forwarded to listeners_. Set to false |
| 2931 | // in death test child processes. |
| 2932 | bool forwarding_enabled_; |
| 2933 | // The list of listeners that receive events. |
| 2934 | std::vector<TestEventListener*> listeners_; |
| 2935 | |
| 2936 | GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); |
| 2937 | }; |
| 2938 | |
| 2939 | TestEventRepeater::~TestEventRepeater() { |
| 2940 | ForEach(listeners_, Delete<TestEventListener>); |
| 2941 | } |
| 2942 | |
| 2943 | void TestEventRepeater::Append(TestEventListener *listener) { |
| 2944 | listeners_.push_back(listener); |
| 2945 | } |
| 2946 | |
| 2947 | // TODO(vladl@google.com): Factor the search functionality into Vector::Find. |
| 2948 | TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { |
| 2949 | for (size_t i = 0; i < listeners_.size(); ++i) { |
| 2950 | if (listeners_[i] == listener) { |
| 2951 | listeners_.erase(listeners_.begin() + i); |
| 2952 | return listener; |
| 2953 | } |
| 2954 | } |
| 2955 | |
| 2956 | return NULL; |
| 2957 | } |
| 2958 | |
| 2959 | // Since most methods are very similar, use macros to reduce boilerplate. |
| 2960 | // This defines a member that forwards the call to all listeners. |
| 2961 | #define GTEST_REPEATER_METHOD_(Name, Type) \ |
| 2962 | void TestEventRepeater::Name(const Type& parameter) { \ |
| 2963 | if (forwarding_enabled_) { \ |
| 2964 | for (size_t i = 0; i < listeners_.size(); i++) { \ |
| 2965 | listeners_[i]->Name(parameter); \ |
| 2966 | } \ |
| 2967 | } \ |
| 2968 | } |
| 2969 | // This defines a member that forwards the call to all listeners in reverse |
| 2970 | // order. |
| 2971 | #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ |
| 2972 | void TestEventRepeater::Name(const Type& parameter) { \ |
| 2973 | if (forwarding_enabled_) { \ |
| 2974 | for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ |
| 2975 | listeners_[i]->Name(parameter); \ |
| 2976 | } \ |
| 2977 | } \ |
| 2978 | } |
| 2979 | |
| 2980 | GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) |
| 2981 | GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) |
| 2982 | GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) |
| 2983 | GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) |
| 2984 | GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) |
| 2985 | GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) |
| 2986 | GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) |
| 2987 | GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) |
| 2988 | GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) |
| 2989 | GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) |
| 2990 | GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) |
| 2991 | |
| 2992 | #undef GTEST_REPEATER_METHOD_ |
| 2993 | #undef GTEST_REVERSE_REPEATER_METHOD_ |
| 2994 | |
| 2995 | void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, |
| 2996 | int iteration) { |
| 2997 | if (forwarding_enabled_) { |
| 2998 | for (size_t i = 0; i < listeners_.size(); i++) { |
| 2999 | listeners_[i]->OnTestIterationStart(unit_test, iteration); |
| 3000 | } |
| 3001 | } |
| 3002 | } |
| 3003 | |
| 3004 | void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, |
| 3005 | int iteration) { |
| 3006 | if (forwarding_enabled_) { |
| 3007 | for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { |
| 3008 | listeners_[i]->OnTestIterationEnd(unit_test, iteration); |
| 3009 | } |
| 3010 | } |
| 3011 | } |
| 3012 | |
| 3013 | // End TestEventRepeater |
| 3014 | |
| 3015 | // This class generates an XML output file. |
| 3016 | class XmlUnitTestResultPrinter : public EmptyTestEventListener { |
| 3017 | public: |
| 3018 | explicit XmlUnitTestResultPrinter(const char* output_file); |
| 3019 | |
| 3020 | virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); |
| 3021 | |
| 3022 | private: |
| 3023 | // Is c a whitespace character that is normalized to a space character |
| 3024 | // when it appears in an XML attribute value? |
| 3025 | static bool IsNormalizableWhitespace(char c) { |
| 3026 | return c == 0x9 || c == 0xA || c == 0xD; |
| 3027 | } |
| 3028 | |
| 3029 | // May c appear in a well-formed XML document? |
| 3030 | static bool IsValidXmlCharacter(char c) { |
| 3031 | return IsNormalizableWhitespace(c) || c >= 0x20; |
| 3032 | } |
| 3033 | |
| 3034 | // Returns an XML-escaped copy of the input string str. If |
| 3035 | // is_attribute is true, the text is meant to appear as an attribute |
| 3036 | // value, and normalizable whitespace is preserved by replacing it |
| 3037 | // with character references. |
| 3038 | static std::string EscapeXml(const std::string& str, bool is_attribute); |
| 3039 | |
| 3040 | // Returns the given string with all characters invalid in XML removed. |
| 3041 | static std::string RemoveInvalidXmlCharacters(const std::string& str); |
| 3042 | |
| 3043 | // Convenience wrapper around EscapeXml when str is an attribute value. |
| 3044 | static std::string EscapeXmlAttribute(const std::string& str) { |
| 3045 | return EscapeXml(str, true); |
| 3046 | } |
| 3047 | |
| 3048 | // Convenience wrapper around EscapeXml when str is not an attribute value. |
| 3049 | static std::string EscapeXmlText(const char* str) { |
| 3050 | return EscapeXml(str, false); |
| 3051 | } |
| 3052 | |
| 3053 | // Verifies that the given attribute belongs to the given element and |
| 3054 | // streams the attribute as XML. |
| 3055 | static void OutputXmlAttribute(std::ostream* stream, |
| 3056 | const std::string& element_name, |
| 3057 | const std::string& name, |
| 3058 | const std::string& value); |
| 3059 | |
| 3060 | // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. |
| 3061 | static void OutputXmlCDataSection(::std::ostream* stream, const char* data); |
| 3062 | |
| 3063 | // Streams an XML representation of a TestInfo object. |
| 3064 | static void OutputXmlTestInfo(::std::ostream* stream, |
| 3065 | const char* test_case_name, |
| 3066 | const TestInfo& test_info); |
| 3067 | |
| 3068 | // Prints an XML representation of a TestCase object |
| 3069 | static void PrintXmlTestCase(::std::ostream* stream, |
| 3070 | const TestCase& test_case); |
| 3071 | |
| 3072 | // Prints an XML summary of unit_test to output stream out. |
| 3073 | static void PrintXmlUnitTest(::std::ostream* stream, |
| 3074 | const UnitTest& unit_test); |
| 3075 | |
| 3076 | // Produces a string representing the test properties in a result as space |
| 3077 | // delimited XML attributes based on the property key="value" pairs. |
| 3078 | // When the std::string is not empty, it includes a space at the beginning, |
| 3079 | // to delimit this attribute from prior attributes. |
| 3080 | static std::string TestPropertiesAsXmlAttributes(const TestResult& result); |
| 3081 | |
| 3082 | // The output file. |
| 3083 | const std::string output_file_; |
| 3084 | |
| 3085 | GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); |
| 3086 | }; |
| 3087 | |
| 3088 | // Creates a new XmlUnitTestResultPrinter. |
| 3089 | XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) |
| 3090 | : output_file_(output_file) { |
| 3091 | if (output_file_.c_str() == NULL || output_file_.empty()) { |
| 3092 | fprintf(stderr, "XML output file may not be null\n"); |
| 3093 | fflush(stderr); |
| 3094 | exit(EXIT_FAILURE); |
| 3095 | } |
| 3096 | } |
| 3097 | |
| 3098 | // Called after the unit test ends. |
| 3099 | void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, |
| 3100 | int /*iteration*/) { |
| 3101 | FILE* xmlout = NULL; |
| 3102 | FilePath output_file(output_file_); |
| 3103 | FilePath output_dir(output_file.RemoveFileName()); |
| 3104 | |
| 3105 | if (output_dir.CreateDirectoriesRecursively()) { |
| 3106 | xmlout = posix::FOpen(output_file_.c_str(), "w"); |
| 3107 | } |
| 3108 | if (xmlout == NULL) { |
| 3109 | // TODO(wan): report the reason of the failure. |
| 3110 | // |
| 3111 | // We don't do it for now as: |
| 3112 | // |
| 3113 | // 1. There is no urgent need for it. |
| 3114 | // 2. It's a bit involved to make the errno variable thread-safe on |
| 3115 | // all three operating systems (Linux, Windows, and Mac OS). |
| 3116 | // 3. To interpret the meaning of errno in a thread-safe way, |
| 3117 | // we need the strerror_r() function, which is not available on |
| 3118 | // Windows. |
| 3119 | fprintf(stderr, |
| 3120 | "Unable to open file \"%s\"\n", |
| 3121 | output_file_.c_str()); |
| 3122 | fflush(stderr); |
| 3123 | exit(EXIT_FAILURE); |
| 3124 | } |
| 3125 | std::stringstream stream; |
| 3126 | PrintXmlUnitTest(&stream, unit_test); |
| 3127 | fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); |
| 3128 | fclose(xmlout); |
| 3129 | } |
| 3130 | |
| 3131 | // Returns an XML-escaped copy of the input string str. If is_attribute |
| 3132 | // is true, the text is meant to appear as an attribute value, and |
| 3133 | // normalizable whitespace is preserved by replacing it with character |
| 3134 | // references. |
| 3135 | // |
| 3136 | // Invalid XML characters in str, if any, are stripped from the output. |
| 3137 | // It is expected that most, if not all, of the text processed by this |
| 3138 | // module will consist of ordinary English text. |
| 3139 | // If this module is ever modified to produce version 1.1 XML output, |
| 3140 | // most invalid characters can be retained using character references. |
| 3141 | // TODO(wan): It might be nice to have a minimally invasive, human-readable |
| 3142 | // escaping scheme for invalid characters, rather than dropping them. |
| 3143 | std::string XmlUnitTestResultPrinter::EscapeXml( |
| 3144 | const std::string& str, bool is_attribute) { |
| 3145 | Message m; |
| 3146 | |
| 3147 | for (size_t i = 0; i < str.size(); ++i) { |
| 3148 | const char ch = str[i]; |
| 3149 | switch (ch) { |
| 3150 | case '<': |
| 3151 | m << "<"; |
| 3152 | break; |
| 3153 | case '>': |
| 3154 | m << ">"; |
| 3155 | break; |
| 3156 | case '&': |
| 3157 | m << "&"; |
| 3158 | break; |
| 3159 | case '\'': |
| 3160 | if (is_attribute) |
| 3161 | m << "'"; |
| 3162 | else |
| 3163 | m << '\''; |
| 3164 | break; |
| 3165 | case '"': |
| 3166 | if (is_attribute) |
| 3167 | m << """; |
| 3168 | else |
| 3169 | m << '"'; |
| 3170 | break; |
| 3171 | default: |
| 3172 | if (IsValidXmlCharacter(ch)) { |
| 3173 | if (is_attribute && IsNormalizableWhitespace(ch)) |
| 3174 | m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) |
| 3175 | << ";"; |
| 3176 | else |
| 3177 | m << ch; |
| 3178 | } |
| 3179 | break; |
| 3180 | } |
| 3181 | } |
| 3182 | |
| 3183 | return m.GetString(); |
| 3184 | } |
| 3185 | |
| 3186 | // Returns the given string with all characters invalid in XML removed. |
| 3187 | // Currently invalid characters are dropped from the string. An |
| 3188 | // alternative is to replace them with certain characters such as . or ?. |
| 3189 | std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( |
| 3190 | const std::string& str) { |
| 3191 | std::string output; |
| 3192 | output.reserve(str.size()); |
| 3193 | for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) |
| 3194 | if (IsValidXmlCharacter(*it)) |
| 3195 | output.push_back(*it); |
| 3196 | |
| 3197 | return output; |
| 3198 | } |
| 3199 | |
| 3200 | // The following routines generate an XML representation of a UnitTest |
| 3201 | // object. |
| 3202 | // |
| 3203 | // This is how Google Test concepts map to the DTD: |
| 3204 | // |
| 3205 | // <testsuites name="AllTests"> <-- corresponds to a UnitTest object |
| 3206 | // <testsuite name="testcase-name"> <-- corresponds to a TestCase object |
| 3207 | // <testcase name="test-name"> <-- corresponds to a TestInfo object |
| 3208 | // <failure message="...">...</failure> |
| 3209 | // <failure message="...">...</failure> |
| 3210 | // <failure message="...">...</failure> |
| 3211 | // <-- individual assertion failures |
| 3212 | // </testcase> |
| 3213 | // </testsuite> |
| 3214 | // </testsuites> |
| 3215 | |
| 3216 | // Formats the given time in milliseconds as seconds. |
| 3217 | std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { |
| 3218 | ::std::stringstream ss; |
| 3219 | ss << ms/1000.0; |
| 3220 | return ss.str(); |
| 3221 | } |
| 3222 | |
| 3223 | // Converts the given epoch time in milliseconds to a date string in the ISO |
| 3224 | // 8601 format, without the timezone information. |
| 3225 | std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { |
| 3226 | time_t seconds = static_cast<time_t>(ms / 1000); |
| 3227 | struct tm time_struct; |
| 3228 | #ifdef _MSC_VER |
| 3229 | if (localtime_s(&time_struct, &seconds) != 0) |
| 3230 | return ""; // Invalid ms value |
| 3231 | #else |
| 3232 | if (localtime_r(&seconds, &time_struct) == NULL) |
| 3233 | return ""; // Invalid ms value |
| 3234 | #endif |
| 3235 | |
| 3236 | // YYYY-MM-DDThh:mm:ss |
| 3237 | return StreamableToString(time_struct.tm_year + 1900) + "-" + |
| 3238 | String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + |
| 3239 | String::FormatIntWidth2(time_struct.tm_mday) + "T" + |
| 3240 | String::FormatIntWidth2(time_struct.tm_hour) + ":" + |
| 3241 | String::FormatIntWidth2(time_struct.tm_min) + ":" + |
| 3242 | String::FormatIntWidth2(time_struct.tm_sec); |
| 3243 | } |
| 3244 | |
| 3245 | // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. |
| 3246 | void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, |
| 3247 | const char* data) { |
| 3248 | const char* segment = data; |
| 3249 | *stream << "<![CDATA["; |
| 3250 | for (;;) { |
| 3251 | const char* const next_segment = strstr(segment, "]]>"); |
| 3252 | if (next_segment != NULL) { |
| 3253 | stream->write( |
| 3254 | segment, static_cast<std::streamsize>(next_segment - segment)); |
| 3255 | *stream << "]]>]]><![CDATA["; |
| 3256 | segment = next_segment + strlen("]]>"); |
| 3257 | } else { |
| 3258 | *stream << segment; |
| 3259 | break; |
| 3260 | } |
| 3261 | } |
| 3262 | *stream << "]]>"; |
| 3263 | } |
| 3264 | |
| 3265 | void XmlUnitTestResultPrinter::OutputXmlAttribute( |
| 3266 | std::ostream* stream, |
| 3267 | const std::string& element_name, |
| 3268 | const std::string& name, |
| 3269 | const std::string& value) { |
| 3270 | const std::vector<std::string>& allowed_names = |
| 3271 | GetReservedAttributesForElement(element_name); |
| 3272 | |
| 3273 | GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != |
| 3274 | allowed_names.end()) |
| 3275 | << "Attribute " << name << " is not allowed for element <" << element_name |
| 3276 | << ">."; |
| 3277 | |
| 3278 | *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; |
| 3279 | } |
| 3280 | |
| 3281 | // Prints an XML representation of a TestInfo object. |
| 3282 | // TODO(wan): There is also value in printing properties with the plain printer. |
| 3283 | void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, |
| 3284 | const char* test_case_name, |
| 3285 | const TestInfo& test_info) { |
| 3286 | const TestResult& result = *test_info.result(); |
| 3287 | const std::string kTestcase = "testcase"; |
| 3288 | |
| 3289 | *stream << " <testcase"; |
| 3290 | OutputXmlAttribute(stream, kTestcase, "name", test_info.name()); |
| 3291 | |
| 3292 | if (test_info.value_param() != NULL) { |
| 3293 | OutputXmlAttribute(stream, kTestcase, "value_param", |
| 3294 | test_info.value_param()); |
| 3295 | } |
| 3296 | if (test_info.type_param() != NULL) { |
| 3297 | OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param()); |
| 3298 | } |
| 3299 | |
| 3300 | OutputXmlAttribute(stream, kTestcase, "status", |
| 3301 | test_info.should_run() ? "run" : "notrun"); |
| 3302 | OutputXmlAttribute(stream, kTestcase, "time", |
| 3303 | FormatTimeInMillisAsSeconds(result.elapsed_time())); |
| 3304 | OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); |
| 3305 | *stream << TestPropertiesAsXmlAttributes(result); |
| 3306 | |
| 3307 | int failures = 0; |
| 3308 | for (int i = 0; i < result.total_part_count(); ++i) { |
| 3309 | const TestPartResult& part = result.GetTestPartResult(i); |
| 3310 | if (part.failed()) { |
| 3311 | if (++failures == 1) { |
| 3312 | *stream << ">\n"; |
| 3313 | } |
| 3314 | const string location = internal::FormatCompilerIndependentFileLocation( |
| 3315 | part.file_name(), part.line_number()); |
| 3316 | const string summary = location + "\n" + part.summary(); |
| 3317 | *stream << " <failure message=\"" |
| 3318 | << EscapeXmlAttribute(summary.c_str()) |
| 3319 | << "\" type=\"\">"; |
| 3320 | const string detail = location + "\n" + part.message(); |
| 3321 | OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); |
| 3322 | *stream << "</failure>\n"; |
| 3323 | } |
| 3324 | } |
| 3325 | |
| 3326 | if (failures == 0) |
| 3327 | *stream << " />\n"; |
| 3328 | else |
| 3329 | *stream << " </testcase>\n"; |
| 3330 | } |
| 3331 | |
| 3332 | // Prints an XML representation of a TestCase object |
| 3333 | void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, |
| 3334 | const TestCase& test_case) { |
| 3335 | const std::string kTestsuite = "testsuite"; |
| 3336 | *stream << " <" << kTestsuite; |
| 3337 | OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); |
| 3338 | OutputXmlAttribute(stream, kTestsuite, "tests", |
| 3339 | StreamableToString(test_case.reportable_test_count())); |
| 3340 | OutputXmlAttribute(stream, kTestsuite, "failures", |
| 3341 | StreamableToString(test_case.failed_test_count())); |
| 3342 | OutputXmlAttribute( |
| 3343 | stream, kTestsuite, "disabled", |
| 3344 | StreamableToString(test_case.reportable_disabled_test_count())); |
| 3345 | OutputXmlAttribute(stream, kTestsuite, "errors", "0"); |
| 3346 | OutputXmlAttribute(stream, kTestsuite, "time", |
| 3347 | FormatTimeInMillisAsSeconds(test_case.elapsed_time())); |
| 3348 | *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) |
| 3349 | << ">\n"; |
| 3350 | |
| 3351 | for (int i = 0; i < test_case.total_test_count(); ++i) { |
| 3352 | if (test_case.GetTestInfo(i)->is_reportable()) |
| 3353 | OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); |
| 3354 | } |
| 3355 | *stream << " </" << kTestsuite << ">\n"; |
| 3356 | } |
| 3357 | |
| 3358 | // Prints an XML summary of unit_test to output stream out. |
| 3359 | void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, |
| 3360 | const UnitTest& unit_test) { |
| 3361 | const std::string kTestsuites = "testsuites"; |
| 3362 | |
| 3363 | *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; |
| 3364 | *stream << "<" << kTestsuites; |
| 3365 | |
| 3366 | OutputXmlAttribute(stream, kTestsuites, "tests", |
| 3367 | StreamableToString(unit_test.reportable_test_count())); |
| 3368 | OutputXmlAttribute(stream, kTestsuites, "failures", |
| 3369 | StreamableToString(unit_test.failed_test_count())); |
| 3370 | OutputXmlAttribute( |
| 3371 | stream, kTestsuites, "disabled", |
| 3372 | StreamableToString(unit_test.reportable_disabled_test_count())); |
| 3373 | OutputXmlAttribute(stream, kTestsuites, "errors", "0"); |
| 3374 | OutputXmlAttribute( |
| 3375 | stream, kTestsuites, "timestamp", |
| 3376 | FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); |
| 3377 | OutputXmlAttribute(stream, kTestsuites, "time", |
| 3378 | FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); |
| 3379 | |
| 3380 | if (GTEST_FLAG(shuffle)) { |
| 3381 | OutputXmlAttribute(stream, kTestsuites, "random_seed", |
| 3382 | StreamableToString(unit_test.random_seed())); |
| 3383 | } |
| 3384 | |
| 3385 | *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); |
| 3386 | |
| 3387 | OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); |
| 3388 | *stream << ">\n"; |
| 3389 | |
| 3390 | for (int i = 0; i < unit_test.total_test_case_count(); ++i) { |
| 3391 | if (unit_test.GetTestCase(i)->reportable_test_count() > 0) |
| 3392 | PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); |
| 3393 | } |
| 3394 | *stream << "</" << kTestsuites << ">\n"; |
| 3395 | } |
| 3396 | |
| 3397 | // Produces a string representing the test properties in a result as space |
| 3398 | // delimited XML attributes based on the property key="value" pairs. |
| 3399 | std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( |
| 3400 | const TestResult& result) { |
| 3401 | Message attributes; |
| 3402 | for (int i = 0; i < result.test_property_count(); ++i) { |
| 3403 | const TestProperty& property = result.GetTestProperty(i); |
| 3404 | attributes << " " << property.key() << "=" |
| 3405 | << "\"" << EscapeXmlAttribute(property.value()) << "\""; |
| 3406 | } |
| 3407 | return attributes.GetString(); |
| 3408 | } |
| 3409 | |
| 3410 | // End XmlUnitTestResultPrinter |
| 3411 | |
| 3412 | #if GTEST_CAN_STREAM_RESULTS_ |
| 3413 | |
| 3414 | // Checks if str contains '=', '&', '%' or '\n' characters. If yes, |
| 3415 | // replaces them by "%xx" where xx is their hexadecimal value. For |
| 3416 | // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) |
| 3417 | // in both time and space -- important as the input str may contain an |
| 3418 | // arbitrarily long test failure message and stack trace. |
| 3419 | string StreamingListener::UrlEncode(const char* str) { |
| 3420 | string result; |
| 3421 | result.reserve(strlen(str) + 1); |
| 3422 | for (char ch = *str; ch != '\0'; ch = *++str) { |
| 3423 | switch (ch) { |
| 3424 | case '%': |
| 3425 | case '=': |
| 3426 | case '&': |
| 3427 | case '\n': |
| 3428 | result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); |
| 3429 | break; |
| 3430 | default: |
| 3431 | result.push_back(ch); |
| 3432 | break; |
| 3433 | } |
| 3434 | } |
| 3435 | return result; |
| 3436 | } |
| 3437 | |
| 3438 | void StreamingListener::SocketWriter::MakeConnection() { |
| 3439 | GTEST_CHECK_(sockfd_ == -1) |
| 3440 | << "MakeConnection() can't be called when there is already a connection."; |
| 3441 | |
| 3442 | addrinfo hints; |
| 3443 | memset(&hints, 0, sizeof(hints)); |
| 3444 | hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. |
| 3445 | hints.ai_socktype = SOCK_STREAM; |
| 3446 | addrinfo* servinfo = NULL; |
| 3447 | |
| 3448 | // Use the getaddrinfo() to get a linked list of IP addresses for |
| 3449 | // the given host name. |
| 3450 | const int error_num = getaddrinfo( |
| 3451 | host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); |
| 3452 | if (error_num != 0) { |
| 3453 | GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " |
| 3454 | << gai_strerror(error_num); |
| 3455 | } |
| 3456 | |
| 3457 | // Loop through all the results and connect to the first we can. |
| 3458 | for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; |
| 3459 | cur_addr = cur_addr->ai_next) { |
| 3460 | sockfd_ = socket( |
| 3461 | cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); |
| 3462 | if (sockfd_ != -1) { |
| 3463 | // Connect the client socket to the server socket. |
| 3464 | if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { |
| 3465 | close(sockfd_); |
| 3466 | sockfd_ = -1; |
| 3467 | } |
| 3468 | } |
| 3469 | } |
| 3470 | |
| 3471 | freeaddrinfo(servinfo); // all done with this structure |
| 3472 | |
| 3473 | if (sockfd_ == -1) { |
| 3474 | GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " |
| 3475 | << host_name_ << ":" << port_num_; |
| 3476 | } |
| 3477 | } |
| 3478 | |
| 3479 | // End of class Streaming Listener |
| 3480 | #endif // GTEST_CAN_STREAM_RESULTS__ |
| 3481 | |
| 3482 | // Class ScopedTrace |
| 3483 | |
| 3484 | // Pushes the given source file location and message onto a per-thread |
| 3485 | // trace stack maintained by Google Test. |
| 3486 | ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) |
| 3487 | GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { |
| 3488 | TraceInfo trace; |
| 3489 | trace.file = file; |
| 3490 | trace.line = line; |
| 3491 | trace.message = message.GetString(); |
| 3492 | |
| 3493 | UnitTest::GetInstance()->PushGTestTrace(trace); |
| 3494 | } |
| 3495 | |
| 3496 | // Pops the info pushed by the c'tor. |
| 3497 | ScopedTrace::~ScopedTrace() |
| 3498 | GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { |
| 3499 | UnitTest::GetInstance()->PopGTestTrace(); |
| 3500 | } |
| 3501 | |
| 3502 | |
| 3503 | // class OsStackTraceGetter |
| 3504 | |
| 3505 | // Returns the current OS stack trace as an std::string. Parameters: |
| 3506 | // |
| 3507 | // max_depth - the maximum number of stack frames to be included |
| 3508 | // in the trace. |
| 3509 | // skip_count - the number of top frames to be skipped; doesn't count |
| 3510 | // against max_depth. |
| 3511 | // |
| 3512 | string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */, |
| 3513 | int /* skip_count */) |
| 3514 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3515 | return ""; |
| 3516 | } |
| 3517 | |
| 3518 | void OsStackTraceGetter::UponLeavingGTest() |
| 3519 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3520 | } |
| 3521 | |
| 3522 | const char* const |
| 3523 | OsStackTraceGetter::kElidedFramesMarker = |
| 3524 | "... " GTEST_NAME_ " internal frames ..."; |
| 3525 | |
| 3526 | // A helper class that creates the premature-exit file in its |
| 3527 | // constructor and deletes the file in its destructor. |
| 3528 | class ScopedPrematureExitFile { |
| 3529 | public: |
| 3530 | explicit ScopedPrematureExitFile(const char* premature_exit_filepath) |
| 3531 | : premature_exit_filepath_(premature_exit_filepath) { |
| 3532 | // If a path to the premature-exit file is specified... |
| 3533 | if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { |
| 3534 | // create the file with a single "0" character in it. I/O |
| 3535 | // errors are ignored as there's nothing better we can do and we |
| 3536 | // don't want to fail the test because of this. |
| 3537 | FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); |
| 3538 | fwrite("0", 1, 1, pfile); |
| 3539 | fclose(pfile); |
| 3540 | } |
| 3541 | } |
| 3542 | |
| 3543 | ~ScopedPrematureExitFile() { |
| 3544 | if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { |
| 3545 | remove(premature_exit_filepath_); |
| 3546 | } |
| 3547 | } |
| 3548 | |
| 3549 | private: |
| 3550 | const char* const premature_exit_filepath_; |
| 3551 | |
| 3552 | GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); |
| 3553 | }; |
| 3554 | |
| 3555 | } // namespace internal |
| 3556 | |
| 3557 | // class TestEventListeners |
| 3558 | |
| 3559 | TestEventListeners::TestEventListeners() |
| 3560 | : repeater_(new internal::TestEventRepeater()), |
| 3561 | default_result_printer_(NULL), |
| 3562 | default_xml_generator_(NULL) { |
| 3563 | } |
| 3564 | |
| 3565 | TestEventListeners::~TestEventListeners() { delete repeater_; } |
| 3566 | |
| 3567 | // Returns the standard listener responsible for the default console |
| 3568 | // output. Can be removed from the listeners list to shut down default |
| 3569 | // console output. Note that removing this object from the listener list |
| 3570 | // with Release transfers its ownership to the user. |
| 3571 | void TestEventListeners::Append(TestEventListener* listener) { |
| 3572 | repeater_->Append(listener); |
| 3573 | } |
| 3574 | |
| 3575 | // Removes the given event listener from the list and returns it. It then |
| 3576 | // becomes the caller's responsibility to delete the listener. Returns |
| 3577 | // NULL if the listener is not found in the list. |
| 3578 | TestEventListener* TestEventListeners::Release(TestEventListener* listener) { |
| 3579 | if (listener == default_result_printer_) |
| 3580 | default_result_printer_ = NULL; |
| 3581 | else if (listener == default_xml_generator_) |
| 3582 | default_xml_generator_ = NULL; |
| 3583 | return repeater_->Release(listener); |
| 3584 | } |
| 3585 | |
| 3586 | // Returns repeater that broadcasts the TestEventListener events to all |
| 3587 | // subscribers. |
| 3588 | TestEventListener* TestEventListeners::repeater() { return repeater_; } |
| 3589 | |
| 3590 | // Sets the default_result_printer attribute to the provided listener. |
| 3591 | // The listener is also added to the listener list and previous |
| 3592 | // default_result_printer is removed from it and deleted. The listener can |
| 3593 | // also be NULL in which case it will not be added to the list. Does |
| 3594 | // nothing if the previous and the current listener objects are the same. |
| 3595 | void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { |
| 3596 | if (default_result_printer_ != listener) { |
| 3597 | // It is an error to pass this method a listener that is already in the |
| 3598 | // list. |
| 3599 | delete Release(default_result_printer_); |
| 3600 | default_result_printer_ = listener; |
| 3601 | if (listener != NULL) |
| 3602 | Append(listener); |
| 3603 | } |
| 3604 | } |
| 3605 | |
| 3606 | // Sets the default_xml_generator attribute to the provided listener. The |
| 3607 | // listener is also added to the listener list and previous |
| 3608 | // default_xml_generator is removed from it and deleted. The listener can |
| 3609 | // also be NULL in which case it will not be added to the list. Does |
| 3610 | // nothing if the previous and the current listener objects are the same. |
| 3611 | void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { |
| 3612 | if (default_xml_generator_ != listener) { |
| 3613 | // It is an error to pass this method a listener that is already in the |
| 3614 | // list. |
| 3615 | delete Release(default_xml_generator_); |
| 3616 | default_xml_generator_ = listener; |
| 3617 | if (listener != NULL) |
| 3618 | Append(listener); |
| 3619 | } |
| 3620 | } |
| 3621 | |
| 3622 | // Controls whether events will be forwarded by the repeater to the |
| 3623 | // listeners in the list. |
| 3624 | bool TestEventListeners::EventForwardingEnabled() const { |
| 3625 | return repeater_->forwarding_enabled(); |
| 3626 | } |
| 3627 | |
| 3628 | void TestEventListeners::SuppressEventForwarding() { |
| 3629 | repeater_->set_forwarding_enabled(false); |
| 3630 | } |
| 3631 | |
| 3632 | // class UnitTest |
| 3633 | |
| 3634 | // Gets the singleton UnitTest object. The first time this method is |
| 3635 | // called, a UnitTest object is constructed and returned. Consecutive |
| 3636 | // calls will return the same object. |
| 3637 | // |
| 3638 | // We don't protect this under mutex_ as a user is not supposed to |
| 3639 | // call this before main() starts, from which point on the return |
| 3640 | // value will never change. |
| 3641 | UnitTest* UnitTest::GetInstance() { |
| 3642 | // When compiled with MSVC 7.1 in optimized mode, destroying the |
| 3643 | // UnitTest object upon exiting the program messes up the exit code, |
| 3644 | // causing successful tests to appear failed. We have to use a |
| 3645 | // different implementation in this case to bypass the compiler bug. |
| 3646 | // This implementation makes the compiler happy, at the cost of |
| 3647 | // leaking the UnitTest object. |
| 3648 | |
| 3649 | // CodeGear C++Builder insists on a public destructor for the |
| 3650 | // default implementation. Use this implementation to keep good OO |
| 3651 | // design with private destructor. |
| 3652 | |
| 3653 | #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) |
| 3654 | static UnitTest* const instance = new UnitTest; |
| 3655 | return instance; |
| 3656 | #else |
| 3657 | static UnitTest instance; |
| 3658 | return &instance; |
| 3659 | #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) |
| 3660 | } |
| 3661 | |
| 3662 | // Gets the number of successful test cases. |
| 3663 | int UnitTest::successful_test_case_count() const { |
| 3664 | return impl()->successful_test_case_count(); |
| 3665 | } |
| 3666 | |
| 3667 | // Gets the number of failed test cases. |
| 3668 | int UnitTest::failed_test_case_count() const { |
| 3669 | return impl()->failed_test_case_count(); |
| 3670 | } |
| 3671 | |
| 3672 | // Gets the number of all test cases. |
| 3673 | int UnitTest::total_test_case_count() const { |
| 3674 | return impl()->total_test_case_count(); |
| 3675 | } |
| 3676 | |
| 3677 | // Gets the number of all test cases that contain at least one test |
| 3678 | // that should run. |
| 3679 | int UnitTest::test_case_to_run_count() const { |
| 3680 | return impl()->test_case_to_run_count(); |
| 3681 | } |
| 3682 | |
| 3683 | // Gets the number of successful tests. |
| 3684 | int UnitTest::successful_test_count() const { |
| 3685 | return impl()->successful_test_count(); |
| 3686 | } |
| 3687 | |
| 3688 | // Gets the number of failed tests. |
| 3689 | int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } |
| 3690 | |
| 3691 | // Gets the number of disabled tests that will be reported in the XML report. |
| 3692 | int UnitTest::reportable_disabled_test_count() const { |
| 3693 | return impl()->reportable_disabled_test_count(); |
| 3694 | } |
| 3695 | |
| 3696 | // Gets the number of disabled tests. |
| 3697 | int UnitTest::disabled_test_count() const { |
| 3698 | return impl()->disabled_test_count(); |
| 3699 | } |
| 3700 | |
| 3701 | // Gets the number of tests to be printed in the XML report. |
| 3702 | int UnitTest::reportable_test_count() const { |
| 3703 | return impl()->reportable_test_count(); |
| 3704 | } |
| 3705 | |
| 3706 | // Gets the number of all tests. |
| 3707 | int UnitTest::total_test_count() const { return impl()->total_test_count(); } |
| 3708 | |
| 3709 | // Gets the number of tests that should run. |
| 3710 | int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } |
| 3711 | |
| 3712 | // Gets the time of the test program start, in ms from the start of the |
| 3713 | // UNIX epoch. |
| 3714 | internal::TimeInMillis UnitTest::start_timestamp() const { |
| 3715 | return impl()->start_timestamp(); |
| 3716 | } |
| 3717 | |
| 3718 | // Gets the elapsed time, in milliseconds. |
| 3719 | internal::TimeInMillis UnitTest::elapsed_time() const { |
| 3720 | return impl()->elapsed_time(); |
| 3721 | } |
| 3722 | |
| 3723 | // Returns true iff the unit test passed (i.e. all test cases passed). |
| 3724 | bool UnitTest::Passed() const { return impl()->Passed(); } |
| 3725 | |
| 3726 | // Returns true iff the unit test failed (i.e. some test case failed |
| 3727 | // or something outside of all tests failed). |
| 3728 | bool UnitTest::Failed() const { return impl()->Failed(); } |
| 3729 | |
| 3730 | // Gets the i-th test case among all the test cases. i can range from 0 to |
| 3731 | // total_test_case_count() - 1. If i is not in that range, returns NULL. |
| 3732 | const TestCase* UnitTest::GetTestCase(int i) const { |
| 3733 | return impl()->GetTestCase(i); |
| 3734 | } |
| 3735 | |
| 3736 | // Returns the TestResult containing information on test failures and |
| 3737 | // properties logged outside of individual test cases. |
| 3738 | const TestResult& UnitTest::ad_hoc_test_result() const { |
| 3739 | return *impl()->ad_hoc_test_result(); |
| 3740 | } |
| 3741 | |
| 3742 | // Gets the i-th test case among all the test cases. i can range from 0 to |
| 3743 | // total_test_case_count() - 1. If i is not in that range, returns NULL. |
| 3744 | TestCase* UnitTest::GetMutableTestCase(int i) { |
| 3745 | return impl()->GetMutableTestCase(i); |
| 3746 | } |
| 3747 | |
| 3748 | // Returns the list of event listeners that can be used to track events |
| 3749 | // inside Google Test. |
| 3750 | TestEventListeners& UnitTest::listeners() { |
| 3751 | return *impl()->listeners(); |
| 3752 | } |
| 3753 | |
| 3754 | // Registers and returns a global test environment. When a test |
| 3755 | // program is run, all global test environments will be set-up in the |
| 3756 | // order they were registered. After all tests in the program have |
| 3757 | // finished, all global test environments will be torn-down in the |
| 3758 | // *reverse* order they were registered. |
| 3759 | // |
| 3760 | // The UnitTest object takes ownership of the given environment. |
| 3761 | // |
| 3762 | // We don't protect this under mutex_, as we only support calling it |
| 3763 | // from the main thread. |
| 3764 | Environment* UnitTest::AddEnvironment(Environment* env) { |
| 3765 | if (env == NULL) { |
| 3766 | return NULL; |
| 3767 | } |
| 3768 | |
| 3769 | impl_->environments().push_back(env); |
| 3770 | return env; |
| 3771 | } |
| 3772 | |
| 3773 | // Adds a TestPartResult to the current TestResult object. All Google Test |
| 3774 | // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call |
| 3775 | // this to report their results. The user code should use the |
| 3776 | // assertion macros instead of calling this directly. |
| 3777 | void UnitTest::AddTestPartResult( |
| 3778 | TestPartResult::Type result_type, |
| 3779 | const char* file_name, |
| 3780 | int line_number, |
| 3781 | const std::string& message, |
| 3782 | const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3783 | Message msg; |
| 3784 | msg << message; |
| 3785 | |
| 3786 | internal::MutexLock lock(&mutex_); |
| 3787 | if (impl_->gtest_trace_stack().size() > 0) { |
| 3788 | msg << "\n" << GTEST_NAME_ << " trace:"; |
| 3789 | |
| 3790 | for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); |
| 3791 | i > 0; --i) { |
| 3792 | const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; |
| 3793 | msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) |
| 3794 | << " " << trace.message; |
| 3795 | } |
| 3796 | } |
| 3797 | |
| 3798 | if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { |
| 3799 | msg << internal::kStackTraceMarker << os_stack_trace; |
| 3800 | } |
| 3801 | |
| 3802 | const TestPartResult result = |
| 3803 | TestPartResult(result_type, file_name, line_number, |
| 3804 | msg.GetString().c_str()); |
| 3805 | impl_->GetTestPartResultReporterForCurrentThread()-> |
| 3806 | ReportTestPartResult(result); |
| 3807 | |
| 3808 | if (result_type != TestPartResult::kSuccess) { |
| 3809 | // gtest_break_on_failure takes precedence over |
| 3810 | // gtest_throw_on_failure. This allows a user to set the latter |
| 3811 | // in the code (perhaps in order to use Google Test assertions |
| 3812 | // with another testing framework) and specify the former on the |
| 3813 | // command line for debugging. |
| 3814 | if (GTEST_FLAG(break_on_failure)) { |
| 3815 | #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT |
| 3816 | // Using DebugBreak on Windows allows gtest to still break into a debugger |
| 3817 | // when a failure happens and both the --gtest_break_on_failure and |
| 3818 | // the --gtest_catch_exceptions flags are specified. |
| 3819 | DebugBreak(); |
| 3820 | #else |
| 3821 | // Dereference NULL through a volatile pointer to prevent the compiler |
| 3822 | // from removing. We use this rather than abort() or __builtin_trap() for |
| 3823 | // portability: Symbian doesn't implement abort() well, and some debuggers |
| 3824 | // don't correctly trap abort(). |
| 3825 | *static_cast<volatile int*>(NULL) = 1; |
| 3826 | #endif // GTEST_OS_WINDOWS |
| 3827 | } else if (GTEST_FLAG(throw_on_failure)) { |
| 3828 | #if GTEST_HAS_EXCEPTIONS |
| 3829 | throw internal::GoogleTestFailureException(result); |
| 3830 | #else |
| 3831 | // We cannot call abort() as it generates a pop-up in debug mode |
| 3832 | // that cannot be suppressed in VC 7.1 or below. |
| 3833 | exit(1); |
| 3834 | #endif |
| 3835 | } |
| 3836 | } |
| 3837 | } |
| 3838 | |
| 3839 | // Adds a TestProperty to the current TestResult object when invoked from |
| 3840 | // inside a test, to current TestCase's ad_hoc_test_result_ when invoked |
| 3841 | // from SetUpTestCase or TearDownTestCase, or to the global property set |
| 3842 | // when invoked elsewhere. If the result already contains a property with |
| 3843 | // the same key, the value will be updated. |
| 3844 | void UnitTest::RecordProperty(const std::string& key, |
| 3845 | const std::string& value) { |
| 3846 | impl_->RecordProperty(TestProperty(key, value)); |
| 3847 | } |
| 3848 | |
| 3849 | // Runs all tests in this UnitTest object and prints the result. |
| 3850 | // Returns 0 if successful, or 1 otherwise. |
| 3851 | // |
| 3852 | // We don't protect this under mutex_, as we only support calling it |
| 3853 | // from the main thread. |
| 3854 | int UnitTest::Run() { |
| 3855 | const bool in_death_test_child_process = |
| 3856 | internal::GTEST_FLAG(internal_run_death_test).length() > 0; |
| 3857 | |
| 3858 | // Google Test implements this protocol for catching that a test |
| 3859 | // program exits before returning control to Google Test: |
| 3860 | // |
| 3861 | // 1. Upon start, Google Test creates a file whose absolute path |
| 3862 | // is specified by the environment variable |
| 3863 | // TEST_PREMATURE_EXIT_FILE. |
| 3864 | // 2. When Google Test has finished its work, it deletes the file. |
| 3865 | // |
| 3866 | // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before |
| 3867 | // running a Google-Test-based test program and check the existence |
| 3868 | // of the file at the end of the test execution to see if it has |
| 3869 | // exited prematurely. |
| 3870 | |
| 3871 | // If we are in the child process of a death test, don't |
| 3872 | // create/delete the premature exit file, as doing so is unnecessary |
| 3873 | // and will confuse the parent process. Otherwise, create/delete |
| 3874 | // the file upon entering/leaving this function. If the program |
| 3875 | // somehow exits before this function has a chance to return, the |
| 3876 | // premature-exit file will be left undeleted, causing a test runner |
| 3877 | // that understands the premature-exit-file protocol to report the |
| 3878 | // test as having failed. |
| 3879 | const internal::ScopedPrematureExitFile premature_exit_file( |
| 3880 | in_death_test_child_process ? |
| 3881 | NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); |
| 3882 | |
| 3883 | // Captures the value of GTEST_FLAG(catch_exceptions). This value will be |
| 3884 | // used for the duration of the program. |
| 3885 | impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); |
| 3886 | |
| 3887 | #if GTEST_HAS_SEH |
| 3888 | // Either the user wants Google Test to catch exceptions thrown by the |
| 3889 | // tests or this is executing in the context of death test child |
| 3890 | // process. In either case the user does not want to see pop-up dialogs |
| 3891 | // about crashes - they are expected. |
| 3892 | if (impl()->catch_exceptions() || in_death_test_child_process) { |
| 3893 | # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT |
| 3894 | // SetErrorMode doesn't exist on CE. |
| 3895 | SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | |
| 3896 | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); |
| 3897 | # endif // !GTEST_OS_WINDOWS_MOBILE |
| 3898 | |
| 3899 | # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE |
| 3900 | // Death test children can be terminated with _abort(). On Windows, |
| 3901 | // _abort() can show a dialog with a warning message. This forces the |
| 3902 | // abort message to go to stderr instead. |
| 3903 | _set_error_mode(_OUT_TO_STDERR); |
| 3904 | # endif |
| 3905 | |
| 3906 | # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE |
| 3907 | // In the debug version, Visual Studio pops up a separate dialog |
| 3908 | // offering a choice to debug the aborted program. We need to suppress |
| 3909 | // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement |
| 3910 | // executed. Google Test will notify the user of any unexpected |
| 3911 | // failure via stderr. |
| 3912 | // |
| 3913 | // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. |
| 3914 | // Users of prior VC versions shall suffer the agony and pain of |
| 3915 | // clicking through the countless debug dialogs. |
| 3916 | // TODO(vladl@google.com): find a way to suppress the abort dialog() in the |
| 3917 | // debug mode when compiled with VC 7.1 or lower. |
| 3918 | if (!GTEST_FLAG(break_on_failure)) |
| 3919 | _set_abort_behavior( |
| 3920 | 0x0, // Clear the following flags: |
| 3921 | _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. |
| 3922 | # endif |
| 3923 | } |
| 3924 | #endif // GTEST_HAS_SEH |
| 3925 | |
| 3926 | return internal::HandleExceptionsInMethodIfSupported( |
| 3927 | impl(), |
| 3928 | &internal::UnitTestImpl::RunAllTests, |
| 3929 | "auxiliary test code (environments or event listeners)") ? 0 : 1; |
| 3930 | } |
| 3931 | |
| 3932 | // Returns the working directory when the first TEST() or TEST_F() was |
| 3933 | // executed. |
| 3934 | const char* UnitTest::original_working_dir() const { |
| 3935 | return impl_->original_working_dir_.c_str(); |
| 3936 | } |
| 3937 | |
| 3938 | // Returns the TestCase object for the test that's currently running, |
| 3939 | // or NULL if no test is running. |
| 3940 | const TestCase* UnitTest::current_test_case() const |
| 3941 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3942 | internal::MutexLock lock(&mutex_); |
| 3943 | return impl_->current_test_case(); |
| 3944 | } |
| 3945 | |
| 3946 | // Returns the TestInfo object for the test that's currently running, |
| 3947 | // or NULL if no test is running. |
| 3948 | const TestInfo* UnitTest::current_test_info() const |
| 3949 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3950 | internal::MutexLock lock(&mutex_); |
| 3951 | return impl_->current_test_info(); |
| 3952 | } |
| 3953 | |
| 3954 | // Returns the random seed used at the start of the current test run. |
| 3955 | int UnitTest::random_seed() const { return impl_->random_seed(); } |
| 3956 | |
| 3957 | #if GTEST_HAS_PARAM_TEST |
| 3958 | // Returns ParameterizedTestCaseRegistry object used to keep track of |
| 3959 | // value-parameterized tests and instantiate and register them. |
| 3960 | internal::ParameterizedTestCaseRegistry& |
| 3961 | UnitTest::parameterized_test_registry() |
| 3962 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3963 | return impl_->parameterized_test_registry(); |
| 3964 | } |
| 3965 | #endif // GTEST_HAS_PARAM_TEST |
| 3966 | |
| 3967 | // Creates an empty UnitTest. |
| 3968 | UnitTest::UnitTest() { |
| 3969 | impl_ = new internal::UnitTestImpl(this); |
| 3970 | } |
| 3971 | |
| 3972 | // Destructor of UnitTest. |
| 3973 | UnitTest::~UnitTest() { |
| 3974 | delete impl_; |
| 3975 | } |
| 3976 | |
| 3977 | // Pushes a trace defined by SCOPED_TRACE() on to the per-thread |
| 3978 | // Google Test trace stack. |
| 3979 | void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) |
| 3980 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3981 | internal::MutexLock lock(&mutex_); |
| 3982 | impl_->gtest_trace_stack().push_back(trace); |
| 3983 | } |
| 3984 | |
| 3985 | // Pops a trace from the per-thread Google Test trace stack. |
| 3986 | void UnitTest::PopGTestTrace() |
| 3987 | GTEST_LOCK_EXCLUDED_(mutex_) { |
| 3988 | internal::MutexLock lock(&mutex_); |
| 3989 | impl_->gtest_trace_stack().pop_back(); |
| 3990 | } |
| 3991 | |
| 3992 | namespace internal { |
| 3993 | |
| 3994 | UnitTestImpl::UnitTestImpl(UnitTest* parent) |
| 3995 | : parent_(parent), |
| 3996 | GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) |
| 3997 | default_global_test_part_result_reporter_(this), |
| 3998 | default_per_thread_test_part_result_reporter_(this), |
| 3999 | GTEST_DISABLE_MSC_WARNINGS_POP_() |
| 4000 | global_test_part_result_repoter_( |
| 4001 | &default_global_test_part_result_reporter_), |
| 4002 | per_thread_test_part_result_reporter_( |
| 4003 | &default_per_thread_test_part_result_reporter_), |
| 4004 | #if GTEST_HAS_PARAM_TEST |
| 4005 | parameterized_test_registry_(), |
| 4006 | parameterized_tests_registered_(false), |
| 4007 | #endif // GTEST_HAS_PARAM_TEST |
| 4008 | last_death_test_case_(-1), |
| 4009 | current_test_case_(NULL), |
| 4010 | current_test_info_(NULL), |
| 4011 | ad_hoc_test_result_(), |
| 4012 | os_stack_trace_getter_(NULL), |
| 4013 | post_flag_parse_init_performed_(false), |
| 4014 | random_seed_(0), // Will be overridden by the flag before first use. |
| 4015 | random_(0), // Will be reseeded before first use. |
| 4016 | start_timestamp_(0), |
| 4017 | elapsed_time_(0), |
| 4018 | #if GTEST_HAS_DEATH_TEST |
| 4019 | death_test_factory_(new DefaultDeathTestFactory), |
| 4020 | #endif |
| 4021 | // Will be overridden by the flag before first use. |
| 4022 | catch_exceptions_(false) { |
| 4023 | listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); |
| 4024 | } |
| 4025 | |
| 4026 | UnitTestImpl::~UnitTestImpl() { |
| 4027 | // Deletes every TestCase. |
| 4028 | ForEach(test_cases_, internal::Delete<TestCase>); |
| 4029 | |
| 4030 | // Deletes every Environment. |
| 4031 | ForEach(environments_, internal::Delete<Environment>); |
| 4032 | |
| 4033 | delete os_stack_trace_getter_; |
| 4034 | } |
| 4035 | |
| 4036 | // Adds a TestProperty to the current TestResult object when invoked in a |
| 4037 | // context of a test, to current test case's ad_hoc_test_result when invoke |
| 4038 | // from SetUpTestCase/TearDownTestCase, or to the global property set |
| 4039 | // otherwise. If the result already contains a property with the same key, |
| 4040 | // the value will be updated. |
| 4041 | void UnitTestImpl::RecordProperty(const TestProperty& test_property) { |
| 4042 | std::string xml_element; |
| 4043 | TestResult* test_result; // TestResult appropriate for property recording. |
| 4044 | |
| 4045 | if (current_test_info_ != NULL) { |
| 4046 | xml_element = "testcase"; |
| 4047 | test_result = &(current_test_info_->result_); |
| 4048 | } else if (current_test_case_ != NULL) { |
| 4049 | xml_element = "testsuite"; |
| 4050 | test_result = &(current_test_case_->ad_hoc_test_result_); |
| 4051 | } else { |
| 4052 | xml_element = "testsuites"; |
| 4053 | test_result = &ad_hoc_test_result_; |
| 4054 | } |
| 4055 | test_result->RecordProperty(xml_element, test_property); |
| 4056 | } |
| 4057 | |
| 4058 | #if GTEST_HAS_DEATH_TEST |
| 4059 | // Disables event forwarding if the control is currently in a death test |
| 4060 | // subprocess. Must not be called before InitGoogleTest. |
| 4061 | void UnitTestImpl::SuppressTestEventsIfInSubprocess() { |
| 4062 | if (internal_run_death_test_flag_.get() != NULL) |
| 4063 | listeners()->SuppressEventForwarding(); |
| 4064 | } |
| 4065 | #endif // GTEST_HAS_DEATH_TEST |
| 4066 | |
| 4067 | // Initializes event listeners performing XML output as specified by |
| 4068 | // UnitTestOptions. Must not be called before InitGoogleTest. |
| 4069 | void UnitTestImpl::ConfigureXmlOutput() { |
| 4070 | const std::string& output_format = UnitTestOptions::GetOutputFormat(); |
| 4071 | if (output_format == "xml") { |
| 4072 | listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( |
| 4073 | UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); |
| 4074 | } else if (output_format != "") { |
| 4075 | printf("WARNING: unrecognized output format \"%s\" ignored.\n", |
| 4076 | output_format.c_str()); |
| 4077 | fflush(stdout); |
| 4078 | } |
| 4079 | } |
| 4080 | |
| 4081 | #if GTEST_CAN_STREAM_RESULTS_ |
| 4082 | // Initializes event listeners for streaming test results in string form. |
| 4083 | // Must not be called before InitGoogleTest. |
| 4084 | void UnitTestImpl::ConfigureStreamingOutput() { |
| 4085 | const std::string& target = GTEST_FLAG(stream_result_to); |
| 4086 | if (!target.empty()) { |
| 4087 | const size_t pos = target.find(':'); |
| 4088 | if (pos != std::string::npos) { |
| 4089 | listeners()->Append(new StreamingListener(target.substr(0, pos), |
| 4090 | target.substr(pos+1))); |
| 4091 | } else { |
| 4092 | printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", |
| 4093 | target.c_str()); |
| 4094 | fflush(stdout); |
| 4095 | } |
| 4096 | } |
| 4097 | } |
| 4098 | #endif // GTEST_CAN_STREAM_RESULTS_ |
| 4099 | |
| 4100 | // Performs initialization dependent upon flag values obtained in |
| 4101 | // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to |
| 4102 | // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest |
| 4103 | // this function is also called from RunAllTests. Since this function can be |
| 4104 | // called more than once, it has to be idempotent. |
| 4105 | void UnitTestImpl::PostFlagParsingInit() { |
| 4106 | // Ensures that this function does not execute more than once. |
| 4107 | if (!post_flag_parse_init_performed_) { |
| 4108 | post_flag_parse_init_performed_ = true; |
| 4109 | |
| 4110 | #if GTEST_HAS_DEATH_TEST |
| 4111 | InitDeathTestSubprocessControlInfo(); |
| 4112 | SuppressTestEventsIfInSubprocess(); |
| 4113 | #endif // GTEST_HAS_DEATH_TEST |
| 4114 | |
| 4115 | // Registers parameterized tests. This makes parameterized tests |
| 4116 | // available to the UnitTest reflection API without running |
| 4117 | // RUN_ALL_TESTS. |
| 4118 | RegisterParameterizedTests(); |
| 4119 | |
| 4120 | // Configures listeners for XML output. This makes it possible for users |
| 4121 | // to shut down the default XML output before invoking RUN_ALL_TESTS. |
| 4122 | ConfigureXmlOutput(); |
| 4123 | |
| 4124 | #if GTEST_CAN_STREAM_RESULTS_ |
| 4125 | // Configures listeners for streaming test results to the specified server. |
| 4126 | ConfigureStreamingOutput(); |
| 4127 | #endif // GTEST_CAN_STREAM_RESULTS_ |
| 4128 | } |
| 4129 | } |
| 4130 | |
| 4131 | // A predicate that checks the name of a TestCase against a known |
| 4132 | // value. |
| 4133 | // |
| 4134 | // This is used for implementation of the UnitTest class only. We put |
| 4135 | // it in the anonymous namespace to prevent polluting the outer |
| 4136 | // namespace. |
| 4137 | // |
| 4138 | // TestCaseNameIs is copyable. |
| 4139 | class TestCaseNameIs { |
| 4140 | public: |
| 4141 | // Constructor. |
| 4142 | explicit TestCaseNameIs(const std::string& name) |
| 4143 | : name_(name) {} |
| 4144 | |
| 4145 | // Returns true iff the name of test_case matches name_. |
| 4146 | bool operator()(const TestCase* test_case) const { |
| 4147 | return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; |
| 4148 | } |
| 4149 | |
| 4150 | private: |
| 4151 | std::string name_; |
| 4152 | }; |
| 4153 | |
| 4154 | // Finds and returns a TestCase with the given name. If one doesn't |
| 4155 | // exist, creates one and returns it. It's the CALLER'S |
| 4156 | // RESPONSIBILITY to ensure that this function is only called WHEN THE |
| 4157 | // TESTS ARE NOT SHUFFLED. |
| 4158 | // |
| 4159 | // Arguments: |
| 4160 | // |
| 4161 | // test_case_name: name of the test case |
| 4162 | // type_param: the name of the test case's type parameter, or NULL if |
| 4163 | // this is not a typed or a type-parameterized test case. |
| 4164 | // set_up_tc: pointer to the function that sets up the test case |
| 4165 | // tear_down_tc: pointer to the function that tears down the test case |
| 4166 | TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, |
| 4167 | const char* type_param, |
| 4168 | Test::SetUpTestCaseFunc set_up_tc, |
| 4169 | Test::TearDownTestCaseFunc tear_down_tc) { |
| 4170 | // Can we find a TestCase with the given name? |
| 4171 | const std::vector<TestCase*>::const_iterator test_case = |
| 4172 | std::find_if(test_cases_.begin(), test_cases_.end(), |
| 4173 | TestCaseNameIs(test_case_name)); |
| 4174 | |
| 4175 | if (test_case != test_cases_.end()) |
| 4176 | return *test_case; |
| 4177 | |
| 4178 | // No. Let's create one. |
| 4179 | TestCase* const new_test_case = |
| 4180 | new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); |
| 4181 | |
| 4182 | // Is this a death test case? |
| 4183 | if (internal::UnitTestOptions::MatchesFilter(test_case_name, |
| 4184 | kDeathTestCaseFilter)) { |
| 4185 | // Yes. Inserts the test case after the last death test case |
| 4186 | // defined so far. This only works when the test cases haven't |
| 4187 | // been shuffled. Otherwise we may end up running a death test |
| 4188 | // after a non-death test. |
| 4189 | ++last_death_test_case_; |
| 4190 | test_cases_.insert(test_cases_.begin() + last_death_test_case_, |
| 4191 | new_test_case); |
| 4192 | } else { |
| 4193 | // No. Appends to the end of the list. |
| 4194 | test_cases_.push_back(new_test_case); |
| 4195 | } |
| 4196 | |
| 4197 | test_case_indices_.push_back(static_cast<int>(test_case_indices_.size())); |
| 4198 | return new_test_case; |
| 4199 | } |
| 4200 | |
| 4201 | // Helpers for setting up / tearing down the given environment. They |
| 4202 | // are for use in the ForEach() function. |
| 4203 | static void SetUpEnvironment(Environment* env) { env->SetUp(); } |
| 4204 | static void TearDownEnvironment(Environment* env) { env->TearDown(); } |
| 4205 | |
| 4206 | // Runs all tests in this UnitTest object, prints the result, and |
| 4207 | // returns true if all tests are successful. If any exception is |
| 4208 | // thrown during a test, the test is considered to be failed, but the |
| 4209 | // rest of the tests will still be run. |
| 4210 | // |
| 4211 | // When parameterized tests are enabled, it expands and registers |
| 4212 | // parameterized tests first in RegisterParameterizedTests(). |
| 4213 | // All other functions called from RunAllTests() may safely assume that |
| 4214 | // parameterized tests are ready to be counted and run. |
| 4215 | bool UnitTestImpl::RunAllTests() { |
| 4216 | // Makes sure InitGoogleTest() was called. |
| 4217 | if (!GTestIsInitialized()) { |
| 4218 | printf("%s", |
| 4219 | "\nThis test program did NOT call ::testing::InitGoogleTest " |
| 4220 | "before calling RUN_ALL_TESTS(). Please fix it.\n"); |
| 4221 | return false; |
| 4222 | } |
| 4223 | |
| 4224 | // Do not run any test if the --help flag was specified. |
| 4225 | if (g_help_flag) |
| 4226 | return true; |
| 4227 | |
| 4228 | // Repeats the call to the post-flag parsing initialization in case the |
| 4229 | // user didn't call InitGoogleTest. |
| 4230 | PostFlagParsingInit(); |
| 4231 | |
| 4232 | // Even if sharding is not on, test runners may want to use the |
| 4233 | // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding |
| 4234 | // protocol. |
| 4235 | internal::WriteToShardStatusFileIfNeeded(); |
| 4236 | |
| 4237 | // True iff we are in a subprocess for running a thread-safe-style |
| 4238 | // death test. |
| 4239 | bool in_subprocess_for_death_test = false; |
| 4240 | |
| 4241 | #if GTEST_HAS_DEATH_TEST |
| 4242 | in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); |
| 4243 | #endif // GTEST_HAS_DEATH_TEST |
| 4244 | |
| 4245 | const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, |
| 4246 | in_subprocess_for_death_test); |
| 4247 | |
| 4248 | // Compares the full test names with the filter to decide which |
| 4249 | // tests to run. |
| 4250 | const bool has_tests_to_run = FilterTests(should_shard |
| 4251 | ? HONOR_SHARDING_PROTOCOL |
| 4252 | : IGNORE_SHARDING_PROTOCOL) > 0; |
| 4253 | |
| 4254 | // Lists the tests and exits if the --gtest_list_tests flag was specified. |
| 4255 | if (GTEST_FLAG(list_tests)) { |
| 4256 | // This must be called *after* FilterTests() has been called. |
| 4257 | ListTestsMatchingFilter(); |
| 4258 | return true; |
| 4259 | } |
| 4260 | |
| 4261 | random_seed_ = GTEST_FLAG(shuffle) ? |
| 4262 | GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; |
| 4263 | |
| 4264 | // True iff at least one test has failed. |
| 4265 | bool failed = false; |
| 4266 | |
| 4267 | TestEventListener* repeater = listeners()->repeater(); |
| 4268 | |
| 4269 | start_timestamp_ = GetTimeInMillis(); |
| 4270 | repeater->OnTestProgramStart(*parent_); |
| 4271 | |
| 4272 | // How many times to repeat the tests? We don't want to repeat them |
| 4273 | // when we are inside the subprocess of a death test. |
| 4274 | const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); |
| 4275 | // Repeats forever if the repeat count is negative. |
| 4276 | const bool forever = repeat < 0; |
| 4277 | for (int i = 0; forever || i != repeat; i++) { |
| 4278 | // We want to preserve failures generated by ad-hoc test |
| 4279 | // assertions executed before RUN_ALL_TESTS(). |
| 4280 | ClearNonAdHocTestResult(); |
| 4281 | |
| 4282 | const TimeInMillis start = GetTimeInMillis(); |
| 4283 | |
| 4284 | // Shuffles test cases and tests if requested. |
| 4285 | if (has_tests_to_run && GTEST_FLAG(shuffle)) { |
| 4286 | random()->Reseed(random_seed_); |
| 4287 | // This should be done before calling OnTestIterationStart(), |
| 4288 | // such that a test event listener can see the actual test order |
| 4289 | // in the event. |
| 4290 | ShuffleTests(); |
| 4291 | } |
| 4292 | |
| 4293 | // Tells the unit test event listeners that the tests are about to start. |
| 4294 | repeater->OnTestIterationStart(*parent_, i); |
| 4295 | |
| 4296 | // Runs each test case if there is at least one test to run. |
| 4297 | if (has_tests_to_run) { |
| 4298 | // Sets up all environments beforehand. |
| 4299 | repeater->OnEnvironmentsSetUpStart(*parent_); |
| 4300 | ForEach(environments_, SetUpEnvironment); |
| 4301 | repeater->OnEnvironmentsSetUpEnd(*parent_); |
| 4302 | |
| 4303 | // Runs the tests only if there was no fatal failure during global |
| 4304 | // set-up. |
| 4305 | if (!Test::HasFatalFailure()) { |
| 4306 | for (int test_index = 0; test_index < total_test_case_count(); |
| 4307 | test_index++) { |
| 4308 | GetMutableTestCase(test_index)->Run(); |
| 4309 | } |
| 4310 | } |
| 4311 | |
| 4312 | // Tears down all environments in reverse order afterwards. |
| 4313 | repeater->OnEnvironmentsTearDownStart(*parent_); |
| 4314 | std::for_each(environments_.rbegin(), environments_.rend(), |
| 4315 | TearDownEnvironment); |
| 4316 | repeater->OnEnvironmentsTearDownEnd(*parent_); |
| 4317 | } |
| 4318 | |
| 4319 | elapsed_time_ = GetTimeInMillis() - start; |
| 4320 | |
| 4321 | // Tells the unit test event listener that the tests have just finished. |
| 4322 | repeater->OnTestIterationEnd(*parent_, i); |
| 4323 | |
| 4324 | // Gets the result and clears it. |
| 4325 | if (!Passed()) { |
| 4326 | failed = true; |
| 4327 | } |
| 4328 | |
| 4329 | // Restores the original test order after the iteration. This |
| 4330 | // allows the user to quickly repro a failure that happens in the |
| 4331 | // N-th iteration without repeating the first (N - 1) iterations. |
| 4332 | // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in |
| 4333 | // case the user somehow changes the value of the flag somewhere |
| 4334 | // (it's always safe to unshuffle the tests). |
| 4335 | UnshuffleTests(); |
| 4336 | |
| 4337 | if (GTEST_FLAG(shuffle)) { |
| 4338 | // Picks a new random seed for each iteration. |
| 4339 | random_seed_ = GetNextRandomSeed(random_seed_); |
| 4340 | } |
| 4341 | } |
| 4342 | |
| 4343 | repeater->OnTestProgramEnd(*parent_); |
| 4344 | |
| 4345 | return !failed; |
| 4346 | } |
| 4347 | |
| 4348 | // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file |
| 4349 | // if the variable is present. If a file already exists at this location, this |
| 4350 | // function will write over it. If the variable is present, but the file cannot |
| 4351 | // be created, prints an error and exits. |
| 4352 | void WriteToShardStatusFileIfNeeded() { |
| 4353 | const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); |
| 4354 | if (test_shard_file != NULL) { |
| 4355 | FILE* const file = posix::FOpen(test_shard_file, "w"); |
| 4356 | if (file == NULL) { |
| 4357 | ColoredPrintf(COLOR_RED, |
| 4358 | "Could not write to the test shard status file \"%s\" " |
| 4359 | "specified by the %s environment variable.\n", |
| 4360 | test_shard_file, kTestShardStatusFile); |
| 4361 | fflush(stdout); |
| 4362 | exit(EXIT_FAILURE); |
| 4363 | } |
| 4364 | fclose(file); |
| 4365 | } |
| 4366 | } |
| 4367 | |
| 4368 | // Checks whether sharding is enabled by examining the relevant |
| 4369 | // environment variable values. If the variables are present, |
| 4370 | // but inconsistent (i.e., shard_index >= total_shards), prints |
| 4371 | // an error and exits. If in_subprocess_for_death_test, sharding is |
| 4372 | // disabled because it must only be applied to the original test |
| 4373 | // process. Otherwise, we could filter out death tests we intended to execute. |
| 4374 | bool ShouldShard(const char* total_shards_env, |
| 4375 | const char* shard_index_env, |
| 4376 | bool in_subprocess_for_death_test) { |
| 4377 | if (in_subprocess_for_death_test) { |
| 4378 | return false; |
| 4379 | } |
| 4380 | |
| 4381 | const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); |
| 4382 | const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); |
| 4383 | |
| 4384 | if (total_shards == -1 && shard_index == -1) { |
| 4385 | return false; |
| 4386 | } else if (total_shards == -1 && shard_index != -1) { |
| 4387 | const Message msg = Message() |
| 4388 | << "Invalid environment variables: you have " |
| 4389 | << kTestShardIndex << " = " << shard_index |
| 4390 | << ", but have left " << kTestTotalShards << " unset.\n"; |
| 4391 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 4392 | fflush(stdout); |
| 4393 | exit(EXIT_FAILURE); |
| 4394 | } else if (total_shards != -1 && shard_index == -1) { |
| 4395 | const Message msg = Message() |
| 4396 | << "Invalid environment variables: you have " |
| 4397 | << kTestTotalShards << " = " << total_shards |
| 4398 | << ", but have left " << kTestShardIndex << " unset.\n"; |
| 4399 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 4400 | fflush(stdout); |
| 4401 | exit(EXIT_FAILURE); |
| 4402 | } else if (shard_index < 0 || shard_index >= total_shards) { |
| 4403 | const Message msg = Message() |
| 4404 | << "Invalid environment variables: we require 0 <= " |
| 4405 | << kTestShardIndex << " < " << kTestTotalShards |
| 4406 | << ", but you have " << kTestShardIndex << "=" << shard_index |
| 4407 | << ", " << kTestTotalShards << "=" << total_shards << ".\n"; |
| 4408 | ColoredPrintf(COLOR_RED, msg.GetString().c_str()); |
| 4409 | fflush(stdout); |
| 4410 | exit(EXIT_FAILURE); |
| 4411 | } |
| 4412 | |
| 4413 | return total_shards > 1; |
| 4414 | } |
| 4415 | |
| 4416 | // Parses the environment variable var as an Int32. If it is unset, |
| 4417 | // returns default_val. If it is not an Int32, prints an error |
| 4418 | // and aborts. |
| 4419 | Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { |
| 4420 | const char* str_val = posix::GetEnv(var); |
| 4421 | if (str_val == NULL) { |
| 4422 | return default_val; |
| 4423 | } |
| 4424 | |
| 4425 | Int32 result; |
| 4426 | if (!ParseInt32(Message() << "The value of environment variable " << var, |
| 4427 | str_val, &result)) { |
| 4428 | exit(EXIT_FAILURE); |
| 4429 | } |
| 4430 | return result; |
| 4431 | } |
| 4432 | |
| 4433 | // Given the total number of shards, the shard index, and the test id, |
| 4434 | // returns true iff the test should be run on this shard. The test id is |
| 4435 | // some arbitrary but unique non-negative integer assigned to each test |
| 4436 | // method. Assumes that 0 <= shard_index < total_shards. |
| 4437 | bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { |
| 4438 | return (test_id % total_shards) == shard_index; |
| 4439 | } |
| 4440 | |
| 4441 | // Compares the name of each test with the user-specified filter to |
| 4442 | // decide whether the test should be run, then records the result in |
| 4443 | // each TestCase and TestInfo object. |
| 4444 | // If shard_tests == true, further filters tests based on sharding |
| 4445 | // variables in the environment - see |
| 4446 | // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. |
| 4447 | // Returns the number of tests that should run. |
| 4448 | int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { |
| 4449 | const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? |
| 4450 | Int32FromEnvOrDie(kTestTotalShards, -1) : -1; |
| 4451 | const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? |
| 4452 | Int32FromEnvOrDie(kTestShardIndex, -1) : -1; |
| 4453 | |
| 4454 | // num_runnable_tests are the number of tests that will |
| 4455 | // run across all shards (i.e., match filter and are not disabled). |
| 4456 | // num_selected_tests are the number of tests to be run on |
| 4457 | // this shard. |
| 4458 | int num_runnable_tests = 0; |
| 4459 | int num_selected_tests = 0; |
| 4460 | for (size_t i = 0; i < test_cases_.size(); i++) { |
| 4461 | TestCase* const test_case = test_cases_[i]; |
| 4462 | const std::string &test_case_name = test_case->name(); |
| 4463 | test_case->set_should_run(false); |
| 4464 | |
| 4465 | for (size_t j = 0; j < test_case->test_info_list().size(); j++) { |
| 4466 | TestInfo* const test_info = test_case->test_info_list()[j]; |
| 4467 | const std::string test_name(test_info->name()); |
| 4468 | // A test is disabled if test case name or test name matches |
| 4469 | // kDisableTestFilter. |
| 4470 | const bool is_disabled = |
| 4471 | internal::UnitTestOptions::MatchesFilter(test_case_name, |
| 4472 | kDisableTestFilter) || |
| 4473 | internal::UnitTestOptions::MatchesFilter(test_name, |
| 4474 | kDisableTestFilter); |
| 4475 | test_info->is_disabled_ = is_disabled; |
| 4476 | |
| 4477 | const bool matches_filter = |
| 4478 | internal::UnitTestOptions::FilterMatchesTest(test_case_name, |
| 4479 | test_name); |
| 4480 | test_info->matches_filter_ = matches_filter; |
| 4481 | |
| 4482 | const bool is_runnable = |
| 4483 | (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && |
| 4484 | matches_filter; |
| 4485 | |
| 4486 | const bool is_selected = is_runnable && |
| 4487 | (shard_tests == IGNORE_SHARDING_PROTOCOL || |
| 4488 | ShouldRunTestOnShard(total_shards, shard_index, |
| 4489 | num_runnable_tests)); |
| 4490 | |
| 4491 | num_runnable_tests += is_runnable; |
| 4492 | num_selected_tests += is_selected; |
| 4493 | |
| 4494 | test_info->should_run_ = is_selected; |
| 4495 | test_case->set_should_run(test_case->should_run() || is_selected); |
| 4496 | } |
| 4497 | } |
| 4498 | return num_selected_tests; |
| 4499 | } |
| 4500 | |
| 4501 | // Prints the given C-string on a single line by replacing all '\n' |
| 4502 | // characters with string "\\n". If the output takes more than |
| 4503 | // max_length characters, only prints the first max_length characters |
| 4504 | // and "...". |
| 4505 | static void PrintOnOneLine(const char* str, int max_length) { |
| 4506 | if (str != NULL) { |
| 4507 | for (int i = 0; *str != '\0'; ++str) { |
| 4508 | if (i >= max_length) { |
| 4509 | printf("..."); |
| 4510 | break; |
| 4511 | } |
| 4512 | if (*str == '\n') { |
| 4513 | printf("\\n"); |
| 4514 | i += 2; |
| 4515 | } else { |
| 4516 | printf("%c", *str); |
| 4517 | ++i; |
| 4518 | } |
| 4519 | } |
| 4520 | } |
| 4521 | } |
| 4522 | |
| 4523 | // Prints the names of the tests matching the user-specified filter flag. |
| 4524 | void UnitTestImpl::ListTestsMatchingFilter() { |
| 4525 | // Print at most this many characters for each type/value parameter. |
| 4526 | const int kMaxParamLength = 250; |
| 4527 | |
| 4528 | for (size_t i = 0; i < test_cases_.size(); i++) { |
| 4529 | const TestCase* const test_case = test_cases_[i]; |
| 4530 | bool printed_test_case_name = false; |
| 4531 | |
| 4532 | for (size_t j = 0; j < test_case->test_info_list().size(); j++) { |
| 4533 | const TestInfo* const test_info = |
| 4534 | test_case->test_info_list()[j]; |
| 4535 | if (test_info->matches_filter_) { |
| 4536 | if (!printed_test_case_name) { |
| 4537 | printed_test_case_name = true; |
| 4538 | printf("%s.", test_case->name()); |
| 4539 | if (test_case->type_param() != NULL) { |
| 4540 | printf(" # %s = ", kTypeParamLabel); |
| 4541 | // We print the type parameter on a single line to make |
| 4542 | // the output easy to parse by a program. |
| 4543 | PrintOnOneLine(test_case->type_param(), kMaxParamLength); |
| 4544 | } |
| 4545 | printf("\n"); |
| 4546 | } |
| 4547 | printf(" %s", test_info->name()); |
| 4548 | if (test_info->value_param() != NULL) { |
| 4549 | printf(" # %s = ", kValueParamLabel); |
| 4550 | // We print the value parameter on a single line to make the |
| 4551 | // output easy to parse by a program. |
| 4552 | PrintOnOneLine(test_info->value_param(), kMaxParamLength); |
| 4553 | } |
| 4554 | printf("\n"); |
| 4555 | } |
| 4556 | } |
| 4557 | } |
| 4558 | fflush(stdout); |
| 4559 | } |
| 4560 | |
| 4561 | // Sets the OS stack trace getter. |
| 4562 | // |
| 4563 | // Does nothing if the input and the current OS stack trace getter are |
| 4564 | // the same; otherwise, deletes the old getter and makes the input the |
| 4565 | // current getter. |
| 4566 | void UnitTestImpl::set_os_stack_trace_getter( |
| 4567 | OsStackTraceGetterInterface* getter) { |
| 4568 | if (os_stack_trace_getter_ != getter) { |
| 4569 | delete os_stack_trace_getter_; |
| 4570 | os_stack_trace_getter_ = getter; |
| 4571 | } |
| 4572 | } |
| 4573 | |
| 4574 | // Returns the current OS stack trace getter if it is not NULL; |
| 4575 | // otherwise, creates an OsStackTraceGetter, makes it the current |
| 4576 | // getter, and returns it. |
| 4577 | OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { |
| 4578 | if (os_stack_trace_getter_ == NULL) { |
| 4579 | os_stack_trace_getter_ = new OsStackTraceGetter; |
| 4580 | } |
| 4581 | |
| 4582 | return os_stack_trace_getter_; |
| 4583 | } |
| 4584 | |
| 4585 | // Returns the TestResult for the test that's currently running, or |
| 4586 | // the TestResult for the ad hoc test if no test is running. |
| 4587 | TestResult* UnitTestImpl::current_test_result() { |
| 4588 | return current_test_info_ ? |
| 4589 | &(current_test_info_->result_) : &ad_hoc_test_result_; |
| 4590 | } |
| 4591 | |
| 4592 | // Shuffles all test cases, and the tests within each test case, |
| 4593 | // making sure that death tests are still run first. |
| 4594 | void UnitTestImpl::ShuffleTests() { |
| 4595 | // Shuffles the death test cases. |
| 4596 | ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); |
| 4597 | |
| 4598 | // Shuffles the non-death test cases. |
| 4599 | ShuffleRange(random(), last_death_test_case_ + 1, |
| 4600 | static_cast<int>(test_cases_.size()), &test_case_indices_); |
| 4601 | |
| 4602 | // Shuffles the tests inside each test case. |
| 4603 | for (size_t i = 0; i < test_cases_.size(); i++) { |
| 4604 | test_cases_[i]->ShuffleTests(random()); |
| 4605 | } |
| 4606 | } |
| 4607 | |
| 4608 | // Restores the test cases and tests to their order before the first shuffle. |
| 4609 | void UnitTestImpl::UnshuffleTests() { |
| 4610 | for (size_t i = 0; i < test_cases_.size(); i++) { |
| 4611 | // Unshuffles the tests in each test case. |
| 4612 | test_cases_[i]->UnshuffleTests(); |
| 4613 | // Resets the index of each test case. |
| 4614 | test_case_indices_[i] = static_cast<int>(i); |
| 4615 | } |
| 4616 | } |
| 4617 | |
| 4618 | // Returns the current OS stack trace as an std::string. |
| 4619 | // |
| 4620 | // The maximum number of stack frames to be included is specified by |
| 4621 | // the gtest_stack_trace_depth flag. The skip_count parameter |
| 4622 | // specifies the number of top frames to be skipped, which doesn't |
| 4623 | // count against the number of frames to be included. |
| 4624 | // |
| 4625 | // For example, if Foo() calls Bar(), which in turn calls |
| 4626 | // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in |
| 4627 | // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. |
| 4628 | std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, |
| 4629 | int skip_count) { |
| 4630 | // We pass skip_count + 1 to skip this wrapper function in addition |
| 4631 | // to what the user really wants to skip. |
| 4632 | return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); |
| 4633 | } |
| 4634 | |
| 4635 | // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to |
| 4636 | // suppress unreachable code warnings. |
| 4637 | namespace { |
| 4638 | class ClassUniqueToAlwaysTrue {}; |
| 4639 | } |
| 4640 | |
| 4641 | bool IsTrue(bool condition) { return condition; } |
| 4642 | |
| 4643 | bool AlwaysTrue() { |
| 4644 | #if GTEST_HAS_EXCEPTIONS |
| 4645 | // This condition is always false so AlwaysTrue() never actually throws, |
| 4646 | // but it makes the compiler think that it may throw. |
| 4647 | if (IsTrue(false)) |
| 4648 | throw ClassUniqueToAlwaysTrue(); |
| 4649 | #endif // GTEST_HAS_EXCEPTIONS |
| 4650 | return true; |
| 4651 | } |
| 4652 | |
| 4653 | // If *pstr starts with the given prefix, modifies *pstr to be right |
| 4654 | // past the prefix and returns true; otherwise leaves *pstr unchanged |
| 4655 | // and returns false. None of pstr, *pstr, and prefix can be NULL. |
| 4656 | bool SkipPrefix(const char* prefix, const char** pstr) { |
| 4657 | const size_t prefix_len = strlen(prefix); |
| 4658 | if (strncmp(*pstr, prefix, prefix_len) == 0) { |
| 4659 | *pstr += prefix_len; |
| 4660 | return true; |
| 4661 | } |
| 4662 | return false; |
| 4663 | } |
| 4664 | |
| 4665 | // Parses a string as a command line flag. The string should have |
| 4666 | // the format "--flag=value". When def_optional is true, the "=value" |
| 4667 | // part can be omitted. |
| 4668 | // |
| 4669 | // Returns the value of the flag, or NULL if the parsing failed. |
| 4670 | const char* ParseFlagValue(const char* str, |
| 4671 | const char* flag, |
| 4672 | bool def_optional) { |
| 4673 | // str and flag must not be NULL. |
| 4674 | if (str == NULL || flag == NULL) return NULL; |
| 4675 | |
| 4676 | // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. |
| 4677 | const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; |
| 4678 | const size_t flag_len = flag_str.length(); |
| 4679 | if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; |
| 4680 | |
| 4681 | // Skips the flag name. |
| 4682 | const char* flag_end = str + flag_len; |
| 4683 | |
| 4684 | // When def_optional is true, it's OK to not have a "=value" part. |
| 4685 | if (def_optional && (flag_end[0] == '\0')) { |
| 4686 | return flag_end; |
| 4687 | } |
| 4688 | |
| 4689 | // If def_optional is true and there are more characters after the |
| 4690 | // flag name, or if def_optional is false, there must be a '=' after |
| 4691 | // the flag name. |
| 4692 | if (flag_end[0] != '=') return NULL; |
| 4693 | |
| 4694 | // Returns the string after "=". |
| 4695 | return flag_end + 1; |
| 4696 | } |
| 4697 | |
| 4698 | // Parses a string for a bool flag, in the form of either |
| 4699 | // "--flag=value" or "--flag". |
| 4700 | // |
| 4701 | // In the former case, the value is taken as true as long as it does |
| 4702 | // not start with '0', 'f', or 'F'. |
| 4703 | // |
| 4704 | // In the latter case, the value is taken as true. |
| 4705 | // |
| 4706 | // On success, stores the value of the flag in *value, and returns |
| 4707 | // true. On failure, returns false without changing *value. |
| 4708 | bool ParseBoolFlag(const char* str, const char* flag, bool* value) { |
| 4709 | // Gets the value of the flag as a string. |
| 4710 | const char* const value_str = ParseFlagValue(str, flag, true); |
| 4711 | |
| 4712 | // Aborts if the parsing failed. |
| 4713 | if (value_str == NULL) return false; |
| 4714 | |
| 4715 | // Converts the string value to a bool. |
| 4716 | *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); |
| 4717 | return true; |
| 4718 | } |
| 4719 | |
| 4720 | // Parses a string for an Int32 flag, in the form of |
| 4721 | // "--flag=value". |
| 4722 | // |
| 4723 | // On success, stores the value of the flag in *value, and returns |
| 4724 | // true. On failure, returns false without changing *value. |
| 4725 | bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { |
| 4726 | // Gets the value of the flag as a string. |
| 4727 | const char* const value_str = ParseFlagValue(str, flag, false); |
| 4728 | |
| 4729 | // Aborts if the parsing failed. |
| 4730 | if (value_str == NULL) return false; |
| 4731 | |
| 4732 | // Sets *value to the value of the flag. |
| 4733 | return ParseInt32(Message() << "The value of flag --" << flag, |
| 4734 | value_str, value); |
| 4735 | } |
| 4736 | |
| 4737 | // Parses a string for a string flag, in the form of |
| 4738 | // "--flag=value". |
| 4739 | // |
| 4740 | // On success, stores the value of the flag in *value, and returns |
| 4741 | // true. On failure, returns false without changing *value. |
| 4742 | bool ParseStringFlag(const char* str, const char* flag, std::string* value) { |
| 4743 | // Gets the value of the flag as a string. |
| 4744 | const char* const value_str = ParseFlagValue(str, flag, false); |
| 4745 | |
| 4746 | // Aborts if the parsing failed. |
| 4747 | if (value_str == NULL) return false; |
| 4748 | |
| 4749 | // Sets *value to the value of the flag. |
| 4750 | *value = value_str; |
| 4751 | return true; |
| 4752 | } |
| 4753 | |
| 4754 | // Determines whether a string has a prefix that Google Test uses for its |
| 4755 | // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. |
| 4756 | // If Google Test detects that a command line flag has its prefix but is not |
| 4757 | // recognized, it will print its help message. Flags starting with |
| 4758 | // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test |
| 4759 | // internal flags and do not trigger the help message. |
| 4760 | static bool HasGoogleTestFlagPrefix(const char* str) { |
| 4761 | return (SkipPrefix("--", &str) || |
| 4762 | SkipPrefix("-", &str) || |
| 4763 | SkipPrefix("/", &str)) && |
| 4764 | !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && |
| 4765 | (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || |
| 4766 | SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); |
| 4767 | } |
| 4768 | |
| 4769 | // Prints a string containing code-encoded text. The following escape |
| 4770 | // sequences can be used in the string to control the text color: |
| 4771 | // |
| 4772 | // @@ prints a single '@' character. |
| 4773 | // @R changes the color to red. |
| 4774 | // @G changes the color to green. |
| 4775 | // @Y changes the color to yellow. |
| 4776 | // @D changes to the default terminal text color. |
| 4777 | // |
| 4778 | // TODO(wan@google.com): Write tests for this once we add stdout |
| 4779 | // capturing to Google Test. |
| 4780 | static void PrintColorEncoded(const char* str) { |
| 4781 | GTestColor color = COLOR_DEFAULT; // The current color. |
| 4782 | |
| 4783 | // Conceptually, we split the string into segments divided by escape |
| 4784 | // sequences. Then we print one segment at a time. At the end of |
| 4785 | // each iteration, the str pointer advances to the beginning of the |
| 4786 | // next segment. |
| 4787 | for (;;) { |
| 4788 | const char* p = strchr(str, '@'); |
| 4789 | if (p == NULL) { |
| 4790 | ColoredPrintf(color, "%s", str); |
| 4791 | return; |
| 4792 | } |
| 4793 | |
| 4794 | ColoredPrintf(color, "%s", std::string(str, p).c_str()); |
| 4795 | |
| 4796 | const char ch = p[1]; |
| 4797 | str = p + 2; |
| 4798 | if (ch == '@') { |
| 4799 | ColoredPrintf(color, "@"); |
| 4800 | } else if (ch == 'D') { |
| 4801 | color = COLOR_DEFAULT; |
| 4802 | } else if (ch == 'R') { |
| 4803 | color = COLOR_RED; |
| 4804 | } else if (ch == 'G') { |
| 4805 | color = COLOR_GREEN; |
| 4806 | } else if (ch == 'Y') { |
| 4807 | color = COLOR_YELLOW; |
| 4808 | } else { |
| 4809 | --str; |
| 4810 | } |
| 4811 | } |
| 4812 | } |
| 4813 | |
| 4814 | static const char kColorEncodedHelpMessage[] = |
| 4815 | "This program contains tests written using " GTEST_NAME_ ". You can use the\n" |
| 4816 | "following command line flags to control its behavior:\n" |
| 4817 | "\n" |
| 4818 | "Test Selection:\n" |
| 4819 | " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" |
| 4820 | " List the names of all tests instead of running them. The name of\n" |
| 4821 | " TEST(Foo, Bar) is \"Foo.Bar\".\n" |
| 4822 | " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" |
| 4823 | "[@G-@YNEGATIVE_PATTERNS]@D\n" |
| 4824 | " Run only the tests whose name matches one of the positive patterns but\n" |
| 4825 | " none of the negative patterns. '?' matches any single character; '*'\n" |
| 4826 | " matches any substring; ':' separates two patterns.\n" |
| 4827 | " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" |
| 4828 | " Run all disabled tests too.\n" |
| 4829 | "\n" |
| 4830 | "Test Execution:\n" |
| 4831 | " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" |
| 4832 | " Run the tests repeatedly; use a negative count to repeat forever.\n" |
| 4833 | " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" |
| 4834 | " Randomize tests' orders on every iteration.\n" |
| 4835 | " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" |
| 4836 | " Random number seed to use for shuffling test orders (between 1 and\n" |
| 4837 | " 99999, or 0 to use a seed based on the current time).\n" |
| 4838 | "\n" |
| 4839 | "Test Output:\n" |
| 4840 | " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" |
| 4841 | " Enable/disable colored output. The default is @Gauto@D.\n" |
| 4842 | " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" |
| 4843 | " Don't print the elapsed time of each test.\n" |
| 4844 | " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" |
| 4845 | GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" |
| 4846 | " Generate an XML report in the given directory or with the given file\n" |
| 4847 | " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" |
| 4848 | #if GTEST_CAN_STREAM_RESULTS_ |
| 4849 | " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" |
| 4850 | " Stream test results to the given server.\n" |
| 4851 | #endif // GTEST_CAN_STREAM_RESULTS_ |
| 4852 | "\n" |
| 4853 | "Assertion Behavior:\n" |
| 4854 | #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS |
| 4855 | " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" |
| 4856 | " Set the default death test style.\n" |
| 4857 | #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS |
| 4858 | " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" |
| 4859 | " Turn assertion failures into debugger break-points.\n" |
| 4860 | " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" |
| 4861 | " Turn assertion failures into C++ exceptions.\n" |
| 4862 | " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" |
| 4863 | " Do not report exceptions as test failures. Instead, allow them\n" |
| 4864 | " to crash the program or throw a pop-up (on Windows).\n" |
| 4865 | "\n" |
| 4866 | "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " |
| 4867 | "the corresponding\n" |
| 4868 | "environment variable of a flag (all letters in upper-case). For example, to\n" |
| 4869 | "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ |
| 4870 | "color=no@D or set\n" |
| 4871 | "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" |
| 4872 | "\n" |
| 4873 | "For more information, please read the " GTEST_NAME_ " documentation at\n" |
| 4874 | "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" |
| 4875 | "(not one in your own code or tests), please report it to\n" |
| 4876 | "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; |
| 4877 | |
| 4878 | // Parses the command line for Google Test flags, without initializing |
| 4879 | // other parts of Google Test. The type parameter CharType can be |
| 4880 | // instantiated to either char or wchar_t. |
| 4881 | template <typename CharType> |
| 4882 | void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { |
| 4883 | for (int i = 1; i < *argc; i++) { |
| 4884 | const std::string arg_string = StreamableToString(argv[i]); |
| 4885 | const char* const arg = arg_string.c_str(); |
| 4886 | |
| 4887 | using internal::ParseBoolFlag; |
| 4888 | using internal::ParseInt32Flag; |
| 4889 | using internal::ParseStringFlag; |
| 4890 | |
| 4891 | // Do we see a Google Test flag? |
| 4892 | if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, |
| 4893 | >EST_FLAG(also_run_disabled_tests)) || |
| 4894 | ParseBoolFlag(arg, kBreakOnFailureFlag, |
| 4895 | >EST_FLAG(break_on_failure)) || |
| 4896 | ParseBoolFlag(arg, kCatchExceptionsFlag, |
| 4897 | >EST_FLAG(catch_exceptions)) || |
| 4898 | ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || |
| 4899 | ParseStringFlag(arg, kDeathTestStyleFlag, |
| 4900 | >EST_FLAG(death_test_style)) || |
| 4901 | ParseBoolFlag(arg, kDeathTestUseFork, |
| 4902 | >EST_FLAG(death_test_use_fork)) || |
| 4903 | ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || |
| 4904 | ParseStringFlag(arg, kInternalRunDeathTestFlag, |
| 4905 | >EST_FLAG(internal_run_death_test)) || |
| 4906 | ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || |
| 4907 | ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || |
| 4908 | ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || |
| 4909 | ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || |
| 4910 | ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || |
| 4911 | ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || |
| 4912 | ParseInt32Flag(arg, kStackTraceDepthFlag, |
| 4913 | >EST_FLAG(stack_trace_depth)) || |
| 4914 | ParseStringFlag(arg, kStreamResultToFlag, |
| 4915 | >EST_FLAG(stream_result_to)) || |
| 4916 | ParseBoolFlag(arg, kThrowOnFailureFlag, |
| 4917 | >EST_FLAG(throw_on_failure)) |
| 4918 | ) { |
| 4919 | // Yes. Shift the remainder of the argv list left by one. Note |
| 4920 | // that argv has (*argc + 1) elements, the last one always being |
| 4921 | // NULL. The following loop moves the trailing NULL element as |
| 4922 | // well. |
| 4923 | for (int j = i; j != *argc; j++) { |
| 4924 | argv[j] = argv[j + 1]; |
| 4925 | } |
| 4926 | |
| 4927 | // Decrements the argument count. |
| 4928 | (*argc)--; |
| 4929 | |
| 4930 | // We also need to decrement the iterator as we just removed |
| 4931 | // an element. |
| 4932 | i--; |
| 4933 | } else if (arg_string == "--help" || arg_string == "-h" || |
| 4934 | arg_string == "-?" || arg_string == "/?" || |
| 4935 | HasGoogleTestFlagPrefix(arg)) { |
| 4936 | // Both help flag and unrecognized Google Test flags (excluding |
| 4937 | // internal ones) trigger help display. |
| 4938 | g_help_flag = true; |
| 4939 | } |
| 4940 | } |
| 4941 | |
| 4942 | if (g_help_flag) { |
| 4943 | // We print the help here instead of in RUN_ALL_TESTS(), as the |
| 4944 | // latter may not be called at all if the user is using Google |
| 4945 | // Test with another testing framework. |
| 4946 | PrintColorEncoded(kColorEncodedHelpMessage); |
| 4947 | } |
| 4948 | } |
| 4949 | |
| 4950 | // Parses the command line for Google Test flags, without initializing |
| 4951 | // other parts of Google Test. |
| 4952 | void ParseGoogleTestFlagsOnly(int* argc, char** argv) { |
| 4953 | ParseGoogleTestFlagsOnlyImpl(argc, argv); |
| 4954 | } |
| 4955 | void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { |
| 4956 | ParseGoogleTestFlagsOnlyImpl(argc, argv); |
| 4957 | } |
| 4958 | |
| 4959 | // The internal implementation of InitGoogleTest(). |
| 4960 | // |
| 4961 | // The type parameter CharType can be instantiated to either char or |
| 4962 | // wchar_t. |
| 4963 | template <typename CharType> |
| 4964 | void InitGoogleTestImpl(int* argc, CharType** argv) { |
| 4965 | g_init_gtest_count++; |
| 4966 | |
| 4967 | // We don't want to run the initialization code twice. |
| 4968 | if (g_init_gtest_count != 1) return; |
| 4969 | |
| 4970 | if (*argc <= 0) return; |
| 4971 | |
| 4972 | internal::g_executable_path = internal::StreamableToString(argv[0]); |
| 4973 | |
| 4974 | #if GTEST_HAS_DEATH_TEST |
| 4975 | |
| 4976 | g_argvs.clear(); |
| 4977 | for (int i = 0; i != *argc; i++) { |
| 4978 | g_argvs.push_back(StreamableToString(argv[i])); |
| 4979 | } |
| 4980 | |
| 4981 | #endif // GTEST_HAS_DEATH_TEST |
| 4982 | |
| 4983 | ParseGoogleTestFlagsOnly(argc, argv); |
| 4984 | GetUnitTestImpl()->PostFlagParsingInit(); |
| 4985 | } |
| 4986 | |
| 4987 | } // namespace internal |
| 4988 | |
| 4989 | // Initializes Google Test. This must be called before calling |
| 4990 | // RUN_ALL_TESTS(). In particular, it parses a command line for the |
| 4991 | // flags that Google Test recognizes. Whenever a Google Test flag is |
| 4992 | // seen, it is removed from argv, and *argc is decremented. |
| 4993 | // |
| 4994 | // No value is returned. Instead, the Google Test flag variables are |
| 4995 | // updated. |
| 4996 | // |
| 4997 | // Calling the function for the second time has no user-visible effect. |
| 4998 | void InitGoogleTest(int* argc, char** argv) { |
| 4999 | internal::InitGoogleTestImpl(argc, argv); |
| 5000 | } |
| 5001 | |
| 5002 | // This overloaded version can be used in Windows programs compiled in |
| 5003 | // UNICODE mode. |
| 5004 | void InitGoogleTest(int* argc, wchar_t** argv) { |
| 5005 | internal::InitGoogleTestImpl(argc, argv); |
| 5006 | } |
| 5007 | |
| 5008 | } // namespace testing |