Mercurial > minori
comparison dep/fmt/test/gtest/gmock-gtest-all.cc @ 343:1faa72660932
*: transfer back to cmake from autotools
autotools just made lots of things more complicated than
they should have and many things broke (i.e. translations)
| author | Paper <paper@paper.us.eu.org> |
|---|---|
| date | Thu, 20 Jun 2024 05:56:06 -0400 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 342:adb79bdde329 | 343:1faa72660932 |
|---|---|
| 1 // Copyright 2008, 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 // | |
| 31 // Google C++ Testing and Mocking Framework (Google Test) | |
| 32 // | |
| 33 // Sometimes it's desirable to build Google Test by compiling a single file. | |
| 34 // This file serves this purpose. | |
| 35 | |
| 36 // This line ensures that gtest.h can be compiled on its own, even | |
| 37 // when it's fused. | |
| 38 #include "gtest/gtest.h" | |
| 39 | |
| 40 // The following lines pull in the real gtest *.cc files. | |
| 41 // Copyright 2005, Google Inc. | |
| 42 // All rights reserved. | |
| 43 // | |
| 44 // Redistribution and use in source and binary forms, with or without | |
| 45 // modification, are permitted provided that the following conditions are | |
| 46 // met: | |
| 47 // | |
| 48 // * Redistributions of source code must retain the above copyright | |
| 49 // notice, this list of conditions and the following disclaimer. | |
| 50 // * Redistributions in binary form must reproduce the above | |
| 51 // copyright notice, this list of conditions and the following disclaimer | |
| 52 // in the documentation and/or other materials provided with the | |
| 53 // distribution. | |
| 54 // * Neither the name of Google Inc. nor the names of its | |
| 55 // contributors may be used to endorse or promote products derived from | |
| 56 // this software without specific prior written permission. | |
| 57 // | |
| 58 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 59 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 60 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 61 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 62 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 63 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 64 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 65 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 66 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 67 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 68 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 69 | |
| 70 // | |
| 71 // The Google C++ Testing and Mocking Framework (Google Test) | |
| 72 | |
| 73 // Copyright 2007, Google Inc. | |
| 74 // All rights reserved. | |
| 75 // | |
| 76 // Redistribution and use in source and binary forms, with or without | |
| 77 // modification, are permitted provided that the following conditions are | |
| 78 // met: | |
| 79 // | |
| 80 // * Redistributions of source code must retain the above copyright | |
| 81 // notice, this list of conditions and the following disclaimer. | |
| 82 // * Redistributions in binary form must reproduce the above | |
| 83 // copyright notice, this list of conditions and the following disclaimer | |
| 84 // in the documentation and/or other materials provided with the | |
| 85 // distribution. | |
| 86 // * Neither the name of Google Inc. nor the names of its | |
| 87 // contributors may be used to endorse or promote products derived from | |
| 88 // this software without specific prior written permission. | |
| 89 // | |
| 90 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 91 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 92 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 93 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 94 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 95 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 96 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 97 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 98 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 99 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 100 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 101 | |
| 102 // | |
| 103 // Utilities for testing Google Test itself and code that uses Google Test | |
| 104 // (e.g. frameworks built on top of Google Test). | |
| 105 | |
| 106 // GOOGLETEST_CM0004 DO NOT DELETE | |
| 107 | |
| 108 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ | |
| 109 #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ | |
| 110 | |
| 111 | |
| 112 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ | |
| 113 /* class A needs to have dll-interface to be used by clients of class B */) | |
| 114 | |
| 115 namespace testing { | |
| 116 | |
| 117 // This helper class can be used to mock out Google Test failure reporting | |
| 118 // so that we can test Google Test or code that builds on Google Test. | |
| 119 // | |
| 120 // An object of this class appends a TestPartResult object to the | |
| 121 // TestPartResultArray object given in the constructor whenever a Google Test | |
| 122 // failure is reported. It can either intercept only failures that are | |
| 123 // generated in the same thread that created this object or it can intercept | |
| 124 // all generated failures. The scope of this mock object can be controlled with | |
| 125 // the second argument to the two arguments constructor. | |
| 126 class GTEST_API_ ScopedFakeTestPartResultReporter | |
| 127 : public TestPartResultReporterInterface { | |
| 128 public: | |
| 129 // The two possible mocking modes of this object. | |
| 130 enum InterceptMode { | |
| 131 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. | |
| 132 INTERCEPT_ALL_THREADS // Intercepts all failures. | |
| 133 }; | |
| 134 | |
| 135 // The c'tor sets this object as the test part result reporter used | |
| 136 // by Google Test. The 'result' parameter specifies where to report the | |
| 137 // results. This reporter will only catch failures generated in the current | |
| 138 // thread. DEPRECATED | |
| 139 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); | |
| 140 | |
| 141 // Same as above, but you can choose the interception scope of this object. | |
| 142 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, | |
| 143 TestPartResultArray* result); | |
| 144 | |
| 145 // The d'tor restores the previous test part result reporter. | |
| 146 ~ScopedFakeTestPartResultReporter() override; | |
| 147 | |
| 148 // Appends the TestPartResult object to the TestPartResultArray | |
| 149 // received in the constructor. | |
| 150 // | |
| 151 // This method is from the TestPartResultReporterInterface | |
| 152 // interface. | |
| 153 void ReportTestPartResult(const TestPartResult& result) override; | |
| 154 | |
| 155 private: | |
| 156 void Init(); | |
| 157 | |
| 158 const InterceptMode intercept_mode_; | |
| 159 TestPartResultReporterInterface* old_reporter_; | |
| 160 TestPartResultArray* const result_; | |
| 161 | |
| 162 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); | |
| 163 }; | |
| 164 | |
| 165 namespace internal { | |
| 166 | |
| 167 // A helper class for implementing EXPECT_FATAL_FAILURE() and | |
| 168 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given | |
| 169 // TestPartResultArray contains exactly one failure that has the given | |
| 170 // type and contains the given substring. If that's not the case, a | |
| 171 // non-fatal failure will be generated. | |
| 172 class GTEST_API_ SingleFailureChecker { | |
| 173 public: | |
| 174 // The constructor remembers the arguments. | |
| 175 SingleFailureChecker(const TestPartResultArray* results, | |
| 176 TestPartResult::Type type, const std::string& substr); | |
| 177 ~SingleFailureChecker(); | |
| 178 private: | |
| 179 const TestPartResultArray* const results_; | |
| 180 const TestPartResult::Type type_; | |
| 181 const std::string substr_; | |
| 182 | |
| 183 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); | |
| 184 }; | |
| 185 | |
| 186 } // namespace internal | |
| 187 | |
| 188 } // namespace testing | |
| 189 | |
| 190 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 | |
| 191 | |
| 192 // A set of macros for testing Google Test assertions or code that's expected | |
| 193 // to generate Google Test fatal failures. It verifies that the given | |
| 194 // statement will cause exactly one fatal Google Test failure with 'substr' | |
| 195 // being part of the failure message. | |
| 196 // | |
| 197 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only | |
| 198 // affects and considers failures generated in the current thread and | |
| 199 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. | |
| 200 // | |
| 201 // The verification of the assertion is done correctly even when the statement | |
| 202 // throws an exception or aborts the current function. | |
| 203 // | |
| 204 // Known restrictions: | |
| 205 // - 'statement' cannot reference local non-static variables or | |
| 206 // non-static members of the current object. | |
| 207 // - 'statement' cannot return a value. | |
| 208 // - You cannot stream a failure message to this macro. | |
| 209 // | |
| 210 // Note that even though the implementations of the following two | |
| 211 // macros are much alike, we cannot refactor them to use a common | |
| 212 // helper macro, due to some peculiarity in how the preprocessor | |
| 213 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in | |
| 214 // gtest_unittest.cc will fail to compile if we do that. | |
| 215 #define EXPECT_FATAL_FAILURE(statement, substr) \ | |
| 216 do { \ | |
| 217 class GTestExpectFatalFailureHelper {\ | |
| 218 public:\ | |
| 219 static void Execute() { statement; }\ | |
| 220 };\ | |
| 221 ::testing::TestPartResultArray gtest_failures;\ | |
| 222 ::testing::internal::SingleFailureChecker gtest_checker(\ | |
| 223 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ | |
| 224 {\ | |
| 225 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ | |
| 226 ::testing::ScopedFakeTestPartResultReporter:: \ | |
| 227 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ | |
| 228 GTestExpectFatalFailureHelper::Execute();\ | |
| 229 }\ | |
| 230 } while (::testing::internal::AlwaysFalse()) | |
| 231 | |
| 232 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ | |
| 233 do { \ | |
| 234 class GTestExpectFatalFailureHelper {\ | |
| 235 public:\ | |
| 236 static void Execute() { statement; }\ | |
| 237 };\ | |
| 238 ::testing::TestPartResultArray gtest_failures;\ | |
| 239 ::testing::internal::SingleFailureChecker gtest_checker(\ | |
| 240 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ | |
| 241 {\ | |
| 242 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ | |
| 243 ::testing::ScopedFakeTestPartResultReporter:: \ | |
| 244 INTERCEPT_ALL_THREADS, >est_failures);\ | |
| 245 GTestExpectFatalFailureHelper::Execute();\ | |
| 246 }\ | |
| 247 } while (::testing::internal::AlwaysFalse()) | |
| 248 | |
| 249 // A macro for testing Google Test assertions or code that's expected to | |
| 250 // generate Google Test non-fatal failures. It asserts that the given | |
| 251 // statement will cause exactly one non-fatal Google Test failure with 'substr' | |
| 252 // being part of the failure message. | |
| 253 // | |
| 254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only | |
| 255 // affects and considers failures generated in the current thread and | |
| 256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. | |
| 257 // | |
| 258 // 'statement' is allowed to reference local variables and members of | |
| 259 // the current object. | |
| 260 // | |
| 261 // The verification of the assertion is done correctly even when the statement | |
| 262 // throws an exception or aborts the current function. | |
| 263 // | |
| 264 // Known restrictions: | |
| 265 // - You cannot stream a failure message to this macro. | |
| 266 // | |
| 267 // Note that even though the implementations of the following two | |
| 268 // macros are much alike, we cannot refactor them to use a common | |
| 269 // helper macro, due to some peculiarity in how the preprocessor | |
| 270 // works. If we do that, the code won't compile when the user gives | |
| 271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that | |
| 272 // expands to code containing an unprotected comma. The | |
| 273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc | |
| 274 // catches that. | |
| 275 // | |
| 276 // For the same reason, we have to write | |
| 277 // if (::testing::internal::AlwaysTrue()) { statement; } | |
| 278 // instead of | |
| 279 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) | |
| 280 // to avoid an MSVC warning on unreachable code. | |
| 281 #define EXPECT_NONFATAL_FAILURE(statement, substr) \ | |
| 282 do {\ | |
| 283 ::testing::TestPartResultArray gtest_failures;\ | |
| 284 ::testing::internal::SingleFailureChecker gtest_checker(\ | |
| 285 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ | |
| 286 (substr));\ | |
| 287 {\ | |
| 288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ | |
| 289 ::testing::ScopedFakeTestPartResultReporter:: \ | |
| 290 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ | |
| 291 if (::testing::internal::AlwaysTrue()) { statement; }\ | |
| 292 }\ | |
| 293 } while (::testing::internal::AlwaysFalse()) | |
| 294 | |
| 295 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ | |
| 296 do {\ | |
| 297 ::testing::TestPartResultArray gtest_failures;\ | |
| 298 ::testing::internal::SingleFailureChecker gtest_checker(\ | |
| 299 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ | |
| 300 (substr));\ | |
| 301 {\ | |
| 302 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ | |
| 303 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ | |
| 304 >est_failures);\ | |
| 305 if (::testing::internal::AlwaysTrue()) { statement; }\ | |
| 306 }\ | |
| 307 } while (::testing::internal::AlwaysFalse()) | |
| 308 | |
| 309 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ | |
| 310 | |
| 311 #include <ctype.h> | |
| 312 #include <stdarg.h> | |
| 313 #include <stdio.h> | |
| 314 #include <stdlib.h> | |
| 315 #include <time.h> | |
| 316 #include <wchar.h> | |
| 317 #include <wctype.h> | |
| 318 | |
| 319 #include <algorithm> | |
| 320 #include <chrono> // NOLINT | |
| 321 #include <cmath> | |
| 322 #include <cstdint> | |
| 323 #include <iomanip> | |
| 324 #include <limits> | |
| 325 #include <list> | |
| 326 #include <map> | |
| 327 #include <ostream> // NOLINT | |
| 328 #include <sstream> | |
| 329 #include <vector> | |
| 330 | |
| 331 #if GTEST_OS_LINUX | |
| 332 | |
| 333 # include <fcntl.h> // NOLINT | |
| 334 # include <limits.h> // NOLINT | |
| 335 # include <sched.h> // NOLINT | |
| 336 // Declares vsnprintf(). This header is not available on Windows. | |
| 337 # include <strings.h> // NOLINT | |
| 338 # include <sys/mman.h> // NOLINT | |
| 339 # include <sys/time.h> // NOLINT | |
| 340 # include <unistd.h> // NOLINT | |
| 341 # include <string> | |
| 342 | |
| 343 #elif GTEST_OS_ZOS | |
| 344 # include <sys/time.h> // NOLINT | |
| 345 | |
| 346 // On z/OS we additionally need strings.h for strcasecmp. | |
| 347 # include <strings.h> // NOLINT | |
| 348 | |
| 349 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. | |
| 350 | |
| 351 # include <windows.h> // NOLINT | |
| 352 # undef min | |
| 353 | |
| 354 #elif GTEST_OS_WINDOWS // We are on Windows proper. | |
| 355 | |
| 356 # include <windows.h> // NOLINT | |
| 357 # undef min | |
| 358 | |
| 359 #ifdef _MSC_VER | |
| 360 # include <crtdbg.h> // NOLINT | |
| 361 #endif | |
| 362 | |
| 363 # include <io.h> // NOLINT | |
| 364 # include <sys/timeb.h> // NOLINT | |
| 365 # include <sys/types.h> // NOLINT | |
| 366 # include <sys/stat.h> // NOLINT | |
| 367 | |
| 368 # if GTEST_OS_WINDOWS_MINGW | |
| 369 # include <sys/time.h> // NOLINT | |
| 370 # endif // GTEST_OS_WINDOWS_MINGW | |
| 371 | |
| 372 #else | |
| 373 | |
| 374 // cpplint thinks that the header is already included, so we want to | |
| 375 // silence it. | |
| 376 # include <sys/time.h> // NOLINT | |
| 377 # include <unistd.h> // NOLINT | |
| 378 | |
| 379 #endif // GTEST_OS_LINUX | |
| 380 | |
| 381 #if GTEST_HAS_EXCEPTIONS | |
| 382 # include <stdexcept> | |
| 383 #endif | |
| 384 | |
| 385 #if GTEST_CAN_STREAM_RESULTS_ | |
| 386 # include <arpa/inet.h> // NOLINT | |
| 387 # include <netdb.h> // NOLINT | |
| 388 # include <sys/socket.h> // NOLINT | |
| 389 # include <sys/types.h> // NOLINT | |
| 390 #endif | |
| 391 | |
| 392 // Copyright 2005, Google Inc. | |
| 393 // All rights reserved. | |
| 394 // | |
| 395 // Redistribution and use in source and binary forms, with or without | |
| 396 // modification, are permitted provided that the following conditions are | |
| 397 // met: | |
| 398 // | |
| 399 // * Redistributions of source code must retain the above copyright | |
| 400 // notice, this list of conditions and the following disclaimer. | |
| 401 // * Redistributions in binary form must reproduce the above | |
| 402 // copyright notice, this list of conditions and the following disclaimer | |
| 403 // in the documentation and/or other materials provided with the | |
| 404 // distribution. | |
| 405 // * Neither the name of Google Inc. nor the names of its | |
| 406 // contributors may be used to endorse or promote products derived from | |
| 407 // this software without specific prior written permission. | |
| 408 // | |
| 409 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 410 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 411 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 412 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 413 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 414 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 415 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 416 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 417 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 418 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 419 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 420 | |
| 421 // Utility functions and classes used by the Google C++ testing framework.// | |
| 422 // This file contains purely Google Test's internal implementation. Please | |
| 423 // DO NOT #INCLUDE IT IN A USER PROGRAM. | |
| 424 | |
| 425 #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ | |
| 426 #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ | |
| 427 | |
| 428 #ifndef _WIN32_WCE | |
| 429 # include <errno.h> | |
| 430 #endif // !_WIN32_WCE | |
| 431 #include <stddef.h> | |
| 432 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. | |
| 433 #include <string.h> // For memmove. | |
| 434 | |
| 435 #include <algorithm> | |
| 436 #include <cstdint> | |
| 437 #include <memory> | |
| 438 #include <string> | |
| 439 #include <vector> | |
| 440 | |
| 441 | |
| 442 #if GTEST_CAN_STREAM_RESULTS_ | |
| 443 # include <arpa/inet.h> // NOLINT | |
| 444 # include <netdb.h> // NOLINT | |
| 445 #endif | |
| 446 | |
| 447 #if GTEST_OS_WINDOWS | |
| 448 # include <windows.h> // NOLINT | |
| 449 #endif // GTEST_OS_WINDOWS | |
| 450 | |
| 451 | |
| 452 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ | |
| 453 /* class A needs to have dll-interface to be used by clients of class B */) | |
| 454 | |
| 455 namespace testing { | |
| 456 | |
| 457 // Declares the flags. | |
| 458 // | |
| 459 // We don't want the users to modify this flag in the code, but want | |
| 460 // Google Test's own unit tests to be able to access it. Therefore we | |
| 461 // declare it here as opposed to in gtest.h. | |
| 462 GTEST_DECLARE_bool_(death_test_use_fork); | |
| 463 | |
| 464 namespace internal { | |
| 465 | |
| 466 // The value of GetTestTypeId() as seen from within the Google Test | |
| 467 // library. This is solely for testing GetTestTypeId(). | |
| 468 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; | |
| 469 | |
| 470 // Names of the flags (needed for parsing Google Test flags). | |
| 471 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; | |
| 472 const char kBreakOnFailureFlag[] = "break_on_failure"; | |
| 473 const char kCatchExceptionsFlag[] = "catch_exceptions"; | |
| 474 const char kColorFlag[] = "color"; | |
| 475 const char kFailFast[] = "fail_fast"; | |
| 476 const char kFilterFlag[] = "filter"; | |
| 477 const char kListTestsFlag[] = "list_tests"; | |
| 478 const char kOutputFlag[] = "output"; | |
| 479 const char kBriefFlag[] = "brief"; | |
| 480 const char kPrintTimeFlag[] = "print_time"; | |
| 481 const char kPrintUTF8Flag[] = "print_utf8"; | |
| 482 const char kRandomSeedFlag[] = "random_seed"; | |
| 483 const char kRepeatFlag[] = "repeat"; | |
| 484 const char kShuffleFlag[] = "shuffle"; | |
| 485 const char kStackTraceDepthFlag[] = "stack_trace_depth"; | |
| 486 const char kStreamResultToFlag[] = "stream_result_to"; | |
| 487 const char kThrowOnFailureFlag[] = "throw_on_failure"; | |
| 488 const char kFlagfileFlag[] = "flagfile"; | |
| 489 | |
| 490 // A valid random seed must be in [1, kMaxRandomSeed]. | |
| 491 const int kMaxRandomSeed = 99999; | |
| 492 | |
| 493 // g_help_flag is true if and only if the --help flag or an equivalent form | |
| 494 // is specified on the command line. | |
| 495 GTEST_API_ extern bool g_help_flag; | |
| 496 | |
| 497 // Returns the current time in milliseconds. | |
| 498 GTEST_API_ TimeInMillis GetTimeInMillis(); | |
| 499 | |
| 500 // Returns true if and only if Google Test should use colors in the output. | |
| 501 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); | |
| 502 | |
| 503 // Formats the given time in milliseconds as seconds. | |
| 504 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); | |
| 505 | |
| 506 // Converts the given time in milliseconds to a date string in the ISO 8601 | |
| 507 // format, without the timezone information. N.B.: due to the use the | |
| 508 // non-reentrant localtime() function, this function is not thread safe. Do | |
| 509 // not use it in any code that can be called from multiple threads. | |
| 510 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); | |
| 511 | |
| 512 // Parses a string for an Int32 flag, in the form of "--flag=value". | |
| 513 // | |
| 514 // On success, stores the value of the flag in *value, and returns | |
| 515 // true. On failure, returns false without changing *value. | |
| 516 GTEST_API_ bool ParseInt32Flag( | |
| 517 const char* str, const char* flag, int32_t* value); | |
| 518 | |
| 519 // Returns a random seed in range [1, kMaxRandomSeed] based on the | |
| 520 // given --gtest_random_seed flag value. | |
| 521 inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { | |
| 522 const unsigned int raw_seed = (random_seed_flag == 0) ? | |
| 523 static_cast<unsigned int>(GetTimeInMillis()) : | |
| 524 static_cast<unsigned int>(random_seed_flag); | |
| 525 | |
| 526 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that | |
| 527 // it's easy to type. | |
| 528 const int normalized_seed = | |
| 529 static_cast<int>((raw_seed - 1U) % | |
| 530 static_cast<unsigned int>(kMaxRandomSeed)) + 1; | |
| 531 return normalized_seed; | |
| 532 } | |
| 533 | |
| 534 // Returns the first valid random seed after 'seed'. The behavior is | |
| 535 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is | |
| 536 // considered to be 1. | |
| 537 inline int GetNextRandomSeed(int seed) { | |
| 538 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) | |
| 539 << "Invalid random seed " << seed << " - must be in [1, " | |
| 540 << kMaxRandomSeed << "]."; | |
| 541 const int next_seed = seed + 1; | |
| 542 return (next_seed > kMaxRandomSeed) ? 1 : next_seed; | |
| 543 } | |
| 544 | |
| 545 // This class saves the values of all Google Test flags in its c'tor, and | |
| 546 // restores them in its d'tor. | |
| 547 class GTestFlagSaver { | |
| 548 public: | |
| 549 // The c'tor. | |
| 550 GTestFlagSaver() { | |
| 551 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); | |
| 552 break_on_failure_ = GTEST_FLAG(break_on_failure); | |
| 553 catch_exceptions_ = GTEST_FLAG(catch_exceptions); | |
| 554 color_ = GTEST_FLAG(color); | |
| 555 death_test_style_ = GTEST_FLAG(death_test_style); | |
| 556 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); | |
| 557 fail_fast_ = GTEST_FLAG(fail_fast); | |
| 558 filter_ = GTEST_FLAG(filter); | |
| 559 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); | |
| 560 list_tests_ = GTEST_FLAG(list_tests); | |
| 561 output_ = GTEST_FLAG(output); | |
| 562 brief_ = GTEST_FLAG(brief); | |
| 563 print_time_ = GTEST_FLAG(print_time); | |
| 564 print_utf8_ = GTEST_FLAG(print_utf8); | |
| 565 random_seed_ = GTEST_FLAG(random_seed); | |
| 566 repeat_ = GTEST_FLAG(repeat); | |
| 567 shuffle_ = GTEST_FLAG(shuffle); | |
| 568 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); | |
| 569 stream_result_to_ = GTEST_FLAG(stream_result_to); | |
| 570 throw_on_failure_ = GTEST_FLAG(throw_on_failure); | |
| 571 } | |
| 572 | |
| 573 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. | |
| 574 ~GTestFlagSaver() { | |
| 575 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; | |
| 576 GTEST_FLAG(break_on_failure) = break_on_failure_; | |
| 577 GTEST_FLAG(catch_exceptions) = catch_exceptions_; | |
| 578 GTEST_FLAG(color) = color_; | |
| 579 GTEST_FLAG(death_test_style) = death_test_style_; | |
| 580 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; | |
| 581 GTEST_FLAG(filter) = filter_; | |
| 582 GTEST_FLAG(fail_fast) = fail_fast_; | |
| 583 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; | |
| 584 GTEST_FLAG(list_tests) = list_tests_; | |
| 585 GTEST_FLAG(output) = output_; | |
| 586 GTEST_FLAG(brief) = brief_; | |
| 587 GTEST_FLAG(print_time) = print_time_; | |
| 588 GTEST_FLAG(print_utf8) = print_utf8_; | |
| 589 GTEST_FLAG(random_seed) = random_seed_; | |
| 590 GTEST_FLAG(repeat) = repeat_; | |
| 591 GTEST_FLAG(shuffle) = shuffle_; | |
| 592 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; | |
| 593 GTEST_FLAG(stream_result_to) = stream_result_to_; | |
| 594 GTEST_FLAG(throw_on_failure) = throw_on_failure_; | |
| 595 } | |
| 596 | |
| 597 private: | |
| 598 // Fields for saving the original values of flags. | |
| 599 bool also_run_disabled_tests_; | |
| 600 bool break_on_failure_; | |
| 601 bool catch_exceptions_; | |
| 602 std::string color_; | |
| 603 std::string death_test_style_; | |
| 604 bool death_test_use_fork_; | |
| 605 bool fail_fast_; | |
| 606 std::string filter_; | |
| 607 std::string internal_run_death_test_; | |
| 608 bool list_tests_; | |
| 609 std::string output_; | |
| 610 bool brief_; | |
| 611 bool print_time_; | |
| 612 bool print_utf8_; | |
| 613 int32_t random_seed_; | |
| 614 int32_t repeat_; | |
| 615 bool shuffle_; | |
| 616 int32_t stack_trace_depth_; | |
| 617 std::string stream_result_to_; | |
| 618 bool throw_on_failure_; | |
| 619 } GTEST_ATTRIBUTE_UNUSED_; | |
| 620 | |
| 621 // Converts a Unicode code point to a narrow string in UTF-8 encoding. | |
| 622 // code_point parameter is of type UInt32 because wchar_t may not be | |
| 623 // wide enough to contain a code point. | |
| 624 // If the code_point is not a valid Unicode code point | |
| 625 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted | |
| 626 // to "(Invalid Unicode 0xXXXXXXXX)". | |
| 627 GTEST_API_ std::string CodePointToUtf8(uint32_t code_point); | |
| 628 | |
| 629 // Converts a wide string to a narrow string in UTF-8 encoding. | |
| 630 // The wide string is assumed to have the following encoding: | |
| 631 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) | |
| 632 // UTF-32 if sizeof(wchar_t) == 4 (on Linux) | |
| 633 // Parameter str points to a null-terminated wide string. | |
| 634 // Parameter num_chars may additionally limit the number | |
| 635 // of wchar_t characters processed. -1 is used when the entire string | |
| 636 // should be processed. | |
| 637 // If the string contains code points that are not valid Unicode code points | |
| 638 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output | |
| 639 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding | |
| 640 // and contains invalid UTF-16 surrogate pairs, values in those pairs | |
| 641 // will be encoded as individual Unicode characters from Basic Normal Plane. | |
| 642 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); | |
| 643 | |
| 644 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file | |
| 645 // if the variable is present. If a file already exists at this location, this | |
| 646 // function will write over it. If the variable is present, but the file cannot | |
| 647 // be created, prints an error and exits. | |
| 648 void WriteToShardStatusFileIfNeeded(); | |
| 649 | |
| 650 // Checks whether sharding is enabled by examining the relevant | |
| 651 // environment variable values. If the variables are present, | |
| 652 // but inconsistent (e.g., shard_index >= total_shards), prints | |
| 653 // an error and exits. If in_subprocess_for_death_test, sharding is | |
| 654 // disabled because it must only be applied to the original test | |
| 655 // process. Otherwise, we could filter out death tests we intended to execute. | |
| 656 GTEST_API_ bool ShouldShard(const char* total_shards_str, | |
| 657 const char* shard_index_str, | |
| 658 bool in_subprocess_for_death_test); | |
| 659 | |
| 660 // Parses the environment variable var as a 32-bit integer. If it is unset, | |
| 661 // returns default_val. If it is not a 32-bit integer, prints an error and | |
| 662 // and aborts. | |
| 663 GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val); | |
| 664 | |
| 665 // Given the total number of shards, the shard index, and the test id, | |
| 666 // returns true if and only if the test should be run on this shard. The test id | |
| 667 // is some arbitrary but unique non-negative integer assigned to each test | |
| 668 // method. Assumes that 0 <= shard_index < total_shards. | |
| 669 GTEST_API_ bool ShouldRunTestOnShard( | |
| 670 int total_shards, int shard_index, int test_id); | |
| 671 | |
| 672 // STL container utilities. | |
| 673 | |
| 674 // Returns the number of elements in the given container that satisfy | |
| 675 // the given predicate. | |
| 676 template <class Container, typename Predicate> | |
| 677 inline int CountIf(const Container& c, Predicate predicate) { | |
| 678 // Implemented as an explicit loop since std::count_if() in libCstd on | |
| 679 // Solaris has a non-standard signature. | |
| 680 int count = 0; | |
| 681 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { | |
| 682 if (predicate(*it)) | |
| 683 ++count; | |
| 684 } | |
| 685 return count; | |
| 686 } | |
| 687 | |
| 688 // Applies a function/functor to each element in the container. | |
| 689 template <class Container, typename Functor> | |
| 690 void ForEach(const Container& c, Functor functor) { | |
| 691 std::for_each(c.begin(), c.end(), functor); | |
| 692 } | |
| 693 | |
| 694 // Returns the i-th element of the vector, or default_value if i is not | |
| 695 // in range [0, v.size()). | |
| 696 template <typename E> | |
| 697 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { | |
| 698 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value | |
| 699 : v[static_cast<size_t>(i)]; | |
| 700 } | |
| 701 | |
| 702 // Performs an in-place shuffle of a range of the vector's elements. | |
| 703 // 'begin' and 'end' are element indices as an STL-style range; | |
| 704 // i.e. [begin, end) are shuffled, where 'end' == size() means to | |
| 705 // shuffle to the end of the vector. | |
| 706 template <typename E> | |
| 707 void ShuffleRange(internal::Random* random, int begin, int end, | |
| 708 std::vector<E>* v) { | |
| 709 const int size = static_cast<int>(v->size()); | |
| 710 GTEST_CHECK_(0 <= begin && begin <= size) | |
| 711 << "Invalid shuffle range start " << begin << ": must be in range [0, " | |
| 712 << size << "]."; | |
| 713 GTEST_CHECK_(begin <= end && end <= size) | |
| 714 << "Invalid shuffle range finish " << end << ": must be in range [" | |
| 715 << begin << ", " << size << "]."; | |
| 716 | |
| 717 // Fisher-Yates shuffle, from | |
| 718 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle | |
| 719 for (int range_width = end - begin; range_width >= 2; range_width--) { | |
| 720 const int last_in_range = begin + range_width - 1; | |
| 721 const int selected = | |
| 722 begin + | |
| 723 static_cast<int>(random->Generate(static_cast<uint32_t>(range_width))); | |
| 724 std::swap((*v)[static_cast<size_t>(selected)], | |
| 725 (*v)[static_cast<size_t>(last_in_range)]); | |
| 726 } | |
| 727 } | |
| 728 | |
| 729 // Performs an in-place shuffle of the vector's elements. | |
| 730 template <typename E> | |
| 731 inline void Shuffle(internal::Random* random, std::vector<E>* v) { | |
| 732 ShuffleRange(random, 0, static_cast<int>(v->size()), v); | |
| 733 } | |
| 734 | |
| 735 // A function for deleting an object. Handy for being used as a | |
| 736 // functor. | |
| 737 template <typename T> | |
| 738 static void Delete(T* x) { | |
| 739 delete x; | |
| 740 } | |
| 741 | |
| 742 // A predicate that checks the key of a TestProperty against a known key. | |
| 743 // | |
| 744 // TestPropertyKeyIs is copyable. | |
| 745 class TestPropertyKeyIs { | |
| 746 public: | |
| 747 // Constructor. | |
| 748 // | |
| 749 // TestPropertyKeyIs has NO default constructor. | |
| 750 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} | |
| 751 | |
| 752 // Returns true if and only if the test name of test property matches on key_. | |
| 753 bool operator()(const TestProperty& test_property) const { | |
| 754 return test_property.key() == key_; | |
| 755 } | |
| 756 | |
| 757 private: | |
| 758 std::string key_; | |
| 759 }; | |
| 760 | |
| 761 // Class UnitTestOptions. | |
| 762 // | |
| 763 // This class contains functions for processing options the user | |
| 764 // specifies when running the tests. It has only static members. | |
| 765 // | |
| 766 // In most cases, the user can specify an option using either an | |
| 767 // environment variable or a command line flag. E.g. you can set the | |
| 768 // test filter using either GTEST_FILTER or --gtest_filter. If both | |
| 769 // the variable and the flag are present, the latter overrides the | |
| 770 // former. | |
| 771 class GTEST_API_ UnitTestOptions { | |
| 772 public: | |
| 773 // Functions for processing the gtest_output flag. | |
| 774 | |
| 775 // Returns the output format, or "" for normal printed output. | |
| 776 static std::string GetOutputFormat(); | |
| 777 | |
| 778 // Returns the absolute path of the requested output file, or the | |
| 779 // default (test_detail.xml in the original working directory) if | |
| 780 // none was explicitly specified. | |
| 781 static std::string GetAbsolutePathToOutputFile(); | |
| 782 | |
| 783 // Functions for processing the gtest_filter flag. | |
| 784 | |
| 785 // Returns true if and only if the user-specified filter matches the test | |
| 786 // suite name and the test name. | |
| 787 static bool FilterMatchesTest(const std::string& test_suite_name, | |
| 788 const std::string& test_name); | |
| 789 | |
| 790 #if GTEST_OS_WINDOWS | |
| 791 // Function for supporting the gtest_catch_exception flag. | |
| 792 | |
| 793 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the | |
| 794 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. | |
| 795 // This function is useful as an __except condition. | |
| 796 static int GTestShouldProcessSEH(DWORD exception_code); | |
| 797 #endif // GTEST_OS_WINDOWS | |
| 798 | |
| 799 // Returns true if "name" matches the ':' separated list of glob-style | |
| 800 // filters in "filter". | |
| 801 static bool MatchesFilter(const std::string& name, const char* filter); | |
| 802 }; | |
| 803 | |
| 804 // Returns the current application's name, removing directory path if that | |
| 805 // is present. Used by UnitTestOptions::GetOutputFile. | |
| 806 GTEST_API_ FilePath GetCurrentExecutableName(); | |
| 807 | |
| 808 // The role interface for getting the OS stack trace as a string. | |
| 809 class OsStackTraceGetterInterface { | |
| 810 public: | |
| 811 OsStackTraceGetterInterface() {} | |
| 812 virtual ~OsStackTraceGetterInterface() {} | |
| 813 | |
| 814 // Returns the current OS stack trace as an std::string. Parameters: | |
| 815 // | |
| 816 // max_depth - the maximum number of stack frames to be included | |
| 817 // in the trace. | |
| 818 // skip_count - the number of top frames to be skipped; doesn't count | |
| 819 // against max_depth. | |
| 820 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0; | |
| 821 | |
| 822 // UponLeavingGTest() should be called immediately before Google Test calls | |
| 823 // user code. It saves some information about the current stack that | |
| 824 // CurrentStackTrace() will use to find and hide Google Test stack frames. | |
| 825 virtual void UponLeavingGTest() = 0; | |
| 826 | |
| 827 // This string is inserted in place of stack frames that are part of | |
| 828 // Google Test's implementation. | |
| 829 static const char* const kElidedFramesMarker; | |
| 830 | |
| 831 private: | |
| 832 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); | |
| 833 }; | |
| 834 | |
| 835 // A working implementation of the OsStackTraceGetterInterface interface. | |
| 836 class OsStackTraceGetter : public OsStackTraceGetterInterface { | |
| 837 public: | |
| 838 OsStackTraceGetter() {} | |
| 839 | |
| 840 std::string CurrentStackTrace(int max_depth, int skip_count) override; | |
| 841 void UponLeavingGTest() override; | |
| 842 | |
| 843 private: | |
| 844 #if GTEST_HAS_ABSL | |
| 845 Mutex mutex_; // Protects all internal state. | |
| 846 | |
| 847 // We save the stack frame below the frame that calls user code. | |
| 848 // We do this because the address of the frame immediately below | |
| 849 // the user code changes between the call to UponLeavingGTest() | |
| 850 // and any calls to the stack trace code from within the user code. | |
| 851 void* caller_frame_ = nullptr; | |
| 852 #endif // GTEST_HAS_ABSL | |
| 853 | |
| 854 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); | |
| 855 }; | |
| 856 | |
| 857 // Information about a Google Test trace point. | |
| 858 struct TraceInfo { | |
| 859 const char* file; | |
| 860 int line; | |
| 861 std::string message; | |
| 862 }; | |
| 863 | |
| 864 // This is the default global test part result reporter used in UnitTestImpl. | |
| 865 // This class should only be used by UnitTestImpl. | |
| 866 class DefaultGlobalTestPartResultReporter | |
| 867 : public TestPartResultReporterInterface { | |
| 868 public: | |
| 869 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); | |
| 870 // Implements the TestPartResultReporterInterface. Reports the test part | |
| 871 // result in the current test. | |
| 872 void ReportTestPartResult(const TestPartResult& result) override; | |
| 873 | |
| 874 private: | |
| 875 UnitTestImpl* const unit_test_; | |
| 876 | |
| 877 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); | |
| 878 }; | |
| 879 | |
| 880 // This is the default per thread test part result reporter used in | |
| 881 // UnitTestImpl. This class should only be used by UnitTestImpl. | |
| 882 class DefaultPerThreadTestPartResultReporter | |
| 883 : public TestPartResultReporterInterface { | |
| 884 public: | |
| 885 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); | |
| 886 // Implements the TestPartResultReporterInterface. The implementation just | |
| 887 // delegates to the current global test part result reporter of *unit_test_. | |
| 888 void ReportTestPartResult(const TestPartResult& result) override; | |
| 889 | |
| 890 private: | |
| 891 UnitTestImpl* const unit_test_; | |
| 892 | |
| 893 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); | |
| 894 }; | |
| 895 | |
| 896 // The private implementation of the UnitTest class. We don't protect | |
| 897 // the methods under a mutex, as this class is not accessible by a | |
| 898 // user and the UnitTest class that delegates work to this class does | |
| 899 // proper locking. | |
| 900 class GTEST_API_ UnitTestImpl { | |
| 901 public: | |
| 902 explicit UnitTestImpl(UnitTest* parent); | |
| 903 virtual ~UnitTestImpl(); | |
| 904 | |
| 905 // There are two different ways to register your own TestPartResultReporter. | |
| 906 // You can register your own repoter to listen either only for test results | |
| 907 // from the current thread or for results from all threads. | |
| 908 // By default, each per-thread test result repoter just passes a new | |
| 909 // TestPartResult to the global test result reporter, which registers the | |
| 910 // test part result for the currently running test. | |
| 911 | |
| 912 // Returns the global test part result reporter. | |
| 913 TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); | |
| 914 | |
| 915 // Sets the global test part result reporter. | |
| 916 void SetGlobalTestPartResultReporter( | |
| 917 TestPartResultReporterInterface* reporter); | |
| 918 | |
| 919 // Returns the test part result reporter for the current thread. | |
| 920 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); | |
| 921 | |
| 922 // Sets the test part result reporter for the current thread. | |
| 923 void SetTestPartResultReporterForCurrentThread( | |
| 924 TestPartResultReporterInterface* reporter); | |
| 925 | |
| 926 // Gets the number of successful test suites. | |
| 927 int successful_test_suite_count() const; | |
| 928 | |
| 929 // Gets the number of failed test suites. | |
| 930 int failed_test_suite_count() const; | |
| 931 | |
| 932 // Gets the number of all test suites. | |
| 933 int total_test_suite_count() const; | |
| 934 | |
| 935 // Gets the number of all test suites that contain at least one test | |
| 936 // that should run. | |
| 937 int test_suite_to_run_count() const; | |
| 938 | |
| 939 // Gets the number of successful tests. | |
| 940 int successful_test_count() const; | |
| 941 | |
| 942 // Gets the number of skipped tests. | |
| 943 int skipped_test_count() const; | |
| 944 | |
| 945 // Gets the number of failed tests. | |
| 946 int failed_test_count() const; | |
| 947 | |
| 948 // Gets the number of disabled tests that will be reported in the XML report. | |
| 949 int reportable_disabled_test_count() const; | |
| 950 | |
| 951 // Gets the number of disabled tests. | |
| 952 int disabled_test_count() const; | |
| 953 | |
| 954 // Gets the number of tests to be printed in the XML report. | |
| 955 int reportable_test_count() const; | |
| 956 | |
| 957 // Gets the number of all tests. | |
| 958 int total_test_count() const; | |
| 959 | |
| 960 // Gets the number of tests that should run. | |
| 961 int test_to_run_count() const; | |
| 962 | |
| 963 // Gets the time of the test program start, in ms from the start of the | |
| 964 // UNIX epoch. | |
| 965 TimeInMillis start_timestamp() const { return start_timestamp_; } | |
| 966 | |
| 967 // Gets the elapsed time, in milliseconds. | |
| 968 TimeInMillis elapsed_time() const { return elapsed_time_; } | |
| 969 | |
| 970 // Returns true if and only if the unit test passed (i.e. all test suites | |
| 971 // passed). | |
| 972 bool Passed() const { return !Failed(); } | |
| 973 | |
| 974 // Returns true if and only if the unit test failed (i.e. some test suite | |
| 975 // failed or something outside of all tests failed). | |
| 976 bool Failed() const { | |
| 977 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed(); | |
| 978 } | |
| 979 | |
| 980 // Gets the i-th test suite among all the test suites. i can range from 0 to | |
| 981 // total_test_suite_count() - 1. If i is not in that range, returns NULL. | |
| 982 const TestSuite* GetTestSuite(int i) const { | |
| 983 const int index = GetElementOr(test_suite_indices_, i, -1); | |
| 984 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)]; | |
| 985 } | |
| 986 | |
| 987 // Legacy API is deprecated but still available | |
| 988 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 989 const TestCase* GetTestCase(int i) const { return GetTestSuite(i); } | |
| 990 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 991 | |
| 992 // Gets the i-th test suite among all the test suites. i can range from 0 to | |
| 993 // total_test_suite_count() - 1. If i is not in that range, returns NULL. | |
| 994 TestSuite* GetMutableSuiteCase(int i) { | |
| 995 const int index = GetElementOr(test_suite_indices_, i, -1); | |
| 996 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)]; | |
| 997 } | |
| 998 | |
| 999 // Provides access to the event listener list. | |
| 1000 TestEventListeners* listeners() { return &listeners_; } | |
| 1001 | |
| 1002 // Returns the TestResult for the test that's currently running, or | |
| 1003 // the TestResult for the ad hoc test if no test is running. | |
| 1004 TestResult* current_test_result(); | |
| 1005 | |
| 1006 // Returns the TestResult for the ad hoc test. | |
| 1007 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } | |
| 1008 | |
| 1009 // Sets the OS stack trace getter. | |
| 1010 // | |
| 1011 // Does nothing if the input and the current OS stack trace getter | |
| 1012 // are the same; otherwise, deletes the old getter and makes the | |
| 1013 // input the current getter. | |
| 1014 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); | |
| 1015 | |
| 1016 // Returns the current OS stack trace getter if it is not NULL; | |
| 1017 // otherwise, creates an OsStackTraceGetter, makes it the current | |
| 1018 // getter, and returns it. | |
| 1019 OsStackTraceGetterInterface* os_stack_trace_getter(); | |
| 1020 | |
| 1021 // Returns the current OS stack trace as an std::string. | |
| 1022 // | |
| 1023 // The maximum number of stack frames to be included is specified by | |
| 1024 // the gtest_stack_trace_depth flag. The skip_count parameter | |
| 1025 // specifies the number of top frames to be skipped, which doesn't | |
| 1026 // count against the number of frames to be included. | |
| 1027 // | |
| 1028 // For example, if Foo() calls Bar(), which in turn calls | |
| 1029 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the | |
| 1030 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. | |
| 1031 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; | |
| 1032 | |
| 1033 // Finds and returns a TestSuite with the given name. If one doesn't | |
| 1034 // exist, creates one and returns it. | |
| 1035 // | |
| 1036 // Arguments: | |
| 1037 // | |
| 1038 // test_suite_name: name of the test suite | |
| 1039 // type_param: the name of the test's type parameter, or NULL if | |
| 1040 // this is not a typed or a type-parameterized test. | |
| 1041 // set_up_tc: pointer to the function that sets up the test suite | |
| 1042 // tear_down_tc: pointer to the function that tears down the test suite | |
| 1043 TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param, | |
| 1044 internal::SetUpTestSuiteFunc set_up_tc, | |
| 1045 internal::TearDownTestSuiteFunc tear_down_tc); | |
| 1046 | |
| 1047 // Legacy API is deprecated but still available | |
| 1048 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 1049 TestCase* GetTestCase(const char* test_case_name, const char* type_param, | |
| 1050 internal::SetUpTestSuiteFunc set_up_tc, | |
| 1051 internal::TearDownTestSuiteFunc tear_down_tc) { | |
| 1052 return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); | |
| 1053 } | |
| 1054 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 1055 | |
| 1056 // Adds a TestInfo to the unit test. | |
| 1057 // | |
| 1058 // Arguments: | |
| 1059 // | |
| 1060 // set_up_tc: pointer to the function that sets up the test suite | |
| 1061 // tear_down_tc: pointer to the function that tears down the test suite | |
| 1062 // test_info: the TestInfo object | |
| 1063 void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, | |
| 1064 internal::TearDownTestSuiteFunc tear_down_tc, | |
| 1065 TestInfo* test_info) { | |
| 1066 #if GTEST_HAS_DEATH_TEST | |
| 1067 // In order to support thread-safe death tests, we need to | |
| 1068 // remember the original working directory when the test program | |
| 1069 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as | |
| 1070 // the user may have changed the current directory before calling | |
| 1071 // RUN_ALL_TESTS(). Therefore we capture the current directory in | |
| 1072 // AddTestInfo(), which is called to register a TEST or TEST_F | |
| 1073 // before main() is reached. | |
| 1074 if (original_working_dir_.IsEmpty()) { | |
| 1075 original_working_dir_.Set(FilePath::GetCurrentDir()); | |
| 1076 GTEST_CHECK_(!original_working_dir_.IsEmpty()) | |
| 1077 << "Failed to get the current working directory."; | |
| 1078 } | |
| 1079 #endif // GTEST_HAS_DEATH_TEST | |
| 1080 | |
| 1081 GetTestSuite(test_info->test_suite_name(), test_info->type_param(), | |
| 1082 set_up_tc, tear_down_tc) | |
| 1083 ->AddTestInfo(test_info); | |
| 1084 } | |
| 1085 | |
| 1086 // Returns ParameterizedTestSuiteRegistry object used to keep track of | |
| 1087 // value-parameterized tests and instantiate and register them. | |
| 1088 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() { | |
| 1089 return parameterized_test_registry_; | |
| 1090 } | |
| 1091 | |
| 1092 std::set<std::string>* ignored_parameterized_test_suites() { | |
| 1093 return &ignored_parameterized_test_suites_; | |
| 1094 } | |
| 1095 | |
| 1096 // Returns TypeParameterizedTestSuiteRegistry object used to keep track of | |
| 1097 // type-parameterized tests and instantiations of them. | |
| 1098 internal::TypeParameterizedTestSuiteRegistry& | |
| 1099 type_parameterized_test_registry() { | |
| 1100 return type_parameterized_test_registry_; | |
| 1101 } | |
| 1102 | |
| 1103 // Sets the TestSuite object for the test that's currently running. | |
| 1104 void set_current_test_suite(TestSuite* a_current_test_suite) { | |
| 1105 current_test_suite_ = a_current_test_suite; | |
| 1106 } | |
| 1107 | |
| 1108 // Sets the TestInfo object for the test that's currently running. If | |
| 1109 // current_test_info is NULL, the assertion results will be stored in | |
| 1110 // ad_hoc_test_result_. | |
| 1111 void set_current_test_info(TestInfo* a_current_test_info) { | |
| 1112 current_test_info_ = a_current_test_info; | |
| 1113 } | |
| 1114 | |
| 1115 // Registers all parameterized tests defined using TEST_P and | |
| 1116 // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter | |
| 1117 // combination. This method can be called more then once; it has guards | |
| 1118 // protecting from registering the tests more then once. If | |
| 1119 // value-parameterized tests are disabled, RegisterParameterizedTests is | |
| 1120 // present but does nothing. | |
| 1121 void RegisterParameterizedTests(); | |
| 1122 | |
| 1123 // Runs all tests in this UnitTest object, prints the result, and | |
| 1124 // returns true if all tests are successful. If any exception is | |
| 1125 // thrown during a test, this test is considered to be failed, but | |
| 1126 // the rest of the tests will still be run. | |
| 1127 bool RunAllTests(); | |
| 1128 | |
| 1129 // Clears the results of all tests, except the ad hoc tests. | |
| 1130 void ClearNonAdHocTestResult() { | |
| 1131 ForEach(test_suites_, TestSuite::ClearTestSuiteResult); | |
| 1132 } | |
| 1133 | |
| 1134 // Clears the results of ad-hoc test assertions. | |
| 1135 void ClearAdHocTestResult() { | |
| 1136 ad_hoc_test_result_.Clear(); | |
| 1137 } | |
| 1138 | |
| 1139 // Adds a TestProperty to the current TestResult object when invoked in a | |
| 1140 // context of a test or a test suite, or to the global property set. If the | |
| 1141 // result already contains a property with the same key, the value will be | |
| 1142 // updated. | |
| 1143 void RecordProperty(const TestProperty& test_property); | |
| 1144 | |
| 1145 enum ReactionToSharding { | |
| 1146 HONOR_SHARDING_PROTOCOL, | |
| 1147 IGNORE_SHARDING_PROTOCOL | |
| 1148 }; | |
| 1149 | |
| 1150 // Matches the full name of each test against the user-specified | |
| 1151 // filter to decide whether the test should run, then records the | |
| 1152 // result in each TestSuite and TestInfo object. | |
| 1153 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests | |
| 1154 // based on sharding variables in the environment. | |
| 1155 // Returns the number of tests that should run. | |
| 1156 int FilterTests(ReactionToSharding shard_tests); | |
| 1157 | |
| 1158 // Prints the names of the tests matching the user-specified filter flag. | |
| 1159 void ListTestsMatchingFilter(); | |
| 1160 | |
| 1161 const TestSuite* current_test_suite() const { return current_test_suite_; } | |
| 1162 TestInfo* current_test_info() { return current_test_info_; } | |
| 1163 const TestInfo* current_test_info() const { return current_test_info_; } | |
| 1164 | |
| 1165 // Returns the vector of environments that need to be set-up/torn-down | |
| 1166 // before/after the tests are run. | |
| 1167 std::vector<Environment*>& environments() { return environments_; } | |
| 1168 | |
| 1169 // Getters for the per-thread Google Test trace stack. | |
| 1170 std::vector<TraceInfo>& gtest_trace_stack() { | |
| 1171 return *(gtest_trace_stack_.pointer()); | |
| 1172 } | |
| 1173 const std::vector<TraceInfo>& gtest_trace_stack() const { | |
| 1174 return gtest_trace_stack_.get(); | |
| 1175 } | |
| 1176 | |
| 1177 #if GTEST_HAS_DEATH_TEST | |
| 1178 void InitDeathTestSubprocessControlInfo() { | |
| 1179 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); | |
| 1180 } | |
| 1181 // Returns a pointer to the parsed --gtest_internal_run_death_test | |
| 1182 // flag, or NULL if that flag was not specified. | |
| 1183 // This information is useful only in a death test child process. | |
| 1184 // Must not be called before a call to InitGoogleTest. | |
| 1185 const InternalRunDeathTestFlag* internal_run_death_test_flag() const { | |
| 1186 return internal_run_death_test_flag_.get(); | |
| 1187 } | |
| 1188 | |
| 1189 // Returns a pointer to the current death test factory. | |
| 1190 internal::DeathTestFactory* death_test_factory() { | |
| 1191 return death_test_factory_.get(); | |
| 1192 } | |
| 1193 | |
| 1194 void SuppressTestEventsIfInSubprocess(); | |
| 1195 | |
| 1196 friend class ReplaceDeathTestFactory; | |
| 1197 #endif // GTEST_HAS_DEATH_TEST | |
| 1198 | |
| 1199 // Initializes the event listener performing XML output as specified by | |
| 1200 // UnitTestOptions. Must not be called before InitGoogleTest. | |
| 1201 void ConfigureXmlOutput(); | |
| 1202 | |
| 1203 #if GTEST_CAN_STREAM_RESULTS_ | |
| 1204 // Initializes the event listener for streaming test results to a socket. | |
| 1205 // Must not be called before InitGoogleTest. | |
| 1206 void ConfigureStreamingOutput(); | |
| 1207 #endif | |
| 1208 | |
| 1209 // Performs initialization dependent upon flag values obtained in | |
| 1210 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to | |
| 1211 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest | |
| 1212 // this function is also called from RunAllTests. Since this function can be | |
| 1213 // called more than once, it has to be idempotent. | |
| 1214 void PostFlagParsingInit(); | |
| 1215 | |
| 1216 // Gets the random seed used at the start of the current test iteration. | |
| 1217 int random_seed() const { return random_seed_; } | |
| 1218 | |
| 1219 // Gets the random number generator. | |
| 1220 internal::Random* random() { return &random_; } | |
| 1221 | |
| 1222 // Shuffles all test suites, and the tests within each test suite, | |
| 1223 // making sure that death tests are still run first. | |
| 1224 void ShuffleTests(); | |
| 1225 | |
| 1226 // Restores the test suites and tests to their order before the first shuffle. | |
| 1227 void UnshuffleTests(); | |
| 1228 | |
| 1229 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment | |
| 1230 // UnitTest::Run() starts. | |
| 1231 bool catch_exceptions() const { return catch_exceptions_; } | |
| 1232 | |
| 1233 private: | |
| 1234 friend class ::testing::UnitTest; | |
| 1235 | |
| 1236 // Used by UnitTest::Run() to capture the state of | |
| 1237 // GTEST_FLAG(catch_exceptions) at the moment it starts. | |
| 1238 void set_catch_exceptions(bool value) { catch_exceptions_ = value; } | |
| 1239 | |
| 1240 // The UnitTest object that owns this implementation object. | |
| 1241 UnitTest* const parent_; | |
| 1242 | |
| 1243 // The working directory when the first TEST() or TEST_F() was | |
| 1244 // executed. | |
| 1245 internal::FilePath original_working_dir_; | |
| 1246 | |
| 1247 // The default test part result reporters. | |
| 1248 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; | |
| 1249 DefaultPerThreadTestPartResultReporter | |
| 1250 default_per_thread_test_part_result_reporter_; | |
| 1251 | |
| 1252 // Points to (but doesn't own) the global test part result reporter. | |
| 1253 TestPartResultReporterInterface* global_test_part_result_repoter_; | |
| 1254 | |
| 1255 // Protects read and write access to global_test_part_result_reporter_. | |
| 1256 internal::Mutex global_test_part_result_reporter_mutex_; | |
| 1257 | |
| 1258 // Points to (but doesn't own) the per-thread test part result reporter. | |
| 1259 internal::ThreadLocal<TestPartResultReporterInterface*> | |
| 1260 per_thread_test_part_result_reporter_; | |
| 1261 | |
| 1262 // The vector of environments that need to be set-up/torn-down | |
| 1263 // before/after the tests are run. | |
| 1264 std::vector<Environment*> environments_; | |
| 1265 | |
| 1266 // The vector of TestSuites in their original order. It owns the | |
| 1267 // elements in the vector. | |
| 1268 std::vector<TestSuite*> test_suites_; | |
| 1269 | |
| 1270 // Provides a level of indirection for the test suite list to allow | |
| 1271 // easy shuffling and restoring the test suite order. The i-th | |
| 1272 // element of this vector is the index of the i-th test suite in the | |
| 1273 // shuffled order. | |
| 1274 std::vector<int> test_suite_indices_; | |
| 1275 | |
| 1276 // ParameterizedTestRegistry object used to register value-parameterized | |
| 1277 // tests. | |
| 1278 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; | |
| 1279 internal::TypeParameterizedTestSuiteRegistry | |
| 1280 type_parameterized_test_registry_; | |
| 1281 | |
| 1282 // The set holding the name of parameterized | |
| 1283 // test suites that may go uninstantiated. | |
| 1284 std::set<std::string> ignored_parameterized_test_suites_; | |
| 1285 | |
| 1286 // Indicates whether RegisterParameterizedTests() has been called already. | |
| 1287 bool parameterized_tests_registered_; | |
| 1288 | |
| 1289 // Index of the last death test suite registered. Initially -1. | |
| 1290 int last_death_test_suite_; | |
| 1291 | |
| 1292 // This points to the TestSuite for the currently running test. It | |
| 1293 // changes as Google Test goes through one test suite after another. | |
| 1294 // When no test is running, this is set to NULL and Google Test | |
| 1295 // stores assertion results in ad_hoc_test_result_. Initially NULL. | |
| 1296 TestSuite* current_test_suite_; | |
| 1297 | |
| 1298 // This points to the TestInfo for the currently running test. It | |
| 1299 // changes as Google Test goes through one test after another. When | |
| 1300 // no test is running, this is set to NULL and Google Test stores | |
| 1301 // assertion results in ad_hoc_test_result_. Initially NULL. | |
| 1302 TestInfo* current_test_info_; | |
| 1303 | |
| 1304 // Normally, a user only writes assertions inside a TEST or TEST_F, | |
| 1305 // or inside a function called by a TEST or TEST_F. Since Google | |
| 1306 // Test keeps track of which test is current running, it can | |
| 1307 // associate such an assertion with the test it belongs to. | |
| 1308 // | |
| 1309 // If an assertion is encountered when no TEST or TEST_F is running, | |
| 1310 // Google Test attributes the assertion result to an imaginary "ad hoc" | |
| 1311 // test, and records the result in ad_hoc_test_result_. | |
| 1312 TestResult ad_hoc_test_result_; | |
| 1313 | |
| 1314 // The list of event listeners that can be used to track events inside | |
| 1315 // Google Test. | |
| 1316 TestEventListeners listeners_; | |
| 1317 | |
| 1318 // The OS stack trace getter. Will be deleted when the UnitTest | |
| 1319 // object is destructed. By default, an OsStackTraceGetter is used, | |
| 1320 // but the user can set this field to use a custom getter if that is | |
| 1321 // desired. | |
| 1322 OsStackTraceGetterInterface* os_stack_trace_getter_; | |
| 1323 | |
| 1324 // True if and only if PostFlagParsingInit() has been called. | |
| 1325 bool post_flag_parse_init_performed_; | |
| 1326 | |
| 1327 // The random number seed used at the beginning of the test run. | |
| 1328 int random_seed_; | |
| 1329 | |
| 1330 // Our random number generator. | |
| 1331 internal::Random random_; | |
| 1332 | |
| 1333 // The time of the test program start, in ms from the start of the | |
| 1334 // UNIX epoch. | |
| 1335 TimeInMillis start_timestamp_; | |
| 1336 | |
| 1337 // How long the test took to run, in milliseconds. | |
| 1338 TimeInMillis elapsed_time_; | |
| 1339 | |
| 1340 #if GTEST_HAS_DEATH_TEST | |
| 1341 // The decomposed components of the gtest_internal_run_death_test flag, | |
| 1342 // parsed when RUN_ALL_TESTS is called. | |
| 1343 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; | |
| 1344 std::unique_ptr<internal::DeathTestFactory> death_test_factory_; | |
| 1345 #endif // GTEST_HAS_DEATH_TEST | |
| 1346 | |
| 1347 // A per-thread stack of traces created by the SCOPED_TRACE() macro. | |
| 1348 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; | |
| 1349 | |
| 1350 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() | |
| 1351 // starts. | |
| 1352 bool catch_exceptions_; | |
| 1353 | |
| 1354 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); | |
| 1355 }; // class UnitTestImpl | |
| 1356 | |
| 1357 // Convenience function for accessing the global UnitTest | |
| 1358 // implementation object. | |
| 1359 inline UnitTestImpl* GetUnitTestImpl() { | |
| 1360 return UnitTest::GetInstance()->impl(); | |
| 1361 } | |
| 1362 | |
| 1363 #if GTEST_USES_SIMPLE_RE | |
| 1364 | |
| 1365 // Internal helper functions for implementing the simple regular | |
| 1366 // expression matcher. | |
| 1367 GTEST_API_ bool IsInSet(char ch, const char* str); | |
| 1368 GTEST_API_ bool IsAsciiDigit(char ch); | |
| 1369 GTEST_API_ bool IsAsciiPunct(char ch); | |
| 1370 GTEST_API_ bool IsRepeat(char ch); | |
| 1371 GTEST_API_ bool IsAsciiWhiteSpace(char ch); | |
| 1372 GTEST_API_ bool IsAsciiWordChar(char ch); | |
| 1373 GTEST_API_ bool IsValidEscape(char ch); | |
| 1374 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); | |
| 1375 GTEST_API_ bool ValidateRegex(const char* regex); | |
| 1376 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); | |
| 1377 GTEST_API_ bool MatchRepetitionAndRegexAtHead( | |
| 1378 bool escaped, char ch, char repeat, const char* regex, const char* str); | |
| 1379 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); | |
| 1380 | |
| 1381 #endif // GTEST_USES_SIMPLE_RE | |
| 1382 | |
| 1383 // Parses the command line for Google Test flags, without initializing | |
| 1384 // other parts of Google Test. | |
| 1385 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); | |
| 1386 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); | |
| 1387 | |
| 1388 #if GTEST_HAS_DEATH_TEST | |
| 1389 | |
| 1390 // Returns the message describing the last system error, regardless of the | |
| 1391 // platform. | |
| 1392 GTEST_API_ std::string GetLastErrnoDescription(); | |
| 1393 | |
| 1394 // Attempts to parse a string into a positive integer pointed to by the | |
| 1395 // number parameter. Returns true if that is possible. | |
| 1396 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use | |
| 1397 // it here. | |
| 1398 template <typename Integer> | |
| 1399 bool ParseNaturalNumber(const ::std::string& str, Integer* number) { | |
| 1400 // Fail fast if the given string does not begin with a digit; | |
| 1401 // this bypasses strtoXXX's "optional leading whitespace and plus | |
| 1402 // or minus sign" semantics, which are undesirable here. | |
| 1403 if (str.empty() || !IsDigit(str[0])) { | |
| 1404 return false; | |
| 1405 } | |
| 1406 errno = 0; | |
| 1407 | |
| 1408 char* end; | |
| 1409 // BiggestConvertible is the largest integer type that system-provided | |
| 1410 // string-to-number conversion routines can return. | |
| 1411 using BiggestConvertible = unsigned long long; // NOLINT | |
| 1412 | |
| 1413 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT | |
| 1414 const bool parse_success = *end == '\0' && errno == 0; | |
| 1415 | |
| 1416 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); | |
| 1417 | |
| 1418 const Integer result = static_cast<Integer>(parsed); | |
| 1419 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { | |
| 1420 *number = result; | |
| 1421 return true; | |
| 1422 } | |
| 1423 return false; | |
| 1424 } | |
| 1425 #endif // GTEST_HAS_DEATH_TEST | |
| 1426 | |
| 1427 // TestResult contains some private methods that should be hidden from | |
| 1428 // Google Test user but are required for testing. This class allow our tests | |
| 1429 // to access them. | |
| 1430 // | |
| 1431 // This class is supplied only for the purpose of testing Google Test's own | |
| 1432 // constructs. Do not use it in user tests, either directly or indirectly. | |
| 1433 class TestResultAccessor { | |
| 1434 public: | |
| 1435 static void RecordProperty(TestResult* test_result, | |
| 1436 const std::string& xml_element, | |
| 1437 const TestProperty& property) { | |
| 1438 test_result->RecordProperty(xml_element, property); | |
| 1439 } | |
| 1440 | |
| 1441 static void ClearTestPartResults(TestResult* test_result) { | |
| 1442 test_result->ClearTestPartResults(); | |
| 1443 } | |
| 1444 | |
| 1445 static const std::vector<testing::TestPartResult>& test_part_results( | |
| 1446 const TestResult& test_result) { | |
| 1447 return test_result.test_part_results(); | |
| 1448 } | |
| 1449 }; | |
| 1450 | |
| 1451 #if GTEST_CAN_STREAM_RESULTS_ | |
| 1452 | |
| 1453 // Streams test results to the given port on the given host machine. | |
| 1454 class StreamingListener : public EmptyTestEventListener { | |
| 1455 public: | |
| 1456 // Abstract base class for writing strings to a socket. | |
| 1457 class AbstractSocketWriter { | |
| 1458 public: | |
| 1459 virtual ~AbstractSocketWriter() {} | |
| 1460 | |
| 1461 // Sends a string to the socket. | |
| 1462 virtual void Send(const std::string& message) = 0; | |
| 1463 | |
| 1464 // Closes the socket. | |
| 1465 virtual void CloseConnection() {} | |
| 1466 | |
| 1467 // Sends a string and a newline to the socket. | |
| 1468 void SendLn(const std::string& message) { Send(message + "\n"); } | |
| 1469 }; | |
| 1470 | |
| 1471 // Concrete class for actually writing strings to a socket. | |
| 1472 class SocketWriter : public AbstractSocketWriter { | |
| 1473 public: | |
| 1474 SocketWriter(const std::string& host, const std::string& port) | |
| 1475 : sockfd_(-1), host_name_(host), port_num_(port) { | |
| 1476 MakeConnection(); | |
| 1477 } | |
| 1478 | |
| 1479 ~SocketWriter() override { | |
| 1480 if (sockfd_ != -1) | |
| 1481 CloseConnection(); | |
| 1482 } | |
| 1483 | |
| 1484 // Sends a string to the socket. | |
| 1485 void Send(const std::string& message) override { | |
| 1486 GTEST_CHECK_(sockfd_ != -1) | |
| 1487 << "Send() can be called only when there is a connection."; | |
| 1488 | |
| 1489 const auto len = static_cast<size_t>(message.length()); | |
| 1490 if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) { | |
| 1491 GTEST_LOG_(WARNING) | |
| 1492 << "stream_result_to: failed to stream to " | |
| 1493 << host_name_ << ":" << port_num_; | |
| 1494 } | |
| 1495 } | |
| 1496 | |
| 1497 private: | |
| 1498 // Creates a client socket and connects to the server. | |
| 1499 void MakeConnection(); | |
| 1500 | |
| 1501 // Closes the socket. | |
| 1502 void CloseConnection() override { | |
| 1503 GTEST_CHECK_(sockfd_ != -1) | |
| 1504 << "CloseConnection() can be called only when there is a connection."; | |
| 1505 | |
| 1506 close(sockfd_); | |
| 1507 sockfd_ = -1; | |
| 1508 } | |
| 1509 | |
| 1510 int sockfd_; // socket file descriptor | |
| 1511 const std::string host_name_; | |
| 1512 const std::string port_num_; | |
| 1513 | |
| 1514 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); | |
| 1515 }; // class SocketWriter | |
| 1516 | |
| 1517 // Escapes '=', '&', '%', and '\n' characters in str as "%xx". | |
| 1518 static std::string UrlEncode(const char* str); | |
| 1519 | |
| 1520 StreamingListener(const std::string& host, const std::string& port) | |
| 1521 : socket_writer_(new SocketWriter(host, port)) { | |
| 1522 Start(); | |
| 1523 } | |
| 1524 | |
| 1525 explicit StreamingListener(AbstractSocketWriter* socket_writer) | |
| 1526 : socket_writer_(socket_writer) { Start(); } | |
| 1527 | |
| 1528 void OnTestProgramStart(const UnitTest& /* unit_test */) override { | |
| 1529 SendLn("event=TestProgramStart"); | |
| 1530 } | |
| 1531 | |
| 1532 void OnTestProgramEnd(const UnitTest& unit_test) override { | |
| 1533 // Note that Google Test current only report elapsed time for each | |
| 1534 // test iteration, not for the entire test program. | |
| 1535 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); | |
| 1536 | |
| 1537 // Notify the streaming server to stop. | |
| 1538 socket_writer_->CloseConnection(); | |
| 1539 } | |
| 1540 | |
| 1541 void OnTestIterationStart(const UnitTest& /* unit_test */, | |
| 1542 int iteration) override { | |
| 1543 SendLn("event=TestIterationStart&iteration=" + | |
| 1544 StreamableToString(iteration)); | |
| 1545 } | |
| 1546 | |
| 1547 void OnTestIterationEnd(const UnitTest& unit_test, | |
| 1548 int /* iteration */) override { | |
| 1549 SendLn("event=TestIterationEnd&passed=" + | |
| 1550 FormatBool(unit_test.Passed()) + "&elapsed_time=" + | |
| 1551 StreamableToString(unit_test.elapsed_time()) + "ms"); | |
| 1552 } | |
| 1553 | |
| 1554 // Note that "event=TestCaseStart" is a wire format and has to remain | |
| 1555 // "case" for compatibility | |
| 1556 void OnTestCaseStart(const TestCase& test_case) override { | |
| 1557 SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); | |
| 1558 } | |
| 1559 | |
| 1560 // Note that "event=TestCaseEnd" is a wire format and has to remain | |
| 1561 // "case" for compatibility | |
| 1562 void OnTestCaseEnd(const TestCase& test_case) override { | |
| 1563 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + | |
| 1564 "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + | |
| 1565 "ms"); | |
| 1566 } | |
| 1567 | |
| 1568 void OnTestStart(const TestInfo& test_info) override { | |
| 1569 SendLn(std::string("event=TestStart&name=") + test_info.name()); | |
| 1570 } | |
| 1571 | |
| 1572 void OnTestEnd(const TestInfo& test_info) override { | |
| 1573 SendLn("event=TestEnd&passed=" + | |
| 1574 FormatBool((test_info.result())->Passed()) + | |
| 1575 "&elapsed_time=" + | |
| 1576 StreamableToString((test_info.result())->elapsed_time()) + "ms"); | |
| 1577 } | |
| 1578 | |
| 1579 void OnTestPartResult(const TestPartResult& test_part_result) override { | |
| 1580 const char* file_name = test_part_result.file_name(); | |
| 1581 if (file_name == nullptr) file_name = ""; | |
| 1582 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + | |
| 1583 "&line=" + StreamableToString(test_part_result.line_number()) + | |
| 1584 "&message=" + UrlEncode(test_part_result.message())); | |
| 1585 } | |
| 1586 | |
| 1587 private: | |
| 1588 // Sends the given message and a newline to the socket. | |
| 1589 void SendLn(const std::string& message) { socket_writer_->SendLn(message); } | |
| 1590 | |
| 1591 // Called at the start of streaming to notify the receiver what | |
| 1592 // protocol we are using. | |
| 1593 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } | |
| 1594 | |
| 1595 std::string FormatBool(bool value) { return value ? "1" : "0"; } | |
| 1596 | |
| 1597 const std::unique_ptr<AbstractSocketWriter> socket_writer_; | |
| 1598 | |
| 1599 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); | |
| 1600 }; // class StreamingListener | |
| 1601 | |
| 1602 #endif // GTEST_CAN_STREAM_RESULTS_ | |
| 1603 | |
| 1604 } // namespace internal | |
| 1605 } // namespace testing | |
| 1606 | |
| 1607 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 | |
| 1608 | |
| 1609 #endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ | |
| 1610 | |
| 1611 #if GTEST_OS_WINDOWS | |
| 1612 # define vsnprintf _vsnprintf | |
| 1613 #endif // GTEST_OS_WINDOWS | |
| 1614 | |
| 1615 #if GTEST_OS_MAC | |
| 1616 #ifndef GTEST_OS_IOS | |
| 1617 #include <crt_externs.h> | |
| 1618 #endif | |
| 1619 #endif | |
| 1620 | |
| 1621 #if GTEST_HAS_ABSL | |
| 1622 #include "absl/debugging/failure_signal_handler.h" | |
| 1623 #include "absl/debugging/stacktrace.h" | |
| 1624 #include "absl/debugging/symbolize.h" | |
| 1625 #include "absl/strings/str_cat.h" | |
| 1626 #endif // GTEST_HAS_ABSL | |
| 1627 | |
| 1628 namespace testing { | |
| 1629 | |
| 1630 using internal::CountIf; | |
| 1631 using internal::ForEach; | |
| 1632 using internal::GetElementOr; | |
| 1633 using internal::Shuffle; | |
| 1634 | |
| 1635 // Constants. | |
| 1636 | |
| 1637 // A test whose test suite name or test name matches this filter is | |
| 1638 // disabled and not run. | |
| 1639 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; | |
| 1640 | |
| 1641 // A test suite whose name matches this filter is considered a death | |
| 1642 // test suite and will be run before test suites whose name doesn't | |
| 1643 // match this filter. | |
| 1644 static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; | |
| 1645 | |
| 1646 // A test filter that matches everything. | |
| 1647 static const char kUniversalFilter[] = "*"; | |
| 1648 | |
| 1649 // The default output format. | |
| 1650 static const char kDefaultOutputFormat[] = "xml"; | |
| 1651 // The default output file. | |
| 1652 static const char kDefaultOutputFile[] = "test_detail"; | |
| 1653 | |
| 1654 // The environment variable name for the test shard index. | |
| 1655 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; | |
| 1656 // The environment variable name for the total number of test shards. | |
| 1657 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; | |
| 1658 // The environment variable name for the test shard status file. | |
| 1659 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; | |
| 1660 | |
| 1661 namespace internal { | |
| 1662 | |
| 1663 // The text used in failure messages to indicate the start of the | |
| 1664 // stack trace. | |
| 1665 const char kStackTraceMarker[] = "\nStack trace:\n"; | |
| 1666 | |
| 1667 // g_help_flag is true if and only if the --help flag or an equivalent form | |
| 1668 // is specified on the command line. | |
| 1669 bool g_help_flag = false; | |
| 1670 | |
| 1671 // Utilty function to Open File for Writing | |
| 1672 static FILE* OpenFileForWriting(const std::string& output_file) { | |
| 1673 FILE* fileout = nullptr; | |
| 1674 FilePath output_file_path(output_file); | |
| 1675 FilePath output_dir(output_file_path.RemoveFileName()); | |
| 1676 | |
| 1677 if (output_dir.CreateDirectoriesRecursively()) { | |
| 1678 fileout = posix::FOpen(output_file.c_str(), "w"); | |
| 1679 } | |
| 1680 if (fileout == nullptr) { | |
| 1681 GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\""; | |
| 1682 } | |
| 1683 return fileout; | |
| 1684 } | |
| 1685 | |
| 1686 } // namespace internal | |
| 1687 | |
| 1688 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY | |
| 1689 // environment variable. | |
| 1690 static const char* GetDefaultFilter() { | |
| 1691 const char* const testbridge_test_only = | |
| 1692 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); | |
| 1693 if (testbridge_test_only != nullptr) { | |
| 1694 return testbridge_test_only; | |
| 1695 } | |
| 1696 return kUniversalFilter; | |
| 1697 } | |
| 1698 | |
| 1699 // Bazel passes in the argument to '--test_runner_fail_fast' via the | |
| 1700 // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable. | |
| 1701 static bool GetDefaultFailFast() { | |
| 1702 const char* const testbridge_test_runner_fail_fast = | |
| 1703 internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST"); | |
| 1704 if (testbridge_test_runner_fail_fast != nullptr) { | |
| 1705 return strcmp(testbridge_test_runner_fail_fast, "1") == 0; | |
| 1706 } | |
| 1707 return false; | |
| 1708 } | |
| 1709 | |
| 1710 GTEST_DEFINE_bool_( | |
| 1711 fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()), | |
| 1712 "True if and only if a test failure should stop further test execution."); | |
| 1713 | |
| 1714 GTEST_DEFINE_bool_( | |
| 1715 also_run_disabled_tests, | |
| 1716 internal::BoolFromGTestEnv("also_run_disabled_tests", false), | |
| 1717 "Run disabled tests too, in addition to the tests normally being run."); | |
| 1718 | |
| 1719 GTEST_DEFINE_bool_( | |
| 1720 break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), | |
| 1721 "True if and only if a failed assertion should be a debugger " | |
| 1722 "break-point."); | |
| 1723 | |
| 1724 GTEST_DEFINE_bool_(catch_exceptions, | |
| 1725 internal::BoolFromGTestEnv("catch_exceptions", true), | |
| 1726 "True if and only if " GTEST_NAME_ | |
| 1727 " should catch exceptions and treat them as test failures."); | |
| 1728 | |
| 1729 GTEST_DEFINE_string_( | |
| 1730 color, | |
| 1731 internal::StringFromGTestEnv("color", "auto"), | |
| 1732 "Whether to use colors in the output. Valid values: yes, no, " | |
| 1733 "and auto. 'auto' means to use colors if the output is " | |
| 1734 "being sent to a terminal and the TERM environment variable " | |
| 1735 "is set to a terminal type that supports colors."); | |
| 1736 | |
| 1737 GTEST_DEFINE_string_( | |
| 1738 filter, | |
| 1739 internal::StringFromGTestEnv("filter", GetDefaultFilter()), | |
| 1740 "A colon-separated list of glob (not regex) patterns " | |
| 1741 "for filtering the tests to run, optionally followed by a " | |
| 1742 "'-' and a : separated list of negative patterns (tests to " | |
| 1743 "exclude). A test is run if it matches one of the positive " | |
| 1744 "patterns and does not match any of the negative patterns."); | |
| 1745 | |
| 1746 GTEST_DEFINE_bool_( | |
| 1747 install_failure_signal_handler, | |
| 1748 internal::BoolFromGTestEnv("install_failure_signal_handler", false), | |
| 1749 "If true and supported on the current platform, " GTEST_NAME_ " should " | |
| 1750 "install a signal handler that dumps debugging information when fatal " | |
| 1751 "signals are raised."); | |
| 1752 | |
| 1753 GTEST_DEFINE_bool_(list_tests, false, | |
| 1754 "List all tests without running them."); | |
| 1755 | |
| 1756 // The net priority order after flag processing is thus: | |
| 1757 // --gtest_output command line flag | |
| 1758 // GTEST_OUTPUT environment variable | |
| 1759 // XML_OUTPUT_FILE environment variable | |
| 1760 // '' | |
| 1761 GTEST_DEFINE_string_( | |
| 1762 output, | |
| 1763 internal::StringFromGTestEnv("output", | |
| 1764 internal::OutputFlagAlsoCheckEnvVar().c_str()), | |
| 1765 "A format (defaults to \"xml\" but can be specified to be \"json\"), " | |
| 1766 "optionally followed by a colon and an output file name or directory. " | |
| 1767 "A directory is indicated by a trailing pathname separator. " | |
| 1768 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " | |
| 1769 "If a directory is specified, output files will be created " | |
| 1770 "within that directory, with file-names based on the test " | |
| 1771 "executable's name and, if necessary, made unique by adding " | |
| 1772 "digits."); | |
| 1773 | |
| 1774 GTEST_DEFINE_bool_( | |
| 1775 brief, internal::BoolFromGTestEnv("brief", false), | |
| 1776 "True if only test failures should be displayed in text output."); | |
| 1777 | |
| 1778 GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true), | |
| 1779 "True if and only if " GTEST_NAME_ | |
| 1780 " should display elapsed time in text output."); | |
| 1781 | |
| 1782 GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true), | |
| 1783 "True if and only if " GTEST_NAME_ | |
| 1784 " prints UTF8 characters as text."); | |
| 1785 | |
| 1786 GTEST_DEFINE_int32_( | |
| 1787 random_seed, | |
| 1788 internal::Int32FromGTestEnv("random_seed", 0), | |
| 1789 "Random number seed to use when shuffling test orders. Must be in range " | |
| 1790 "[1, 99999], or 0 to use a seed based on the current time."); | |
| 1791 | |
| 1792 GTEST_DEFINE_int32_( | |
| 1793 repeat, | |
| 1794 internal::Int32FromGTestEnv("repeat", 1), | |
| 1795 "How many times to repeat each test. Specify a negative number " | |
| 1796 "for repeating forever. Useful for shaking out flaky tests."); | |
| 1797 | |
| 1798 GTEST_DEFINE_bool_(show_internal_stack_frames, false, | |
| 1799 "True if and only if " GTEST_NAME_ | |
| 1800 " should include internal stack frames when " | |
| 1801 "printing test failure stack traces."); | |
| 1802 | |
| 1803 GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false), | |
| 1804 "True if and only if " GTEST_NAME_ | |
| 1805 " should randomize tests' order on every run."); | |
| 1806 | |
| 1807 GTEST_DEFINE_int32_( | |
| 1808 stack_trace_depth, | |
| 1809 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), | |
| 1810 "The maximum number of stack frames to print when an " | |
| 1811 "assertion fails. The valid range is 0 through 100, inclusive."); | |
| 1812 | |
| 1813 GTEST_DEFINE_string_( | |
| 1814 stream_result_to, | |
| 1815 internal::StringFromGTestEnv("stream_result_to", ""), | |
| 1816 "This flag specifies the host name and the port number on which to stream " | |
| 1817 "test results. Example: \"localhost:555\". The flag is effective only on " | |
| 1818 "Linux."); | |
| 1819 | |
| 1820 GTEST_DEFINE_bool_( | |
| 1821 throw_on_failure, | |
| 1822 internal::BoolFromGTestEnv("throw_on_failure", false), | |
| 1823 "When this flag is specified, a failed assertion will throw an exception " | |
| 1824 "if exceptions are enabled or exit the program with a non-zero code " | |
| 1825 "otherwise. For use with an external test framework."); | |
| 1826 | |
| 1827 #if GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 1828 GTEST_DEFINE_string_( | |
| 1829 flagfile, | |
| 1830 internal::StringFromGTestEnv("flagfile", ""), | |
| 1831 "This flag specifies the flagfile to read command-line flags from."); | |
| 1832 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 1833 | |
| 1834 namespace internal { | |
| 1835 | |
| 1836 // Generates a random number from [0, range), using a Linear | |
| 1837 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater | |
| 1838 // than kMaxRange. | |
| 1839 uint32_t Random::Generate(uint32_t range) { | |
| 1840 // These constants are the same as are used in glibc's rand(3). | |
| 1841 // Use wider types than necessary to prevent unsigned overflow diagnostics. | |
| 1842 state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange; | |
| 1843 | |
| 1844 GTEST_CHECK_(range > 0) | |
| 1845 << "Cannot generate a number in the range [0, 0)."; | |
| 1846 GTEST_CHECK_(range <= kMaxRange) | |
| 1847 << "Generation of a number in [0, " << range << ") was requested, " | |
| 1848 << "but this can only generate numbers in [0, " << kMaxRange << ")."; | |
| 1849 | |
| 1850 // Converting via modulus introduces a bit of downward bias, but | |
| 1851 // it's simple, and a linear congruential generator isn't too good | |
| 1852 // to begin with. | |
| 1853 return state_ % range; | |
| 1854 } | |
| 1855 | |
| 1856 // GTestIsInitialized() returns true if and only if the user has initialized | |
| 1857 // Google Test. Useful for catching the user mistake of not initializing | |
| 1858 // Google Test before calling RUN_ALL_TESTS(). | |
| 1859 static bool GTestIsInitialized() { return GetArgvs().size() > 0; } | |
| 1860 | |
| 1861 // Iterates over a vector of TestSuites, keeping a running sum of the | |
| 1862 // results of calling a given int-returning method on each. | |
| 1863 // Returns the sum. | |
| 1864 static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, | |
| 1865 int (TestSuite::*method)() const) { | |
| 1866 int sum = 0; | |
| 1867 for (size_t i = 0; i < case_list.size(); i++) { | |
| 1868 sum += (case_list[i]->*method)(); | |
| 1869 } | |
| 1870 return sum; | |
| 1871 } | |
| 1872 | |
| 1873 // Returns true if and only if the test suite passed. | |
| 1874 static bool TestSuitePassed(const TestSuite* test_suite) { | |
| 1875 return test_suite->should_run() && test_suite->Passed(); | |
| 1876 } | |
| 1877 | |
| 1878 // Returns true if and only if the test suite failed. | |
| 1879 static bool TestSuiteFailed(const TestSuite* test_suite) { | |
| 1880 return test_suite->should_run() && test_suite->Failed(); | |
| 1881 } | |
| 1882 | |
| 1883 // Returns true if and only if test_suite contains at least one test that | |
| 1884 // should run. | |
| 1885 static bool ShouldRunTestSuite(const TestSuite* test_suite) { | |
| 1886 return test_suite->should_run(); | |
| 1887 } | |
| 1888 | |
| 1889 // AssertHelper constructor. | |
| 1890 AssertHelper::AssertHelper(TestPartResult::Type type, | |
| 1891 const char* file, | |
| 1892 int line, | |
| 1893 const char* message) | |
| 1894 : data_(new AssertHelperData(type, file, line, message)) { | |
| 1895 } | |
| 1896 | |
| 1897 AssertHelper::~AssertHelper() { | |
| 1898 delete data_; | |
| 1899 } | |
| 1900 | |
| 1901 // Message assignment, for assertion streaming support. | |
| 1902 void AssertHelper::operator=(const Message& message) const { | |
| 1903 UnitTest::GetInstance()-> | |
| 1904 AddTestPartResult(data_->type, data_->file, data_->line, | |
| 1905 AppendUserMessage(data_->message, message), | |
| 1906 UnitTest::GetInstance()->impl() | |
| 1907 ->CurrentOsStackTraceExceptTop(1) | |
| 1908 // Skips the stack frame for this function itself. | |
| 1909 ); // NOLINT | |
| 1910 } | |
| 1911 | |
| 1912 namespace { | |
| 1913 | |
| 1914 // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P | |
| 1915 // to creates test cases for it, a synthetic test case is | |
| 1916 // inserted to report ether an error or a log message. | |
| 1917 // | |
| 1918 // This configuration bit will likely be removed at some point. | |
| 1919 constexpr bool kErrorOnUninstantiatedParameterizedTest = true; | |
| 1920 constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true; | |
| 1921 | |
| 1922 // A test that fails at a given file/line location with a given message. | |
| 1923 class FailureTest : public Test { | |
| 1924 public: | |
| 1925 explicit FailureTest(const CodeLocation& loc, std::string error_message, | |
| 1926 bool as_error) | |
| 1927 : loc_(loc), | |
| 1928 error_message_(std::move(error_message)), | |
| 1929 as_error_(as_error) {} | |
| 1930 | |
| 1931 void TestBody() override { | |
| 1932 if (as_error_) { | |
| 1933 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(), | |
| 1934 loc_.line, "") = Message() << error_message_; | |
| 1935 } else { | |
| 1936 std::cout << error_message_ << std::endl; | |
| 1937 } | |
| 1938 } | |
| 1939 | |
| 1940 private: | |
| 1941 const CodeLocation loc_; | |
| 1942 const std::string error_message_; | |
| 1943 const bool as_error_; | |
| 1944 }; | |
| 1945 | |
| 1946 | |
| 1947 } // namespace | |
| 1948 | |
| 1949 std::set<std::string>* GetIgnoredParameterizedTestSuites() { | |
| 1950 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites(); | |
| 1951 } | |
| 1952 | |
| 1953 // Add a given test_suit to the list of them allow to go un-instantiated. | |
| 1954 MarkAsIgnored::MarkAsIgnored(const char* test_suite) { | |
| 1955 GetIgnoredParameterizedTestSuites()->insert(test_suite); | |
| 1956 } | |
| 1957 | |
| 1958 // If this parameterized test suite has no instantiations (and that | |
| 1959 // has not been marked as okay), emit a test case reporting that. | |
| 1960 void InsertSyntheticTestCase(const std::string& name, CodeLocation location, | |
| 1961 bool has_test_p) { | |
| 1962 const auto& ignored = *GetIgnoredParameterizedTestSuites(); | |
| 1963 if (ignored.find(name) != ignored.end()) return; | |
| 1964 | |
| 1965 const char kMissingInstantiation[] = // | |
| 1966 " is defined via TEST_P, but never instantiated. None of the test cases " | |
| 1967 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " | |
| 1968 "ones provided expand to nothing." | |
| 1969 "\n\n" | |
| 1970 "Ideally, TEST_P definitions should only ever be included as part of " | |
| 1971 "binaries that intend to use them. (As opposed to, for example, being " | |
| 1972 "placed in a library that may be linked in to get other utilities.)"; | |
| 1973 | |
| 1974 const char kMissingTestCase[] = // | |
| 1975 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are " | |
| 1976 "defined via TEST_P . No test cases will run." | |
| 1977 "\n\n" | |
| 1978 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from " | |
| 1979 "code that always depend on code that provides TEST_P. Failing to do " | |
| 1980 "so is often an indication of dead code, e.g. the last TEST_P was " | |
| 1981 "removed but the rest got left behind."; | |
| 1982 | |
| 1983 std::string message = | |
| 1984 "Parameterized test suite " + name + | |
| 1985 (has_test_p ? kMissingInstantiation : kMissingTestCase) + | |
| 1986 "\n\n" | |
| 1987 "To suppress this error for this test suite, insert the following line " | |
| 1988 "(in a non-header) in the namespace it is defined in:" | |
| 1989 "\n\n" | |
| 1990 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; | |
| 1991 | |
| 1992 std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; | |
| 1993 RegisterTest( // | |
| 1994 "GoogleTestVerification", full_name.c_str(), | |
| 1995 nullptr, // No type parameter. | |
| 1996 nullptr, // No value parameter. | |
| 1997 location.file.c_str(), location.line, [message, location] { | |
| 1998 return new FailureTest(location, message, | |
| 1999 kErrorOnUninstantiatedParameterizedTest); | |
| 2000 }); | |
| 2001 } | |
| 2002 | |
| 2003 void RegisterTypeParameterizedTestSuite(const char* test_suite_name, | |
| 2004 CodeLocation code_location) { | |
| 2005 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( | |
| 2006 test_suite_name, code_location); | |
| 2007 } | |
| 2008 | |
| 2009 void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { | |
| 2010 GetUnitTestImpl() | |
| 2011 ->type_parameterized_test_registry() | |
| 2012 .RegisterInstantiation(case_name); | |
| 2013 } | |
| 2014 | |
| 2015 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( | |
| 2016 const char* test_suite_name, CodeLocation code_location) { | |
| 2017 suites_.emplace(std::string(test_suite_name), | |
| 2018 TypeParameterizedTestSuiteInfo(code_location)); | |
| 2019 } | |
| 2020 | |
| 2021 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( | |
| 2022 const char* test_suite_name) { | |
| 2023 auto it = suites_.find(std::string(test_suite_name)); | |
| 2024 if (it != suites_.end()) { | |
| 2025 it->second.instantiated = true; | |
| 2026 } else { | |
| 2027 GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '" | |
| 2028 << test_suite_name << "'"; | |
| 2029 } | |
| 2030 } | |
| 2031 | |
| 2032 void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { | |
| 2033 const auto& ignored = *GetIgnoredParameterizedTestSuites(); | |
| 2034 for (const auto& testcase : suites_) { | |
| 2035 if (testcase.second.instantiated) continue; | |
| 2036 if (ignored.find(testcase.first) != ignored.end()) continue; | |
| 2037 | |
| 2038 std::string message = | |
| 2039 "Type parameterized test suite " + testcase.first + | |
| 2040 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated " | |
| 2041 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run." | |
| 2042 "\n\n" | |
| 2043 "Ideally, TYPED_TEST_P definitions should only ever be included as " | |
| 2044 "part of binaries that intend to use them. (As opposed to, for " | |
| 2045 "example, being placed in a library that may be linked in to get other " | |
| 2046 "utilities.)" | |
| 2047 "\n\n" | |
| 2048 "To suppress this error for this test suite, insert the following line " | |
| 2049 "(in a non-header) in the namespace it is defined in:" | |
| 2050 "\n\n" | |
| 2051 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + | |
| 2052 testcase.first + ");"; | |
| 2053 | |
| 2054 std::string full_name = | |
| 2055 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">"; | |
| 2056 RegisterTest( // | |
| 2057 "GoogleTestVerification", full_name.c_str(), | |
| 2058 nullptr, // No type parameter. | |
| 2059 nullptr, // No value parameter. | |
| 2060 testcase.second.code_location.file.c_str(), | |
| 2061 testcase.second.code_location.line, [message, testcase] { | |
| 2062 return new FailureTest(testcase.second.code_location, message, | |
| 2063 kErrorOnUninstantiatedTypeParameterizedTest); | |
| 2064 }); | |
| 2065 } | |
| 2066 } | |
| 2067 | |
| 2068 // A copy of all command line arguments. Set by InitGoogleTest(). | |
| 2069 static ::std::vector<std::string> g_argvs; | |
| 2070 | |
| 2071 ::std::vector<std::string> GetArgvs() { | |
| 2072 #if defined(GTEST_CUSTOM_GET_ARGVS_) | |
| 2073 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or | |
| 2074 // ::string. This code converts it to the appropriate type. | |
| 2075 const auto& custom = GTEST_CUSTOM_GET_ARGVS_(); | |
| 2076 return ::std::vector<std::string>(custom.begin(), custom.end()); | |
| 2077 #else // defined(GTEST_CUSTOM_GET_ARGVS_) | |
| 2078 return g_argvs; | |
| 2079 #endif // defined(GTEST_CUSTOM_GET_ARGVS_) | |
| 2080 } | |
| 2081 | |
| 2082 // Returns the current application's name, removing directory path if that | |
| 2083 // is present. | |
| 2084 FilePath GetCurrentExecutableName() { | |
| 2085 FilePath result; | |
| 2086 | |
| 2087 #if GTEST_OS_WINDOWS || GTEST_OS_OS2 | |
| 2088 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); | |
| 2089 #else | |
| 2090 result.Set(FilePath(GetArgvs()[0])); | |
| 2091 #endif // GTEST_OS_WINDOWS | |
| 2092 | |
| 2093 return result.RemoveDirectoryName(); | |
| 2094 } | |
| 2095 | |
| 2096 // Functions for processing the gtest_output flag. | |
| 2097 | |
| 2098 // Returns the output format, or "" for normal printed output. | |
| 2099 std::string UnitTestOptions::GetOutputFormat() { | |
| 2100 const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); | |
| 2101 const char* const colon = strchr(gtest_output_flag, ':'); | |
| 2102 return (colon == nullptr) | |
| 2103 ? std::string(gtest_output_flag) | |
| 2104 : std::string(gtest_output_flag, | |
| 2105 static_cast<size_t>(colon - gtest_output_flag)); | |
| 2106 } | |
| 2107 | |
| 2108 // Returns the name of the requested output file, or the default if none | |
| 2109 // was explicitly specified. | |
| 2110 std::string UnitTestOptions::GetAbsolutePathToOutputFile() { | |
| 2111 const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); | |
| 2112 | |
| 2113 std::string format = GetOutputFormat(); | |
| 2114 if (format.empty()) | |
| 2115 format = std::string(kDefaultOutputFormat); | |
| 2116 | |
| 2117 const char* const colon = strchr(gtest_output_flag, ':'); | |
| 2118 if (colon == nullptr) | |
| 2119 return internal::FilePath::MakeFileName( | |
| 2120 internal::FilePath( | |
| 2121 UnitTest::GetInstance()->original_working_dir()), | |
| 2122 internal::FilePath(kDefaultOutputFile), 0, | |
| 2123 format.c_str()).string(); | |
| 2124 | |
| 2125 internal::FilePath output_name(colon + 1); | |
| 2126 if (!output_name.IsAbsolutePath()) | |
| 2127 output_name = internal::FilePath::ConcatPaths( | |
| 2128 internal::FilePath(UnitTest::GetInstance()->original_working_dir()), | |
| 2129 internal::FilePath(colon + 1)); | |
| 2130 | |
| 2131 if (!output_name.IsDirectory()) | |
| 2132 return output_name.string(); | |
| 2133 | |
| 2134 internal::FilePath result(internal::FilePath::GenerateUniqueFileName( | |
| 2135 output_name, internal::GetCurrentExecutableName(), | |
| 2136 GetOutputFormat().c_str())); | |
| 2137 return result.string(); | |
| 2138 } | |
| 2139 | |
| 2140 // Returns true if and only if the wildcard pattern matches the string. Each | |
| 2141 // pattern consists of regular characters, single-character wildcards (?), and | |
| 2142 // multi-character wildcards (*). | |
| 2143 // | |
| 2144 // This function implements a linear-time string globbing algorithm based on | |
| 2145 // https://research.swtch.com/glob. | |
| 2146 static bool PatternMatchesString(const std::string& name_str, | |
| 2147 const char* pattern, const char* pattern_end) { | |
| 2148 const char* name = name_str.c_str(); | |
| 2149 const char* const name_begin = name; | |
| 2150 const char* const name_end = name + name_str.size(); | |
| 2151 | |
| 2152 const char* pattern_next = pattern; | |
| 2153 const char* name_next = name; | |
| 2154 | |
| 2155 while (pattern < pattern_end || name < name_end) { | |
| 2156 if (pattern < pattern_end) { | |
| 2157 switch (*pattern) { | |
| 2158 default: // Match an ordinary character. | |
| 2159 if (name < name_end && *name == *pattern) { | |
| 2160 ++pattern; | |
| 2161 ++name; | |
| 2162 continue; | |
| 2163 } | |
| 2164 break; | |
| 2165 case '?': // Match any single character. | |
| 2166 if (name < name_end) { | |
| 2167 ++pattern; | |
| 2168 ++name; | |
| 2169 continue; | |
| 2170 } | |
| 2171 break; | |
| 2172 case '*': | |
| 2173 // Match zero or more characters. Start by skipping over the wildcard | |
| 2174 // and matching zero characters from name. If that fails, restart and | |
| 2175 // match one more character than the last attempt. | |
| 2176 pattern_next = pattern; | |
| 2177 name_next = name + 1; | |
| 2178 ++pattern; | |
| 2179 continue; | |
| 2180 } | |
| 2181 } | |
| 2182 // Failed to match a character. Restart if possible. | |
| 2183 if (name_begin < name_next && name_next <= name_end) { | |
| 2184 pattern = pattern_next; | |
| 2185 name = name_next; | |
| 2186 continue; | |
| 2187 } | |
| 2188 return false; | |
| 2189 } | |
| 2190 return true; | |
| 2191 } | |
| 2192 | |
| 2193 bool UnitTestOptions::MatchesFilter(const std::string& name_str, | |
| 2194 const char* filter) { | |
| 2195 // The filter is a list of patterns separated by colons (:). | |
| 2196 const char* pattern = filter; | |
| 2197 while (true) { | |
| 2198 // Find the bounds of this pattern. | |
| 2199 const char* const next_sep = strchr(pattern, ':'); | |
| 2200 const char* const pattern_end = | |
| 2201 next_sep != nullptr ? next_sep : pattern + strlen(pattern); | |
| 2202 | |
| 2203 // Check if this pattern matches name_str. | |
| 2204 if (PatternMatchesString(name_str, pattern, pattern_end)) { | |
| 2205 break; | |
| 2206 } | |
| 2207 | |
| 2208 // Give up on this pattern. However, if we found a pattern separator (:), | |
| 2209 // advance to the next pattern (skipping over the separator) and restart. | |
| 2210 if (next_sep == nullptr) { | |
| 2211 return false; | |
| 2212 } | |
| 2213 pattern = next_sep + 1; | |
| 2214 } | |
| 2215 return true; | |
| 2216 } | |
| 2217 | |
| 2218 // Returns true if and only if the user-specified filter matches the test | |
| 2219 // suite name and the test name. | |
| 2220 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, | |
| 2221 const std::string& test_name) { | |
| 2222 const std::string& full_name = test_suite_name + "." + test_name.c_str(); | |
| 2223 | |
| 2224 // Split --gtest_filter at '-', if there is one, to separate into | |
| 2225 // positive filter and negative filter portions | |
| 2226 const char* const p = GTEST_FLAG(filter).c_str(); | |
| 2227 const char* const dash = strchr(p, '-'); | |
| 2228 std::string positive; | |
| 2229 std::string negative; | |
| 2230 if (dash == nullptr) { | |
| 2231 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter | |
| 2232 negative = ""; | |
| 2233 } else { | |
| 2234 positive = std::string(p, dash); // Everything up to the dash | |
| 2235 negative = std::string(dash + 1); // Everything after the dash | |
| 2236 if (positive.empty()) { | |
| 2237 // Treat '-test1' as the same as '*-test1' | |
| 2238 positive = kUniversalFilter; | |
| 2239 } | |
| 2240 } | |
| 2241 | |
| 2242 // A filter is a colon-separated list of patterns. It matches a | |
| 2243 // test if any pattern in it matches the test. | |
| 2244 return (MatchesFilter(full_name, positive.c_str()) && | |
| 2245 !MatchesFilter(full_name, negative.c_str())); | |
| 2246 } | |
| 2247 | |
| 2248 #if GTEST_HAS_SEH | |
| 2249 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the | |
| 2250 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. | |
| 2251 // This function is useful as an __except condition. | |
| 2252 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { | |
| 2253 // Google Test should handle a SEH exception if: | |
| 2254 // 1. the user wants it to, AND | |
| 2255 // 2. this is not a breakpoint exception, AND | |
| 2256 // 3. this is not a C++ exception (VC++ implements them via SEH, | |
| 2257 // apparently). | |
| 2258 // | |
| 2259 // SEH exception code for C++ exceptions. | |
| 2260 // (see http://support.microsoft.com/kb/185294 for more information). | |
| 2261 const DWORD kCxxExceptionCode = 0xe06d7363; | |
| 2262 | |
| 2263 bool should_handle = true; | |
| 2264 | |
| 2265 if (!GTEST_FLAG(catch_exceptions)) | |
| 2266 should_handle = false; | |
| 2267 else if (exception_code == EXCEPTION_BREAKPOINT) | |
| 2268 should_handle = false; | |
| 2269 else if (exception_code == kCxxExceptionCode) | |
| 2270 should_handle = false; | |
| 2271 | |
| 2272 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; | |
| 2273 } | |
| 2274 #endif // GTEST_HAS_SEH | |
| 2275 | |
| 2276 } // namespace internal | |
| 2277 | |
| 2278 // The c'tor sets this object as the test part result reporter used by | |
| 2279 // Google Test. The 'result' parameter specifies where to report the | |
| 2280 // results. Intercepts only failures from the current thread. | |
| 2281 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( | |
| 2282 TestPartResultArray* result) | |
| 2283 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), | |
| 2284 result_(result) { | |
| 2285 Init(); | |
| 2286 } | |
| 2287 | |
| 2288 // The c'tor sets this object as the test part result reporter used by | |
| 2289 // Google Test. The 'result' parameter specifies where to report the | |
| 2290 // results. | |
| 2291 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( | |
| 2292 InterceptMode intercept_mode, TestPartResultArray* result) | |
| 2293 : intercept_mode_(intercept_mode), | |
| 2294 result_(result) { | |
| 2295 Init(); | |
| 2296 } | |
| 2297 | |
| 2298 void ScopedFakeTestPartResultReporter::Init() { | |
| 2299 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 2300 if (intercept_mode_ == INTERCEPT_ALL_THREADS) { | |
| 2301 old_reporter_ = impl->GetGlobalTestPartResultReporter(); | |
| 2302 impl->SetGlobalTestPartResultReporter(this); | |
| 2303 } else { | |
| 2304 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); | |
| 2305 impl->SetTestPartResultReporterForCurrentThread(this); | |
| 2306 } | |
| 2307 } | |
| 2308 | |
| 2309 // The d'tor restores the test part result reporter used by Google Test | |
| 2310 // before. | |
| 2311 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { | |
| 2312 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 2313 if (intercept_mode_ == INTERCEPT_ALL_THREADS) { | |
| 2314 impl->SetGlobalTestPartResultReporter(old_reporter_); | |
| 2315 } else { | |
| 2316 impl->SetTestPartResultReporterForCurrentThread(old_reporter_); | |
| 2317 } | |
| 2318 } | |
| 2319 | |
| 2320 // Increments the test part result count and remembers the result. | |
| 2321 // This method is from the TestPartResultReporterInterface interface. | |
| 2322 void ScopedFakeTestPartResultReporter::ReportTestPartResult( | |
| 2323 const TestPartResult& result) { | |
| 2324 result_->Append(result); | |
| 2325 } | |
| 2326 | |
| 2327 namespace internal { | |
| 2328 | |
| 2329 // Returns the type ID of ::testing::Test. We should always call this | |
| 2330 // instead of GetTypeId< ::testing::Test>() to get the type ID of | |
| 2331 // testing::Test. This is to work around a suspected linker bug when | |
| 2332 // using Google Test as a framework on Mac OS X. The bug causes | |
| 2333 // GetTypeId< ::testing::Test>() to return different values depending | |
| 2334 // on whether the call is from the Google Test framework itself or | |
| 2335 // from user test code. GetTestTypeId() is guaranteed to always | |
| 2336 // return the same value, as it always calls GetTypeId<>() from the | |
| 2337 // gtest.cc, which is within the Google Test framework. | |
| 2338 TypeId GetTestTypeId() { | |
| 2339 return GetTypeId<Test>(); | |
| 2340 } | |
| 2341 | |
| 2342 // The value of GetTestTypeId() as seen from within the Google Test | |
| 2343 // library. This is solely for testing GetTestTypeId(). | |
| 2344 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); | |
| 2345 | |
| 2346 // This predicate-formatter checks that 'results' contains a test part | |
| 2347 // failure of the given type and that the failure message contains the | |
| 2348 // given substring. | |
| 2349 static AssertionResult HasOneFailure(const char* /* results_expr */, | |
| 2350 const char* /* type_expr */, | |
| 2351 const char* /* substr_expr */, | |
| 2352 const TestPartResultArray& results, | |
| 2353 TestPartResult::Type type, | |
| 2354 const std::string& substr) { | |
| 2355 const std::string expected(type == TestPartResult::kFatalFailure ? | |
| 2356 "1 fatal failure" : | |
| 2357 "1 non-fatal failure"); | |
| 2358 Message msg; | |
| 2359 if (results.size() != 1) { | |
| 2360 msg << "Expected: " << expected << "\n" | |
| 2361 << " Actual: " << results.size() << " failures"; | |
| 2362 for (int i = 0; i < results.size(); i++) { | |
| 2363 msg << "\n" << results.GetTestPartResult(i); | |
| 2364 } | |
| 2365 return AssertionFailure() << msg; | |
| 2366 } | |
| 2367 | |
| 2368 const TestPartResult& r = results.GetTestPartResult(0); | |
| 2369 if (r.type() != type) { | |
| 2370 return AssertionFailure() << "Expected: " << expected << "\n" | |
| 2371 << " Actual:\n" | |
| 2372 << r; | |
| 2373 } | |
| 2374 | |
| 2375 if (strstr(r.message(), substr.c_str()) == nullptr) { | |
| 2376 return AssertionFailure() << "Expected: " << expected << " containing \"" | |
| 2377 << substr << "\"\n" | |
| 2378 << " Actual:\n" | |
| 2379 << r; | |
| 2380 } | |
| 2381 | |
| 2382 return AssertionSuccess(); | |
| 2383 } | |
| 2384 | |
| 2385 // The constructor of SingleFailureChecker remembers where to look up | |
| 2386 // test part results, what type of failure we expect, and what | |
| 2387 // substring the failure message should contain. | |
| 2388 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, | |
| 2389 TestPartResult::Type type, | |
| 2390 const std::string& substr) | |
| 2391 : results_(results), type_(type), substr_(substr) {} | |
| 2392 | |
| 2393 // The destructor of SingleFailureChecker verifies that the given | |
| 2394 // TestPartResultArray contains exactly one failure that has the given | |
| 2395 // type and contains the given substring. If that's not the case, a | |
| 2396 // non-fatal failure will be generated. | |
| 2397 SingleFailureChecker::~SingleFailureChecker() { | |
| 2398 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); | |
| 2399 } | |
| 2400 | |
| 2401 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( | |
| 2402 UnitTestImpl* unit_test) : unit_test_(unit_test) {} | |
| 2403 | |
| 2404 void DefaultGlobalTestPartResultReporter::ReportTestPartResult( | |
| 2405 const TestPartResult& result) { | |
| 2406 unit_test_->current_test_result()->AddTestPartResult(result); | |
| 2407 unit_test_->listeners()->repeater()->OnTestPartResult(result); | |
| 2408 } | |
| 2409 | |
| 2410 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( | |
| 2411 UnitTestImpl* unit_test) : unit_test_(unit_test) {} | |
| 2412 | |
| 2413 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( | |
| 2414 const TestPartResult& result) { | |
| 2415 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); | |
| 2416 } | |
| 2417 | |
| 2418 // Returns the global test part result reporter. | |
| 2419 TestPartResultReporterInterface* | |
| 2420 UnitTestImpl::GetGlobalTestPartResultReporter() { | |
| 2421 internal::MutexLock lock(&global_test_part_result_reporter_mutex_); | |
| 2422 return global_test_part_result_repoter_; | |
| 2423 } | |
| 2424 | |
| 2425 // Sets the global test part result reporter. | |
| 2426 void UnitTestImpl::SetGlobalTestPartResultReporter( | |
| 2427 TestPartResultReporterInterface* reporter) { | |
| 2428 internal::MutexLock lock(&global_test_part_result_reporter_mutex_); | |
| 2429 global_test_part_result_repoter_ = reporter; | |
| 2430 } | |
| 2431 | |
| 2432 // Returns the test part result reporter for the current thread. | |
| 2433 TestPartResultReporterInterface* | |
| 2434 UnitTestImpl::GetTestPartResultReporterForCurrentThread() { | |
| 2435 return per_thread_test_part_result_reporter_.get(); | |
| 2436 } | |
| 2437 | |
| 2438 // Sets the test part result reporter for the current thread. | |
| 2439 void UnitTestImpl::SetTestPartResultReporterForCurrentThread( | |
| 2440 TestPartResultReporterInterface* reporter) { | |
| 2441 per_thread_test_part_result_reporter_.set(reporter); | |
| 2442 } | |
| 2443 | |
| 2444 // Gets the number of successful test suites. | |
| 2445 int UnitTestImpl::successful_test_suite_count() const { | |
| 2446 return CountIf(test_suites_, TestSuitePassed); | |
| 2447 } | |
| 2448 | |
| 2449 // Gets the number of failed test suites. | |
| 2450 int UnitTestImpl::failed_test_suite_count() const { | |
| 2451 return CountIf(test_suites_, TestSuiteFailed); | |
| 2452 } | |
| 2453 | |
| 2454 // Gets the number of all test suites. | |
| 2455 int UnitTestImpl::total_test_suite_count() const { | |
| 2456 return static_cast<int>(test_suites_.size()); | |
| 2457 } | |
| 2458 | |
| 2459 // Gets the number of all test suites that contain at least one test | |
| 2460 // that should run. | |
| 2461 int UnitTestImpl::test_suite_to_run_count() const { | |
| 2462 return CountIf(test_suites_, ShouldRunTestSuite); | |
| 2463 } | |
| 2464 | |
| 2465 // Gets the number of successful tests. | |
| 2466 int UnitTestImpl::successful_test_count() const { | |
| 2467 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count); | |
| 2468 } | |
| 2469 | |
| 2470 // Gets the number of skipped tests. | |
| 2471 int UnitTestImpl::skipped_test_count() const { | |
| 2472 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count); | |
| 2473 } | |
| 2474 | |
| 2475 // Gets the number of failed tests. | |
| 2476 int UnitTestImpl::failed_test_count() const { | |
| 2477 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count); | |
| 2478 } | |
| 2479 | |
| 2480 // Gets the number of disabled tests that will be reported in the XML report. | |
| 2481 int UnitTestImpl::reportable_disabled_test_count() const { | |
| 2482 return SumOverTestSuiteList(test_suites_, | |
| 2483 &TestSuite::reportable_disabled_test_count); | |
| 2484 } | |
| 2485 | |
| 2486 // Gets the number of disabled tests. | |
| 2487 int UnitTestImpl::disabled_test_count() const { | |
| 2488 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count); | |
| 2489 } | |
| 2490 | |
| 2491 // Gets the number of tests to be printed in the XML report. | |
| 2492 int UnitTestImpl::reportable_test_count() const { | |
| 2493 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count); | |
| 2494 } | |
| 2495 | |
| 2496 // Gets the number of all tests. | |
| 2497 int UnitTestImpl::total_test_count() const { | |
| 2498 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count); | |
| 2499 } | |
| 2500 | |
| 2501 // Gets the number of tests that should run. | |
| 2502 int UnitTestImpl::test_to_run_count() const { | |
| 2503 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count); | |
| 2504 } | |
| 2505 | |
| 2506 // Returns the current OS stack trace as an std::string. | |
| 2507 // | |
| 2508 // The maximum number of stack frames to be included is specified by | |
| 2509 // the gtest_stack_trace_depth flag. The skip_count parameter | |
| 2510 // specifies the number of top frames to be skipped, which doesn't | |
| 2511 // count against the number of frames to be included. | |
| 2512 // | |
| 2513 // For example, if Foo() calls Bar(), which in turn calls | |
| 2514 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the | |
| 2515 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. | |
| 2516 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { | |
| 2517 return os_stack_trace_getter()->CurrentStackTrace( | |
| 2518 static_cast<int>(GTEST_FLAG(stack_trace_depth)), | |
| 2519 skip_count + 1 | |
| 2520 // Skips the user-specified number of frames plus this function | |
| 2521 // itself. | |
| 2522 ); // NOLINT | |
| 2523 } | |
| 2524 | |
| 2525 // A helper class for measuring elapsed times. | |
| 2526 class Timer { | |
| 2527 public: | |
| 2528 Timer() : start_(std::chrono::steady_clock::now()) {} | |
| 2529 | |
| 2530 // Return time elapsed in milliseconds since the timer was created. | |
| 2531 TimeInMillis Elapsed() { | |
| 2532 return std::chrono::duration_cast<std::chrono::milliseconds>( | |
| 2533 std::chrono::steady_clock::now() - start_) | |
| 2534 .count(); | |
| 2535 } | |
| 2536 | |
| 2537 private: | |
| 2538 std::chrono::steady_clock::time_point start_; | |
| 2539 }; | |
| 2540 | |
| 2541 // Returns a timestamp as milliseconds since the epoch. Note this time may jump | |
| 2542 // around subject to adjustments by the system, to measure elapsed time use | |
| 2543 // Timer instead. | |
| 2544 TimeInMillis GetTimeInMillis() { | |
| 2545 return std::chrono::duration_cast<std::chrono::milliseconds>( | |
| 2546 std::chrono::system_clock::now() - | |
| 2547 std::chrono::system_clock::from_time_t(0)) | |
| 2548 .count(); | |
| 2549 } | |
| 2550 | |
| 2551 // Utilities | |
| 2552 | |
| 2553 // class String. | |
| 2554 | |
| 2555 #if GTEST_OS_WINDOWS_MOBILE | |
| 2556 // Creates a UTF-16 wide string from the given ANSI string, allocating | |
| 2557 // memory using new. The caller is responsible for deleting the return | |
| 2558 // value using delete[]. Returns the wide string, or NULL if the | |
| 2559 // input is NULL. | |
| 2560 LPCWSTR String::AnsiToUtf16(const char* ansi) { | |
| 2561 if (!ansi) return nullptr; | |
| 2562 const int length = strlen(ansi); | |
| 2563 const int unicode_length = | |
| 2564 MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); | |
| 2565 WCHAR* unicode = new WCHAR[unicode_length + 1]; | |
| 2566 MultiByteToWideChar(CP_ACP, 0, ansi, length, | |
| 2567 unicode, unicode_length); | |
| 2568 unicode[unicode_length] = 0; | |
| 2569 return unicode; | |
| 2570 } | |
| 2571 | |
| 2572 // Creates an ANSI string from the given wide string, allocating | |
| 2573 // memory using new. The caller is responsible for deleting the return | |
| 2574 // value using delete[]. Returns the ANSI string, or NULL if the | |
| 2575 // input is NULL. | |
| 2576 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { | |
| 2577 if (!utf16_str) return nullptr; | |
| 2578 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, | |
| 2579 0, nullptr, nullptr); | |
| 2580 char* ansi = new char[ansi_length + 1]; | |
| 2581 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr, | |
| 2582 nullptr); | |
| 2583 ansi[ansi_length] = 0; | |
| 2584 return ansi; | |
| 2585 } | |
| 2586 | |
| 2587 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 2588 | |
| 2589 // Compares two C strings. Returns true if and only if they have the same | |
| 2590 // content. | |
| 2591 // | |
| 2592 // Unlike strcmp(), this function can handle NULL argument(s). A NULL | |
| 2593 // C string is considered different to any non-NULL C string, | |
| 2594 // including the empty string. | |
| 2595 bool String::CStringEquals(const char * lhs, const char * rhs) { | |
| 2596 if (lhs == nullptr) return rhs == nullptr; | |
| 2597 | |
| 2598 if (rhs == nullptr) return false; | |
| 2599 | |
| 2600 return strcmp(lhs, rhs) == 0; | |
| 2601 } | |
| 2602 | |
| 2603 #if GTEST_HAS_STD_WSTRING | |
| 2604 | |
| 2605 // Converts an array of wide chars to a narrow string using the UTF-8 | |
| 2606 // encoding, and streams the result to the given Message object. | |
| 2607 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, | |
| 2608 Message* msg) { | |
| 2609 for (size_t i = 0; i != length; ) { // NOLINT | |
| 2610 if (wstr[i] != L'\0') { | |
| 2611 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); | |
| 2612 while (i != length && wstr[i] != L'\0') | |
| 2613 i++; | |
| 2614 } else { | |
| 2615 *msg << '\0'; | |
| 2616 i++; | |
| 2617 } | |
| 2618 } | |
| 2619 } | |
| 2620 | |
| 2621 #endif // GTEST_HAS_STD_WSTRING | |
| 2622 | |
| 2623 void SplitString(const ::std::string& str, char delimiter, | |
| 2624 ::std::vector< ::std::string>* dest) { | |
| 2625 ::std::vector< ::std::string> parsed; | |
| 2626 ::std::string::size_type pos = 0; | |
| 2627 while (::testing::internal::AlwaysTrue()) { | |
| 2628 const ::std::string::size_type colon = str.find(delimiter, pos); | |
| 2629 if (colon == ::std::string::npos) { | |
| 2630 parsed.push_back(str.substr(pos)); | |
| 2631 break; | |
| 2632 } else { | |
| 2633 parsed.push_back(str.substr(pos, colon - pos)); | |
| 2634 pos = colon + 1; | |
| 2635 } | |
| 2636 } | |
| 2637 dest->swap(parsed); | |
| 2638 } | |
| 2639 | |
| 2640 } // namespace internal | |
| 2641 | |
| 2642 // Constructs an empty Message. | |
| 2643 // We allocate the stringstream separately because otherwise each use of | |
| 2644 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's | |
| 2645 // stack frame leading to huge stack frames in some cases; gcc does not reuse | |
| 2646 // the stack space. | |
| 2647 Message::Message() : ss_(new ::std::stringstream) { | |
| 2648 // By default, we want there to be enough precision when printing | |
| 2649 // a double to a Message. | |
| 2650 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); | |
| 2651 } | |
| 2652 | |
| 2653 // These two overloads allow streaming a wide C string to a Message | |
| 2654 // using the UTF-8 encoding. | |
| 2655 Message& Message::operator <<(const wchar_t* wide_c_str) { | |
| 2656 return *this << internal::String::ShowWideCString(wide_c_str); | |
| 2657 } | |
| 2658 Message& Message::operator <<(wchar_t* wide_c_str) { | |
| 2659 return *this << internal::String::ShowWideCString(wide_c_str); | |
| 2660 } | |
| 2661 | |
| 2662 #if GTEST_HAS_STD_WSTRING | |
| 2663 // Converts the given wide string to a narrow string using the UTF-8 | |
| 2664 // encoding, and streams the result to this Message object. | |
| 2665 Message& Message::operator <<(const ::std::wstring& wstr) { | |
| 2666 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); | |
| 2667 return *this; | |
| 2668 } | |
| 2669 #endif // GTEST_HAS_STD_WSTRING | |
| 2670 | |
| 2671 // Gets the text streamed to this object so far as an std::string. | |
| 2672 // Each '\0' character in the buffer is replaced with "\\0". | |
| 2673 std::string Message::GetString() const { | |
| 2674 return internal::StringStreamToString(ss_.get()); | |
| 2675 } | |
| 2676 | |
| 2677 // AssertionResult constructors. | |
| 2678 // Used in EXPECT_TRUE/FALSE(assertion_result). | |
| 2679 AssertionResult::AssertionResult(const AssertionResult& other) | |
| 2680 : success_(other.success_), | |
| 2681 message_(other.message_.get() != nullptr | |
| 2682 ? new ::std::string(*other.message_) | |
| 2683 : static_cast< ::std::string*>(nullptr)) {} | |
| 2684 | |
| 2685 // Swaps two AssertionResults. | |
| 2686 void AssertionResult::swap(AssertionResult& other) { | |
| 2687 using std::swap; | |
| 2688 swap(success_, other.success_); | |
| 2689 swap(message_, other.message_); | |
| 2690 } | |
| 2691 | |
| 2692 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. | |
| 2693 AssertionResult AssertionResult::operator!() const { | |
| 2694 AssertionResult negation(!success_); | |
| 2695 if (message_.get() != nullptr) negation << *message_; | |
| 2696 return negation; | |
| 2697 } | |
| 2698 | |
| 2699 // Makes a successful assertion result. | |
| 2700 AssertionResult AssertionSuccess() { | |
| 2701 return AssertionResult(true); | |
| 2702 } | |
| 2703 | |
| 2704 // Makes a failed assertion result. | |
| 2705 AssertionResult AssertionFailure() { | |
| 2706 return AssertionResult(false); | |
| 2707 } | |
| 2708 | |
| 2709 // Makes a failed assertion result with the given failure message. | |
| 2710 // Deprecated; use AssertionFailure() << message. | |
| 2711 AssertionResult AssertionFailure(const Message& message) { | |
| 2712 return AssertionFailure() << message; | |
| 2713 } | |
| 2714 | |
| 2715 namespace internal { | |
| 2716 | |
| 2717 namespace edit_distance { | |
| 2718 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, | |
| 2719 const std::vector<size_t>& right) { | |
| 2720 std::vector<std::vector<double> > costs( | |
| 2721 left.size() + 1, std::vector<double>(right.size() + 1)); | |
| 2722 std::vector<std::vector<EditType> > best_move( | |
| 2723 left.size() + 1, std::vector<EditType>(right.size() + 1)); | |
| 2724 | |
| 2725 // Populate for empty right. | |
| 2726 for (size_t l_i = 0; l_i < costs.size(); ++l_i) { | |
| 2727 costs[l_i][0] = static_cast<double>(l_i); | |
| 2728 best_move[l_i][0] = kRemove; | |
| 2729 } | |
| 2730 // Populate for empty left. | |
| 2731 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { | |
| 2732 costs[0][r_i] = static_cast<double>(r_i); | |
| 2733 best_move[0][r_i] = kAdd; | |
| 2734 } | |
| 2735 | |
| 2736 for (size_t l_i = 0; l_i < left.size(); ++l_i) { | |
| 2737 for (size_t r_i = 0; r_i < right.size(); ++r_i) { | |
| 2738 if (left[l_i] == right[r_i]) { | |
| 2739 // Found a match. Consume it. | |
| 2740 costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; | |
| 2741 best_move[l_i + 1][r_i + 1] = kMatch; | |
| 2742 continue; | |
| 2743 } | |
| 2744 | |
| 2745 const double add = costs[l_i + 1][r_i]; | |
| 2746 const double remove = costs[l_i][r_i + 1]; | |
| 2747 const double replace = costs[l_i][r_i]; | |
| 2748 if (add < remove && add < replace) { | |
| 2749 costs[l_i + 1][r_i + 1] = add + 1; | |
| 2750 best_move[l_i + 1][r_i + 1] = kAdd; | |
| 2751 } else if (remove < add && remove < replace) { | |
| 2752 costs[l_i + 1][r_i + 1] = remove + 1; | |
| 2753 best_move[l_i + 1][r_i + 1] = kRemove; | |
| 2754 } else { | |
| 2755 // We make replace a little more expensive than add/remove to lower | |
| 2756 // their priority. | |
| 2757 costs[l_i + 1][r_i + 1] = replace + 1.00001; | |
| 2758 best_move[l_i + 1][r_i + 1] = kReplace; | |
| 2759 } | |
| 2760 } | |
| 2761 } | |
| 2762 | |
| 2763 // Reconstruct the best path. We do it in reverse order. | |
| 2764 std::vector<EditType> best_path; | |
| 2765 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { | |
| 2766 EditType move = best_move[l_i][r_i]; | |
| 2767 best_path.push_back(move); | |
| 2768 l_i -= move != kAdd; | |
| 2769 r_i -= move != kRemove; | |
| 2770 } | |
| 2771 std::reverse(best_path.begin(), best_path.end()); | |
| 2772 return best_path; | |
| 2773 } | |
| 2774 | |
| 2775 namespace { | |
| 2776 | |
| 2777 // Helper class to convert string into ids with deduplication. | |
| 2778 class InternalStrings { | |
| 2779 public: | |
| 2780 size_t GetId(const std::string& str) { | |
| 2781 IdMap::iterator it = ids_.find(str); | |
| 2782 if (it != ids_.end()) return it->second; | |
| 2783 size_t id = ids_.size(); | |
| 2784 return ids_[str] = id; | |
| 2785 } | |
| 2786 | |
| 2787 private: | |
| 2788 typedef std::map<std::string, size_t> IdMap; | |
| 2789 IdMap ids_; | |
| 2790 }; | |
| 2791 | |
| 2792 } // namespace | |
| 2793 | |
| 2794 std::vector<EditType> CalculateOptimalEdits( | |
| 2795 const std::vector<std::string>& left, | |
| 2796 const std::vector<std::string>& right) { | |
| 2797 std::vector<size_t> left_ids, right_ids; | |
| 2798 { | |
| 2799 InternalStrings intern_table; | |
| 2800 for (size_t i = 0; i < left.size(); ++i) { | |
| 2801 left_ids.push_back(intern_table.GetId(left[i])); | |
| 2802 } | |
| 2803 for (size_t i = 0; i < right.size(); ++i) { | |
| 2804 right_ids.push_back(intern_table.GetId(right[i])); | |
| 2805 } | |
| 2806 } | |
| 2807 return CalculateOptimalEdits(left_ids, right_ids); | |
| 2808 } | |
| 2809 | |
| 2810 namespace { | |
| 2811 | |
| 2812 // Helper class that holds the state for one hunk and prints it out to the | |
| 2813 // stream. | |
| 2814 // It reorders adds/removes when possible to group all removes before all | |
| 2815 // adds. It also adds the hunk header before printint into the stream. | |
| 2816 class Hunk { | |
| 2817 public: | |
| 2818 Hunk(size_t left_start, size_t right_start) | |
| 2819 : left_start_(left_start), | |
| 2820 right_start_(right_start), | |
| 2821 adds_(), | |
| 2822 removes_(), | |
| 2823 common_() {} | |
| 2824 | |
| 2825 void PushLine(char edit, const char* line) { | |
| 2826 switch (edit) { | |
| 2827 case ' ': | |
| 2828 ++common_; | |
| 2829 FlushEdits(); | |
| 2830 hunk_.push_back(std::make_pair(' ', line)); | |
| 2831 break; | |
| 2832 case '-': | |
| 2833 ++removes_; | |
| 2834 hunk_removes_.push_back(std::make_pair('-', line)); | |
| 2835 break; | |
| 2836 case '+': | |
| 2837 ++adds_; | |
| 2838 hunk_adds_.push_back(std::make_pair('+', line)); | |
| 2839 break; | |
| 2840 } | |
| 2841 } | |
| 2842 | |
| 2843 void PrintTo(std::ostream* os) { | |
| 2844 PrintHeader(os); | |
| 2845 FlushEdits(); | |
| 2846 for (std::list<std::pair<char, const char*> >::const_iterator it = | |
| 2847 hunk_.begin(); | |
| 2848 it != hunk_.end(); ++it) { | |
| 2849 *os << it->first << it->second << "\n"; | |
| 2850 } | |
| 2851 } | |
| 2852 | |
| 2853 bool has_edits() const { return adds_ || removes_; } | |
| 2854 | |
| 2855 private: | |
| 2856 void FlushEdits() { | |
| 2857 hunk_.splice(hunk_.end(), hunk_removes_); | |
| 2858 hunk_.splice(hunk_.end(), hunk_adds_); | |
| 2859 } | |
| 2860 | |
| 2861 // Print a unified diff header for one hunk. | |
| 2862 // The format is | |
| 2863 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@" | |
| 2864 // where the left/right parts are omitted if unnecessary. | |
| 2865 void PrintHeader(std::ostream* ss) const { | |
| 2866 *ss << "@@ "; | |
| 2867 if (removes_) { | |
| 2868 *ss << "-" << left_start_ << "," << (removes_ + common_); | |
| 2869 } | |
| 2870 if (removes_ && adds_) { | |
| 2871 *ss << " "; | |
| 2872 } | |
| 2873 if (adds_) { | |
| 2874 *ss << "+" << right_start_ << "," << (adds_ + common_); | |
| 2875 } | |
| 2876 *ss << " @@\n"; | |
| 2877 } | |
| 2878 | |
| 2879 size_t left_start_, right_start_; | |
| 2880 size_t adds_, removes_, common_; | |
| 2881 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; | |
| 2882 }; | |
| 2883 | |
| 2884 } // namespace | |
| 2885 | |
| 2886 // Create a list of diff hunks in Unified diff format. | |
| 2887 // Each hunk has a header generated by PrintHeader above plus a body with | |
| 2888 // lines prefixed with ' ' for no change, '-' for deletion and '+' for | |
| 2889 // addition. | |
| 2890 // 'context' represents the desired unchanged prefix/suffix around the diff. | |
| 2891 // If two hunks are close enough that their contexts overlap, then they are | |
| 2892 // joined into one hunk. | |
| 2893 std::string CreateUnifiedDiff(const std::vector<std::string>& left, | |
| 2894 const std::vector<std::string>& right, | |
| 2895 size_t context) { | |
| 2896 const std::vector<EditType> edits = CalculateOptimalEdits(left, right); | |
| 2897 | |
| 2898 size_t l_i = 0, r_i = 0, edit_i = 0; | |
| 2899 std::stringstream ss; | |
| 2900 while (edit_i < edits.size()) { | |
| 2901 // Find first edit. | |
| 2902 while (edit_i < edits.size() && edits[edit_i] == kMatch) { | |
| 2903 ++l_i; | |
| 2904 ++r_i; | |
| 2905 ++edit_i; | |
| 2906 } | |
| 2907 | |
| 2908 // Find the first line to include in the hunk. | |
| 2909 const size_t prefix_context = std::min(l_i, context); | |
| 2910 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); | |
| 2911 for (size_t i = prefix_context; i > 0; --i) { | |
| 2912 hunk.PushLine(' ', left[l_i - i].c_str()); | |
| 2913 } | |
| 2914 | |
| 2915 // Iterate the edits until we found enough suffix for the hunk or the input | |
| 2916 // is over. | |
| 2917 size_t n_suffix = 0; | |
| 2918 for (; edit_i < edits.size(); ++edit_i) { | |
| 2919 if (n_suffix >= context) { | |
| 2920 // Continue only if the next hunk is very close. | |
| 2921 auto it = edits.begin() + static_cast<int>(edit_i); | |
| 2922 while (it != edits.end() && *it == kMatch) ++it; | |
| 2923 if (it == edits.end() || | |
| 2924 static_cast<size_t>(it - edits.begin()) - edit_i >= context) { | |
| 2925 // There is no next edit or it is too far away. | |
| 2926 break; | |
| 2927 } | |
| 2928 } | |
| 2929 | |
| 2930 EditType edit = edits[edit_i]; | |
| 2931 // Reset count when a non match is found. | |
| 2932 n_suffix = edit == kMatch ? n_suffix + 1 : 0; | |
| 2933 | |
| 2934 if (edit == kMatch || edit == kRemove || edit == kReplace) { | |
| 2935 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); | |
| 2936 } | |
| 2937 if (edit == kAdd || edit == kReplace) { | |
| 2938 hunk.PushLine('+', right[r_i].c_str()); | |
| 2939 } | |
| 2940 | |
| 2941 // Advance indices, depending on edit type. | |
| 2942 l_i += edit != kAdd; | |
| 2943 r_i += edit != kRemove; | |
| 2944 } | |
| 2945 | |
| 2946 if (!hunk.has_edits()) { | |
| 2947 // We are done. We don't want this hunk. | |
| 2948 break; | |
| 2949 } | |
| 2950 | |
| 2951 hunk.PrintTo(&ss); | |
| 2952 } | |
| 2953 return ss.str(); | |
| 2954 } | |
| 2955 | |
| 2956 } // namespace edit_distance | |
| 2957 | |
| 2958 namespace { | |
| 2959 | |
| 2960 // The string representation of the values received in EqFailure() are already | |
| 2961 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped | |
| 2962 // characters the same. | |
| 2963 std::vector<std::string> SplitEscapedString(const std::string& str) { | |
| 2964 std::vector<std::string> lines; | |
| 2965 size_t start = 0, end = str.size(); | |
| 2966 if (end > 2 && str[0] == '"' && str[end - 1] == '"') { | |
| 2967 ++start; | |
| 2968 --end; | |
| 2969 } | |
| 2970 bool escaped = false; | |
| 2971 for (size_t i = start; i + 1 < end; ++i) { | |
| 2972 if (escaped) { | |
| 2973 escaped = false; | |
| 2974 if (str[i] == 'n') { | |
| 2975 lines.push_back(str.substr(start, i - start - 1)); | |
| 2976 start = i + 1; | |
| 2977 } | |
| 2978 } else { | |
| 2979 escaped = str[i] == '\\'; | |
| 2980 } | |
| 2981 } | |
| 2982 lines.push_back(str.substr(start, end - start)); | |
| 2983 return lines; | |
| 2984 } | |
| 2985 | |
| 2986 } // namespace | |
| 2987 | |
| 2988 // Constructs and returns the message for an equality assertion | |
| 2989 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. | |
| 2990 // | |
| 2991 // The first four parameters are the expressions used in the assertion | |
| 2992 // and their values, as strings. For example, for ASSERT_EQ(foo, bar) | |
| 2993 // where foo is 5 and bar is 6, we have: | |
| 2994 // | |
| 2995 // lhs_expression: "foo" | |
| 2996 // rhs_expression: "bar" | |
| 2997 // lhs_value: "5" | |
| 2998 // rhs_value: "6" | |
| 2999 // | |
| 3000 // The ignoring_case parameter is true if and only if the assertion is a | |
| 3001 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will | |
| 3002 // be inserted into the message. | |
| 3003 AssertionResult EqFailure(const char* lhs_expression, | |
| 3004 const char* rhs_expression, | |
| 3005 const std::string& lhs_value, | |
| 3006 const std::string& rhs_value, | |
| 3007 bool ignoring_case) { | |
| 3008 Message msg; | |
| 3009 msg << "Expected equality of these values:"; | |
| 3010 msg << "\n " << lhs_expression; | |
| 3011 if (lhs_value != lhs_expression) { | |
| 3012 msg << "\n Which is: " << lhs_value; | |
| 3013 } | |
| 3014 msg << "\n " << rhs_expression; | |
| 3015 if (rhs_value != rhs_expression) { | |
| 3016 msg << "\n Which is: " << rhs_value; | |
| 3017 } | |
| 3018 | |
| 3019 if (ignoring_case) { | |
| 3020 msg << "\nIgnoring case"; | |
| 3021 } | |
| 3022 | |
| 3023 if (!lhs_value.empty() && !rhs_value.empty()) { | |
| 3024 const std::vector<std::string> lhs_lines = | |
| 3025 SplitEscapedString(lhs_value); | |
| 3026 const std::vector<std::string> rhs_lines = | |
| 3027 SplitEscapedString(rhs_value); | |
| 3028 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { | |
| 3029 msg << "\nWith diff:\n" | |
| 3030 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); | |
| 3031 } | |
| 3032 } | |
| 3033 | |
| 3034 return AssertionFailure() << msg; | |
| 3035 } | |
| 3036 | |
| 3037 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. | |
| 3038 std::string GetBoolAssertionFailureMessage( | |
| 3039 const AssertionResult& assertion_result, | |
| 3040 const char* expression_text, | |
| 3041 const char* actual_predicate_value, | |
| 3042 const char* expected_predicate_value) { | |
| 3043 const char* actual_message = assertion_result.message(); | |
| 3044 Message msg; | |
| 3045 msg << "Value of: " << expression_text | |
| 3046 << "\n Actual: " << actual_predicate_value; | |
| 3047 if (actual_message[0] != '\0') | |
| 3048 msg << " (" << actual_message << ")"; | |
| 3049 msg << "\nExpected: " << expected_predicate_value; | |
| 3050 return msg.GetString(); | |
| 3051 } | |
| 3052 | |
| 3053 // Helper function for implementing ASSERT_NEAR. | |
| 3054 AssertionResult DoubleNearPredFormat(const char* expr1, | |
| 3055 const char* expr2, | |
| 3056 const char* abs_error_expr, | |
| 3057 double val1, | |
| 3058 double val2, | |
| 3059 double abs_error) { | |
| 3060 const double diff = fabs(val1 - val2); | |
| 3061 if (diff <= abs_error) return AssertionSuccess(); | |
| 3062 | |
| 3063 // Find the value which is closest to zero. | |
| 3064 const double min_abs = std::min(fabs(val1), fabs(val2)); | |
| 3065 // Find the distance to the next double from that value. | |
| 3066 const double epsilon = | |
| 3067 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs; | |
| 3068 // Detect the case where abs_error is so small that EXPECT_NEAR is | |
| 3069 // effectively the same as EXPECT_EQUAL, and give an informative error | |
| 3070 // message so that the situation can be more easily understood without | |
| 3071 // requiring exotic floating-point knowledge. | |
| 3072 // Don't do an epsilon check if abs_error is zero because that implies | |
| 3073 // that an equality check was actually intended. | |
| 3074 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 && | |
| 3075 abs_error < epsilon) { | |
| 3076 return AssertionFailure() | |
| 3077 << "The difference between " << expr1 << " and " << expr2 << " is " | |
| 3078 << diff << ", where\n" | |
| 3079 << expr1 << " evaluates to " << val1 << ",\n" | |
| 3080 << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter " | |
| 3081 << abs_error_expr << " evaluates to " << abs_error | |
| 3082 << " which is smaller than the minimum distance between doubles for " | |
| 3083 "numbers of this magnitude which is " | |
| 3084 << epsilon | |
| 3085 << ", thus making this EXPECT_NEAR check equivalent to " | |
| 3086 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; | |
| 3087 } | |
| 3088 return AssertionFailure() | |
| 3089 << "The difference between " << expr1 << " and " << expr2 | |
| 3090 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" | |
| 3091 << expr1 << " evaluates to " << val1 << ",\n" | |
| 3092 << expr2 << " evaluates to " << val2 << ", and\n" | |
| 3093 << abs_error_expr << " evaluates to " << abs_error << "."; | |
| 3094 } | |
| 3095 | |
| 3096 | |
| 3097 // Helper template for implementing FloatLE() and DoubleLE(). | |
| 3098 template <typename RawType> | |
| 3099 AssertionResult FloatingPointLE(const char* expr1, | |
| 3100 const char* expr2, | |
| 3101 RawType val1, | |
| 3102 RawType val2) { | |
| 3103 // Returns success if val1 is less than val2, | |
| 3104 if (val1 < val2) { | |
| 3105 return AssertionSuccess(); | |
| 3106 } | |
| 3107 | |
| 3108 // or if val1 is almost equal to val2. | |
| 3109 const FloatingPoint<RawType> lhs(val1), rhs(val2); | |
| 3110 if (lhs.AlmostEquals(rhs)) { | |
| 3111 return AssertionSuccess(); | |
| 3112 } | |
| 3113 | |
| 3114 // Note that the above two checks will both fail if either val1 or | |
| 3115 // val2 is NaN, as the IEEE floating-point standard requires that | |
| 3116 // any predicate involving a NaN must return false. | |
| 3117 | |
| 3118 ::std::stringstream val1_ss; | |
| 3119 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) | |
| 3120 << val1; | |
| 3121 | |
| 3122 ::std::stringstream val2_ss; | |
| 3123 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) | |
| 3124 << val2; | |
| 3125 | |
| 3126 return AssertionFailure() | |
| 3127 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" | |
| 3128 << " Actual: " << StringStreamToString(&val1_ss) << " vs " | |
| 3129 << StringStreamToString(&val2_ss); | |
| 3130 } | |
| 3131 | |
| 3132 } // namespace internal | |
| 3133 | |
| 3134 // Asserts that val1 is less than, or almost equal to, val2. Fails | |
| 3135 // otherwise. In particular, it fails if either val1 or val2 is NaN. | |
| 3136 AssertionResult FloatLE(const char* expr1, const char* expr2, | |
| 3137 float val1, float val2) { | |
| 3138 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); | |
| 3139 } | |
| 3140 | |
| 3141 // Asserts that val1 is less than, or almost equal to, val2. Fails | |
| 3142 // otherwise. In particular, it fails if either val1 or val2 is NaN. | |
| 3143 AssertionResult DoubleLE(const char* expr1, const char* expr2, | |
| 3144 double val1, double val2) { | |
| 3145 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); | |
| 3146 } | |
| 3147 | |
| 3148 namespace internal { | |
| 3149 | |
| 3150 // The helper function for {ASSERT|EXPECT}_STREQ. | |
| 3151 AssertionResult CmpHelperSTREQ(const char* lhs_expression, | |
| 3152 const char* rhs_expression, | |
| 3153 const char* lhs, | |
| 3154 const char* rhs) { | |
| 3155 if (String::CStringEquals(lhs, rhs)) { | |
| 3156 return AssertionSuccess(); | |
| 3157 } | |
| 3158 | |
| 3159 return EqFailure(lhs_expression, | |
| 3160 rhs_expression, | |
| 3161 PrintToString(lhs), | |
| 3162 PrintToString(rhs), | |
| 3163 false); | |
| 3164 } | |
| 3165 | |
| 3166 // The helper function for {ASSERT|EXPECT}_STRCASEEQ. | |
| 3167 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, | |
| 3168 const char* rhs_expression, | |
| 3169 const char* lhs, | |
| 3170 const char* rhs) { | |
| 3171 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { | |
| 3172 return AssertionSuccess(); | |
| 3173 } | |
| 3174 | |
| 3175 return EqFailure(lhs_expression, | |
| 3176 rhs_expression, | |
| 3177 PrintToString(lhs), | |
| 3178 PrintToString(rhs), | |
| 3179 true); | |
| 3180 } | |
| 3181 | |
| 3182 // The helper function for {ASSERT|EXPECT}_STRNE. | |
| 3183 AssertionResult CmpHelperSTRNE(const char* s1_expression, | |
| 3184 const char* s2_expression, | |
| 3185 const char* s1, | |
| 3186 const char* s2) { | |
| 3187 if (!String::CStringEquals(s1, s2)) { | |
| 3188 return AssertionSuccess(); | |
| 3189 } else { | |
| 3190 return AssertionFailure() << "Expected: (" << s1_expression << ") != (" | |
| 3191 << s2_expression << "), actual: \"" | |
| 3192 << s1 << "\" vs \"" << s2 << "\""; | |
| 3193 } | |
| 3194 } | |
| 3195 | |
| 3196 // The helper function for {ASSERT|EXPECT}_STRCASENE. | |
| 3197 AssertionResult CmpHelperSTRCASENE(const char* s1_expression, | |
| 3198 const char* s2_expression, | |
| 3199 const char* s1, | |
| 3200 const char* s2) { | |
| 3201 if (!String::CaseInsensitiveCStringEquals(s1, s2)) { | |
| 3202 return AssertionSuccess(); | |
| 3203 } else { | |
| 3204 return AssertionFailure() | |
| 3205 << "Expected: (" << s1_expression << ") != (" | |
| 3206 << s2_expression << ") (ignoring case), actual: \"" | |
| 3207 << s1 << "\" vs \"" << s2 << "\""; | |
| 3208 } | |
| 3209 } | |
| 3210 | |
| 3211 } // namespace internal | |
| 3212 | |
| 3213 namespace { | |
| 3214 | |
| 3215 // Helper functions for implementing IsSubString() and IsNotSubstring(). | |
| 3216 | |
| 3217 // This group of overloaded functions return true if and only if needle | |
| 3218 // is a substring of haystack. NULL is considered a substring of | |
| 3219 // itself only. | |
| 3220 | |
| 3221 bool IsSubstringPred(const char* needle, const char* haystack) { | |
| 3222 if (needle == nullptr || haystack == nullptr) return needle == haystack; | |
| 3223 | |
| 3224 return strstr(haystack, needle) != nullptr; | |
| 3225 } | |
| 3226 | |
| 3227 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { | |
| 3228 if (needle == nullptr || haystack == nullptr) return needle == haystack; | |
| 3229 | |
| 3230 return wcsstr(haystack, needle) != nullptr; | |
| 3231 } | |
| 3232 | |
| 3233 // StringType here can be either ::std::string or ::std::wstring. | |
| 3234 template <typename StringType> | |
| 3235 bool IsSubstringPred(const StringType& needle, | |
| 3236 const StringType& haystack) { | |
| 3237 return haystack.find(needle) != StringType::npos; | |
| 3238 } | |
| 3239 | |
| 3240 // This function implements either IsSubstring() or IsNotSubstring(), | |
| 3241 // depending on the value of the expected_to_be_substring parameter. | |
| 3242 // StringType here can be const char*, const wchar_t*, ::std::string, | |
| 3243 // or ::std::wstring. | |
| 3244 template <typename StringType> | |
| 3245 AssertionResult IsSubstringImpl( | |
| 3246 bool expected_to_be_substring, | |
| 3247 const char* needle_expr, const char* haystack_expr, | |
| 3248 const StringType& needle, const StringType& haystack) { | |
| 3249 if (IsSubstringPred(needle, haystack) == expected_to_be_substring) | |
| 3250 return AssertionSuccess(); | |
| 3251 | |
| 3252 const bool is_wide_string = sizeof(needle[0]) > 1; | |
| 3253 const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; | |
| 3254 return AssertionFailure() | |
| 3255 << "Value of: " << needle_expr << "\n" | |
| 3256 << " Actual: " << begin_string_quote << needle << "\"\n" | |
| 3257 << "Expected: " << (expected_to_be_substring ? "" : "not ") | |
| 3258 << "a substring of " << haystack_expr << "\n" | |
| 3259 << "Which is: " << begin_string_quote << haystack << "\""; | |
| 3260 } | |
| 3261 | |
| 3262 } // namespace | |
| 3263 | |
| 3264 // IsSubstring() and IsNotSubstring() check whether needle is a | |
| 3265 // substring of haystack (NULL is considered a substring of itself | |
| 3266 // only), and return an appropriate error message when they fail. | |
| 3267 | |
| 3268 AssertionResult IsSubstring( | |
| 3269 const char* needle_expr, const char* haystack_expr, | |
| 3270 const char* needle, const char* haystack) { | |
| 3271 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); | |
| 3272 } | |
| 3273 | |
| 3274 AssertionResult IsSubstring( | |
| 3275 const char* needle_expr, const char* haystack_expr, | |
| 3276 const wchar_t* needle, const wchar_t* haystack) { | |
| 3277 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); | |
| 3278 } | |
| 3279 | |
| 3280 AssertionResult IsNotSubstring( | |
| 3281 const char* needle_expr, const char* haystack_expr, | |
| 3282 const char* needle, const char* haystack) { | |
| 3283 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); | |
| 3284 } | |
| 3285 | |
| 3286 AssertionResult IsNotSubstring( | |
| 3287 const char* needle_expr, const char* haystack_expr, | |
| 3288 const wchar_t* needle, const wchar_t* haystack) { | |
| 3289 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); | |
| 3290 } | |
| 3291 | |
| 3292 AssertionResult IsSubstring( | |
| 3293 const char* needle_expr, const char* haystack_expr, | |
| 3294 const ::std::string& needle, const ::std::string& haystack) { | |
| 3295 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); | |
| 3296 } | |
| 3297 | |
| 3298 AssertionResult IsNotSubstring( | |
| 3299 const char* needle_expr, const char* haystack_expr, | |
| 3300 const ::std::string& needle, const ::std::string& haystack) { | |
| 3301 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); | |
| 3302 } | |
| 3303 | |
| 3304 #if GTEST_HAS_STD_WSTRING | |
| 3305 AssertionResult IsSubstring( | |
| 3306 const char* needle_expr, const char* haystack_expr, | |
| 3307 const ::std::wstring& needle, const ::std::wstring& haystack) { | |
| 3308 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); | |
| 3309 } | |
| 3310 | |
| 3311 AssertionResult IsNotSubstring( | |
| 3312 const char* needle_expr, const char* haystack_expr, | |
| 3313 const ::std::wstring& needle, const ::std::wstring& haystack) { | |
| 3314 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); | |
| 3315 } | |
| 3316 #endif // GTEST_HAS_STD_WSTRING | |
| 3317 | |
| 3318 namespace internal { | |
| 3319 | |
| 3320 #if GTEST_OS_WINDOWS | |
| 3321 | |
| 3322 namespace { | |
| 3323 | |
| 3324 // Helper function for IsHRESULT{SuccessFailure} predicates | |
| 3325 AssertionResult HRESULTFailureHelper(const char* expr, | |
| 3326 const char* expected, | |
| 3327 long hr) { // NOLINT | |
| 3328 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE | |
| 3329 | |
| 3330 // Windows CE doesn't support FormatMessage. | |
| 3331 const char error_text[] = ""; | |
| 3332 | |
| 3333 # else | |
| 3334 | |
| 3335 // Looks up the human-readable system message for the HRESULT code | |
| 3336 // and since we're not passing any params to FormatMessage, we don't | |
| 3337 // want inserts expanded. | |
| 3338 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | | |
| 3339 FORMAT_MESSAGE_IGNORE_INSERTS; | |
| 3340 const DWORD kBufSize = 4096; | |
| 3341 // Gets the system's human readable message string for this HRESULT. | |
| 3342 char error_text[kBufSize] = { '\0' }; | |
| 3343 DWORD message_length = ::FormatMessageA(kFlags, | |
| 3344 0, // no source, we're asking system | |
| 3345 static_cast<DWORD>(hr), // the error | |
| 3346 0, // no line width restrictions | |
| 3347 error_text, // output buffer | |
| 3348 kBufSize, // buf size | |
| 3349 nullptr); // no arguments for inserts | |
| 3350 // Trims tailing white space (FormatMessage leaves a trailing CR-LF) | |
| 3351 for (; message_length && IsSpace(error_text[message_length - 1]); | |
| 3352 --message_length) { | |
| 3353 error_text[message_length - 1] = '\0'; | |
| 3354 } | |
| 3355 | |
| 3356 # endif // GTEST_OS_WINDOWS_MOBILE | |
| 3357 | |
| 3358 const std::string error_hex("0x" + String::FormatHexInt(hr)); | |
| 3359 return ::testing::AssertionFailure() | |
| 3360 << "Expected: " << expr << " " << expected << ".\n" | |
| 3361 << " Actual: " << error_hex << " " << error_text << "\n"; | |
| 3362 } | |
| 3363 | |
| 3364 } // namespace | |
| 3365 | |
| 3366 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT | |
| 3367 if (SUCCEEDED(hr)) { | |
| 3368 return AssertionSuccess(); | |
| 3369 } | |
| 3370 return HRESULTFailureHelper(expr, "succeeds", hr); | |
| 3371 } | |
| 3372 | |
| 3373 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT | |
| 3374 if (FAILED(hr)) { | |
| 3375 return AssertionSuccess(); | |
| 3376 } | |
| 3377 return HRESULTFailureHelper(expr, "fails", hr); | |
| 3378 } | |
| 3379 | |
| 3380 #endif // GTEST_OS_WINDOWS | |
| 3381 | |
| 3382 // Utility functions for encoding Unicode text (wide strings) in | |
| 3383 // UTF-8. | |
| 3384 | |
| 3385 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8 | |
| 3386 // like this: | |
| 3387 // | |
| 3388 // Code-point length Encoding | |
| 3389 // 0 - 7 bits 0xxxxxxx | |
| 3390 // 8 - 11 bits 110xxxxx 10xxxxxx | |
| 3391 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx | |
| 3392 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | |
| 3393 | |
| 3394 // The maximum code-point a one-byte UTF-8 sequence can represent. | |
| 3395 constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; | |
| 3396 | |
| 3397 // The maximum code-point a two-byte UTF-8 sequence can represent. | |
| 3398 constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1; | |
| 3399 | |
| 3400 // The maximum code-point a three-byte UTF-8 sequence can represent. | |
| 3401 constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1; | |
| 3402 | |
| 3403 // The maximum code-point a four-byte UTF-8 sequence can represent. | |
| 3404 constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1; | |
| 3405 | |
| 3406 // Chops off the n lowest bits from a bit pattern. Returns the n | |
| 3407 // lowest bits. As a side effect, the original bit pattern will be | |
| 3408 // shifted to the right by n bits. | |
| 3409 inline uint32_t ChopLowBits(uint32_t* bits, int n) { | |
| 3410 const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1); | |
| 3411 *bits >>= n; | |
| 3412 return low_bits; | |
| 3413 } | |
| 3414 | |
| 3415 // Converts a Unicode code point to a narrow string in UTF-8 encoding. | |
| 3416 // code_point parameter is of type uint32_t because wchar_t may not be | |
| 3417 // wide enough to contain a code point. | |
| 3418 // If the code_point is not a valid Unicode code point | |
| 3419 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted | |
| 3420 // to "(Invalid Unicode 0xXXXXXXXX)". | |
| 3421 std::string CodePointToUtf8(uint32_t code_point) { | |
| 3422 if (code_point > kMaxCodePoint4) { | |
| 3423 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")"; | |
| 3424 } | |
| 3425 | |
| 3426 char str[5]; // Big enough for the largest valid code point. | |
| 3427 if (code_point <= kMaxCodePoint1) { | |
| 3428 str[1] = '\0'; | |
| 3429 str[0] = static_cast<char>(code_point); // 0xxxxxxx | |
| 3430 } else if (code_point <= kMaxCodePoint2) { | |
| 3431 str[2] = '\0'; | |
| 3432 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3433 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx | |
| 3434 } else if (code_point <= kMaxCodePoint3) { | |
| 3435 str[3] = '\0'; | |
| 3436 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3437 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3438 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx | |
| 3439 } else { // code_point <= kMaxCodePoint4 | |
| 3440 str[4] = '\0'; | |
| 3441 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3442 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3443 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx | |
| 3444 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx | |
| 3445 } | |
| 3446 return str; | |
| 3447 } | |
| 3448 | |
| 3449 // The following two functions only make sense if the system | |
| 3450 // uses UTF-16 for wide string encoding. All supported systems | |
| 3451 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16. | |
| 3452 | |
| 3453 // Determines if the arguments constitute UTF-16 surrogate pair | |
| 3454 // and thus should be combined into a single Unicode code point | |
| 3455 // using CreateCodePointFromUtf16SurrogatePair. | |
| 3456 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { | |
| 3457 return sizeof(wchar_t) == 2 && | |
| 3458 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; | |
| 3459 } | |
| 3460 | |
| 3461 // Creates a Unicode code point from UTF16 surrogate pair. | |
| 3462 inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, | |
| 3463 wchar_t second) { | |
| 3464 const auto first_u = static_cast<uint32_t>(first); | |
| 3465 const auto second_u = static_cast<uint32_t>(second); | |
| 3466 const uint32_t mask = (1 << 10) - 1; | |
| 3467 return (sizeof(wchar_t) == 2) | |
| 3468 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000 | |
| 3469 : | |
| 3470 // This function should not be called when the condition is | |
| 3471 // false, but we provide a sensible default in case it is. | |
| 3472 first_u; | |
| 3473 } | |
| 3474 | |
| 3475 // Converts a wide string to a narrow string in UTF-8 encoding. | |
| 3476 // The wide string is assumed to have the following encoding: | |
| 3477 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) | |
| 3478 // UTF-32 if sizeof(wchar_t) == 4 (on Linux) | |
| 3479 // Parameter str points to a null-terminated wide string. | |
| 3480 // Parameter num_chars may additionally limit the number | |
| 3481 // of wchar_t characters processed. -1 is used when the entire string | |
| 3482 // should be processed. | |
| 3483 // If the string contains code points that are not valid Unicode code points | |
| 3484 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output | |
| 3485 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding | |
| 3486 // and contains invalid UTF-16 surrogate pairs, values in those pairs | |
| 3487 // will be encoded as individual Unicode characters from Basic Normal Plane. | |
| 3488 std::string WideStringToUtf8(const wchar_t* str, int num_chars) { | |
| 3489 if (num_chars == -1) | |
| 3490 num_chars = static_cast<int>(wcslen(str)); | |
| 3491 | |
| 3492 ::std::stringstream stream; | |
| 3493 for (int i = 0; i < num_chars; ++i) { | |
| 3494 uint32_t unicode_code_point; | |
| 3495 | |
| 3496 if (str[i] == L'\0') { | |
| 3497 break; | |
| 3498 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { | |
| 3499 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], | |
| 3500 str[i + 1]); | |
| 3501 i++; | |
| 3502 } else { | |
| 3503 unicode_code_point = static_cast<uint32_t>(str[i]); | |
| 3504 } | |
| 3505 | |
| 3506 stream << CodePointToUtf8(unicode_code_point); | |
| 3507 } | |
| 3508 return StringStreamToString(&stream); | |
| 3509 } | |
| 3510 | |
| 3511 // Converts a wide C string to an std::string using the UTF-8 encoding. | |
| 3512 // NULL will be converted to "(null)". | |
| 3513 std::string String::ShowWideCString(const wchar_t * wide_c_str) { | |
| 3514 if (wide_c_str == nullptr) return "(null)"; | |
| 3515 | |
| 3516 return internal::WideStringToUtf8(wide_c_str, -1); | |
| 3517 } | |
| 3518 | |
| 3519 // Compares two wide C strings. Returns true if and only if they have the | |
| 3520 // same content. | |
| 3521 // | |
| 3522 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL | |
| 3523 // C string is considered different to any non-NULL C string, | |
| 3524 // including the empty string. | |
| 3525 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { | |
| 3526 if (lhs == nullptr) return rhs == nullptr; | |
| 3527 | |
| 3528 if (rhs == nullptr) return false; | |
| 3529 | |
| 3530 return wcscmp(lhs, rhs) == 0; | |
| 3531 } | |
| 3532 | |
| 3533 // Helper function for *_STREQ on wide strings. | |
| 3534 AssertionResult CmpHelperSTREQ(const char* lhs_expression, | |
| 3535 const char* rhs_expression, | |
| 3536 const wchar_t* lhs, | |
| 3537 const wchar_t* rhs) { | |
| 3538 if (String::WideCStringEquals(lhs, rhs)) { | |
| 3539 return AssertionSuccess(); | |
| 3540 } | |
| 3541 | |
| 3542 return EqFailure(lhs_expression, | |
| 3543 rhs_expression, | |
| 3544 PrintToString(lhs), | |
| 3545 PrintToString(rhs), | |
| 3546 false); | |
| 3547 } | |
| 3548 | |
| 3549 // Helper function for *_STRNE on wide strings. | |
| 3550 AssertionResult CmpHelperSTRNE(const char* s1_expression, | |
| 3551 const char* s2_expression, | |
| 3552 const wchar_t* s1, | |
| 3553 const wchar_t* s2) { | |
| 3554 if (!String::WideCStringEquals(s1, s2)) { | |
| 3555 return AssertionSuccess(); | |
| 3556 } | |
| 3557 | |
| 3558 return AssertionFailure() << "Expected: (" << s1_expression << ") != (" | |
| 3559 << s2_expression << "), actual: " | |
| 3560 << PrintToString(s1) | |
| 3561 << " vs " << PrintToString(s2); | |
| 3562 } | |
| 3563 | |
| 3564 // Compares two C strings, ignoring case. Returns true if and only if they have | |
| 3565 // the same content. | |
| 3566 // | |
| 3567 // Unlike strcasecmp(), this function can handle NULL argument(s). A | |
| 3568 // NULL C string is considered different to any non-NULL C string, | |
| 3569 // including the empty string. | |
| 3570 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { | |
| 3571 if (lhs == nullptr) return rhs == nullptr; | |
| 3572 if (rhs == nullptr) return false; | |
| 3573 return posix::StrCaseCmp(lhs, rhs) == 0; | |
| 3574 } | |
| 3575 | |
| 3576 // Compares two wide C strings, ignoring case. Returns true if and only if they | |
| 3577 // have the same content. | |
| 3578 // | |
| 3579 // Unlike wcscasecmp(), this function can handle NULL argument(s). | |
| 3580 // A NULL C string is considered different to any non-NULL wide C string, | |
| 3581 // including the empty string. | |
| 3582 // NB: The implementations on different platforms slightly differ. | |
| 3583 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE | |
| 3584 // environment variable. On GNU platform this method uses wcscasecmp | |
| 3585 // which compares according to LC_CTYPE category of the current locale. | |
| 3586 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the | |
| 3587 // current locale. | |
| 3588 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, | |
| 3589 const wchar_t* rhs) { | |
| 3590 if (lhs == nullptr) return rhs == nullptr; | |
| 3591 | |
| 3592 if (rhs == nullptr) return false; | |
| 3593 | |
| 3594 #if GTEST_OS_WINDOWS | |
| 3595 return _wcsicmp(lhs, rhs) == 0; | |
| 3596 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID | |
| 3597 return wcscasecmp(lhs, rhs) == 0; | |
| 3598 #else | |
| 3599 // Android, Mac OS X and Cygwin don't define wcscasecmp. | |
| 3600 // Other unknown OSes may not define it either. | |
| 3601 wint_t left, right; | |
| 3602 do { | |
| 3603 left = towlower(static_cast<wint_t>(*lhs++)); | |
| 3604 right = towlower(static_cast<wint_t>(*rhs++)); | |
| 3605 } while (left && left == right); | |
| 3606 return left == right; | |
| 3607 #endif // OS selector | |
| 3608 } | |
| 3609 | |
| 3610 // Returns true if and only if str ends with the given suffix, ignoring case. | |
| 3611 // Any string is considered to end with an empty suffix. | |
| 3612 bool String::EndsWithCaseInsensitive( | |
| 3613 const std::string& str, const std::string& suffix) { | |
| 3614 const size_t str_len = str.length(); | |
| 3615 const size_t suffix_len = suffix.length(); | |
| 3616 return (str_len >= suffix_len) && | |
| 3617 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, | |
| 3618 suffix.c_str()); | |
| 3619 } | |
| 3620 | |
| 3621 // Formats an int value as "%02d". | |
| 3622 std::string String::FormatIntWidth2(int value) { | |
| 3623 return FormatIntWidthN(value, 2); | |
| 3624 } | |
| 3625 | |
| 3626 // Formats an int value to given width with leading zeros. | |
| 3627 std::string String::FormatIntWidthN(int value, int width) { | |
| 3628 std::stringstream ss; | |
| 3629 ss << std::setfill('0') << std::setw(width) << value; | |
| 3630 return ss.str(); | |
| 3631 } | |
| 3632 | |
| 3633 // Formats an int value as "%X". | |
| 3634 std::string String::FormatHexUInt32(uint32_t value) { | |
| 3635 std::stringstream ss; | |
| 3636 ss << std::hex << std::uppercase << value; | |
| 3637 return ss.str(); | |
| 3638 } | |
| 3639 | |
| 3640 // Formats an int value as "%X". | |
| 3641 std::string String::FormatHexInt(int value) { | |
| 3642 return FormatHexUInt32(static_cast<uint32_t>(value)); | |
| 3643 } | |
| 3644 | |
| 3645 // Formats a byte as "%02X". | |
| 3646 std::string String::FormatByte(unsigned char value) { | |
| 3647 std::stringstream ss; | |
| 3648 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase | |
| 3649 << static_cast<unsigned int>(value); | |
| 3650 return ss.str(); | |
| 3651 } | |
| 3652 | |
| 3653 // Converts the buffer in a stringstream to an std::string, converting NUL | |
| 3654 // bytes to "\\0" along the way. | |
| 3655 std::string StringStreamToString(::std::stringstream* ss) { | |
| 3656 const ::std::string& str = ss->str(); | |
| 3657 const char* const start = str.c_str(); | |
| 3658 const char* const end = start + str.length(); | |
| 3659 | |
| 3660 std::string result; | |
| 3661 result.reserve(static_cast<size_t>(2 * (end - start))); | |
| 3662 for (const char* ch = start; ch != end; ++ch) { | |
| 3663 if (*ch == '\0') { | |
| 3664 result += "\\0"; // Replaces NUL with "\\0"; | |
| 3665 } else { | |
| 3666 result += *ch; | |
| 3667 } | |
| 3668 } | |
| 3669 | |
| 3670 return result; | |
| 3671 } | |
| 3672 | |
| 3673 // Appends the user-supplied message to the Google-Test-generated message. | |
| 3674 std::string AppendUserMessage(const std::string& gtest_msg, | |
| 3675 const Message& user_msg) { | |
| 3676 // Appends the user message if it's non-empty. | |
| 3677 const std::string user_msg_string = user_msg.GetString(); | |
| 3678 if (user_msg_string.empty()) { | |
| 3679 return gtest_msg; | |
| 3680 } | |
| 3681 if (gtest_msg.empty()) { | |
| 3682 return user_msg_string; | |
| 3683 } | |
| 3684 return gtest_msg + "\n" + user_msg_string; | |
| 3685 } | |
| 3686 | |
| 3687 } // namespace internal | |
| 3688 | |
| 3689 // class TestResult | |
| 3690 | |
| 3691 // Creates an empty TestResult. | |
| 3692 TestResult::TestResult() | |
| 3693 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} | |
| 3694 | |
| 3695 // D'tor. | |
| 3696 TestResult::~TestResult() { | |
| 3697 } | |
| 3698 | |
| 3699 // Returns the i-th test part result among all the results. i can | |
| 3700 // range from 0 to total_part_count() - 1. If i is not in that range, | |
| 3701 // aborts the program. | |
| 3702 const TestPartResult& TestResult::GetTestPartResult(int i) const { | |
| 3703 if (i < 0 || i >= total_part_count()) | |
| 3704 internal::posix::Abort(); | |
| 3705 return test_part_results_.at(static_cast<size_t>(i)); | |
| 3706 } | |
| 3707 | |
| 3708 // Returns the i-th test property. i can range from 0 to | |
| 3709 // test_property_count() - 1. If i is not in that range, aborts the | |
| 3710 // program. | |
| 3711 const TestProperty& TestResult::GetTestProperty(int i) const { | |
| 3712 if (i < 0 || i >= test_property_count()) | |
| 3713 internal::posix::Abort(); | |
| 3714 return test_properties_.at(static_cast<size_t>(i)); | |
| 3715 } | |
| 3716 | |
| 3717 // Clears the test part results. | |
| 3718 void TestResult::ClearTestPartResults() { | |
| 3719 test_part_results_.clear(); | |
| 3720 } | |
| 3721 | |
| 3722 // Adds a test part result to the list. | |
| 3723 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { | |
| 3724 test_part_results_.push_back(test_part_result); | |
| 3725 } | |
| 3726 | |
| 3727 // Adds a test property to the list. If a property with the same key as the | |
| 3728 // supplied property is already represented, the value of this test_property | |
| 3729 // replaces the old value for that key. | |
| 3730 void TestResult::RecordProperty(const std::string& xml_element, | |
| 3731 const TestProperty& test_property) { | |
| 3732 if (!ValidateTestProperty(xml_element, test_property)) { | |
| 3733 return; | |
| 3734 } | |
| 3735 internal::MutexLock lock(&test_properties_mutex_); | |
| 3736 const std::vector<TestProperty>::iterator property_with_matching_key = | |
| 3737 std::find_if(test_properties_.begin(), test_properties_.end(), | |
| 3738 internal::TestPropertyKeyIs(test_property.key())); | |
| 3739 if (property_with_matching_key == test_properties_.end()) { | |
| 3740 test_properties_.push_back(test_property); | |
| 3741 return; | |
| 3742 } | |
| 3743 property_with_matching_key->SetValue(test_property.value()); | |
| 3744 } | |
| 3745 | |
| 3746 // The list of reserved attributes used in the <testsuites> element of XML | |
| 3747 // output. | |
| 3748 static const char* const kReservedTestSuitesAttributes[] = { | |
| 3749 "disabled", | |
| 3750 "errors", | |
| 3751 "failures", | |
| 3752 "name", | |
| 3753 "random_seed", | |
| 3754 "tests", | |
| 3755 "time", | |
| 3756 "timestamp" | |
| 3757 }; | |
| 3758 | |
| 3759 // The list of reserved attributes used in the <testsuite> element of XML | |
| 3760 // output. | |
| 3761 static const char* const kReservedTestSuiteAttributes[] = { | |
| 3762 "disabled", "errors", "failures", "name", | |
| 3763 "tests", "time", "timestamp", "skipped"}; | |
| 3764 | |
| 3765 // The list of reserved attributes used in the <testcase> element of XML output. | |
| 3766 static const char* const kReservedTestCaseAttributes[] = { | |
| 3767 "classname", "name", "status", "time", "type_param", | |
| 3768 "value_param", "file", "line"}; | |
| 3769 | |
| 3770 // Use a slightly different set for allowed output to ensure existing tests can | |
| 3771 // still RecordProperty("result") or "RecordProperty(timestamp") | |
| 3772 static const char* const kReservedOutputTestCaseAttributes[] = { | |
| 3773 "classname", "name", "status", "time", "type_param", | |
| 3774 "value_param", "file", "line", "result", "timestamp"}; | |
| 3775 | |
| 3776 template <size_t kSize> | |
| 3777 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { | |
| 3778 return std::vector<std::string>(array, array + kSize); | |
| 3779 } | |
| 3780 | |
| 3781 static std::vector<std::string> GetReservedAttributesForElement( | |
| 3782 const std::string& xml_element) { | |
| 3783 if (xml_element == "testsuites") { | |
| 3784 return ArrayAsVector(kReservedTestSuitesAttributes); | |
| 3785 } else if (xml_element == "testsuite") { | |
| 3786 return ArrayAsVector(kReservedTestSuiteAttributes); | |
| 3787 } else if (xml_element == "testcase") { | |
| 3788 return ArrayAsVector(kReservedTestCaseAttributes); | |
| 3789 } else { | |
| 3790 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; | |
| 3791 } | |
| 3792 // This code is unreachable but some compilers may not realizes that. | |
| 3793 return std::vector<std::string>(); | |
| 3794 } | |
| 3795 | |
| 3796 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved | |
| 3797 static std::vector<std::string> GetReservedOutputAttributesForElement( | |
| 3798 const std::string& xml_element) { | |
| 3799 if (xml_element == "testsuites") { | |
| 3800 return ArrayAsVector(kReservedTestSuitesAttributes); | |
| 3801 } else if (xml_element == "testsuite") { | |
| 3802 return ArrayAsVector(kReservedTestSuiteAttributes); | |
| 3803 } else if (xml_element == "testcase") { | |
| 3804 return ArrayAsVector(kReservedOutputTestCaseAttributes); | |
| 3805 } else { | |
| 3806 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; | |
| 3807 } | |
| 3808 // This code is unreachable but some compilers may not realizes that. | |
| 3809 return std::vector<std::string>(); | |
| 3810 } | |
| 3811 | |
| 3812 static std::string FormatWordList(const std::vector<std::string>& words) { | |
| 3813 Message word_list; | |
| 3814 for (size_t i = 0; i < words.size(); ++i) { | |
| 3815 if (i > 0 && words.size() > 2) { | |
| 3816 word_list << ", "; | |
| 3817 } | |
| 3818 if (i == words.size() - 1) { | |
| 3819 word_list << "and "; | |
| 3820 } | |
| 3821 word_list << "'" << words[i] << "'"; | |
| 3822 } | |
| 3823 return word_list.GetString(); | |
| 3824 } | |
| 3825 | |
| 3826 static bool ValidateTestPropertyName( | |
| 3827 const std::string& property_name, | |
| 3828 const std::vector<std::string>& reserved_names) { | |
| 3829 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != | |
| 3830 reserved_names.end()) { | |
| 3831 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name | |
| 3832 << " (" << FormatWordList(reserved_names) | |
| 3833 << " are reserved by " << GTEST_NAME_ << ")"; | |
| 3834 return false; | |
| 3835 } | |
| 3836 return true; | |
| 3837 } | |
| 3838 | |
| 3839 // Adds a failure if the key is a reserved attribute of the element named | |
| 3840 // xml_element. Returns true if the property is valid. | |
| 3841 bool TestResult::ValidateTestProperty(const std::string& xml_element, | |
| 3842 const TestProperty& test_property) { | |
| 3843 return ValidateTestPropertyName(test_property.key(), | |
| 3844 GetReservedAttributesForElement(xml_element)); | |
| 3845 } | |
| 3846 | |
| 3847 // Clears the object. | |
| 3848 void TestResult::Clear() { | |
| 3849 test_part_results_.clear(); | |
| 3850 test_properties_.clear(); | |
| 3851 death_test_count_ = 0; | |
| 3852 elapsed_time_ = 0; | |
| 3853 } | |
| 3854 | |
| 3855 // Returns true off the test part was skipped. | |
| 3856 static bool TestPartSkipped(const TestPartResult& result) { | |
| 3857 return result.skipped(); | |
| 3858 } | |
| 3859 | |
| 3860 // Returns true if and only if the test was skipped. | |
| 3861 bool TestResult::Skipped() const { | |
| 3862 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0; | |
| 3863 } | |
| 3864 | |
| 3865 // Returns true if and only if the test failed. | |
| 3866 bool TestResult::Failed() const { | |
| 3867 for (int i = 0; i < total_part_count(); ++i) { | |
| 3868 if (GetTestPartResult(i).failed()) | |
| 3869 return true; | |
| 3870 } | |
| 3871 return false; | |
| 3872 } | |
| 3873 | |
| 3874 // Returns true if and only if the test part fatally failed. | |
| 3875 static bool TestPartFatallyFailed(const TestPartResult& result) { | |
| 3876 return result.fatally_failed(); | |
| 3877 } | |
| 3878 | |
| 3879 // Returns true if and only if the test fatally failed. | |
| 3880 bool TestResult::HasFatalFailure() const { | |
| 3881 return CountIf(test_part_results_, TestPartFatallyFailed) > 0; | |
| 3882 } | |
| 3883 | |
| 3884 // Returns true if and only if the test part non-fatally failed. | |
| 3885 static bool TestPartNonfatallyFailed(const TestPartResult& result) { | |
| 3886 return result.nonfatally_failed(); | |
| 3887 } | |
| 3888 | |
| 3889 // Returns true if and only if the test has a non-fatal failure. | |
| 3890 bool TestResult::HasNonfatalFailure() const { | |
| 3891 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; | |
| 3892 } | |
| 3893 | |
| 3894 // Gets the number of all test parts. This is the sum of the number | |
| 3895 // of successful test parts and the number of failed test parts. | |
| 3896 int TestResult::total_part_count() const { | |
| 3897 return static_cast<int>(test_part_results_.size()); | |
| 3898 } | |
| 3899 | |
| 3900 // Returns the number of the test properties. | |
| 3901 int TestResult::test_property_count() const { | |
| 3902 return static_cast<int>(test_properties_.size()); | |
| 3903 } | |
| 3904 | |
| 3905 // class Test | |
| 3906 | |
| 3907 // Creates a Test object. | |
| 3908 | |
| 3909 // The c'tor saves the states of all flags. | |
| 3910 Test::Test() | |
| 3911 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { | |
| 3912 } | |
| 3913 | |
| 3914 // The d'tor restores the states of all flags. The actual work is | |
| 3915 // done by the d'tor of the gtest_flag_saver_ field, and thus not | |
| 3916 // visible here. | |
| 3917 Test::~Test() { | |
| 3918 } | |
| 3919 | |
| 3920 // Sets up the test fixture. | |
| 3921 // | |
| 3922 // A sub-class may override this. | |
| 3923 void Test::SetUp() { | |
| 3924 } | |
| 3925 | |
| 3926 // Tears down the test fixture. | |
| 3927 // | |
| 3928 // A sub-class may override this. | |
| 3929 void Test::TearDown() { | |
| 3930 } | |
| 3931 | |
| 3932 // Allows user supplied key value pairs to be recorded for later output. | |
| 3933 void Test::RecordProperty(const std::string& key, const std::string& value) { | |
| 3934 UnitTest::GetInstance()->RecordProperty(key, value); | |
| 3935 } | |
| 3936 | |
| 3937 // Allows user supplied key value pairs to be recorded for later output. | |
| 3938 void Test::RecordProperty(const std::string& key, int value) { | |
| 3939 Message value_message; | |
| 3940 value_message << value; | |
| 3941 RecordProperty(key, value_message.GetString().c_str()); | |
| 3942 } | |
| 3943 | |
| 3944 namespace internal { | |
| 3945 | |
| 3946 void ReportFailureInUnknownLocation(TestPartResult::Type result_type, | |
| 3947 const std::string& message) { | |
| 3948 // This function is a friend of UnitTest and as such has access to | |
| 3949 // AddTestPartResult. | |
| 3950 UnitTest::GetInstance()->AddTestPartResult( | |
| 3951 result_type, | |
| 3952 nullptr, // No info about the source file where the exception occurred. | |
| 3953 -1, // We have no info on which line caused the exception. | |
| 3954 message, | |
| 3955 ""); // No stack trace, either. | |
| 3956 } | |
| 3957 | |
| 3958 } // namespace internal | |
| 3959 | |
| 3960 // Google Test requires all tests in the same test suite to use the same test | |
| 3961 // fixture class. This function checks if the current test has the | |
| 3962 // same fixture class as the first test in the current test suite. If | |
| 3963 // yes, it returns true; otherwise it generates a Google Test failure and | |
| 3964 // returns false. | |
| 3965 bool Test::HasSameFixtureClass() { | |
| 3966 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 3967 const TestSuite* const test_suite = impl->current_test_suite(); | |
| 3968 | |
| 3969 // Info about the first test in the current test suite. | |
| 3970 const TestInfo* const first_test_info = test_suite->test_info_list()[0]; | |
| 3971 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; | |
| 3972 const char* const first_test_name = first_test_info->name(); | |
| 3973 | |
| 3974 // Info about the current test. | |
| 3975 const TestInfo* const this_test_info = impl->current_test_info(); | |
| 3976 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; | |
| 3977 const char* const this_test_name = this_test_info->name(); | |
| 3978 | |
| 3979 if (this_fixture_id != first_fixture_id) { | |
| 3980 // Is the first test defined using TEST? | |
| 3981 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); | |
| 3982 // Is this test defined using TEST? | |
| 3983 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); | |
| 3984 | |
| 3985 if (first_is_TEST || this_is_TEST) { | |
| 3986 // Both TEST and TEST_F appear in same test suite, which is incorrect. | |
| 3987 // Tell the user how to fix this. | |
| 3988 | |
| 3989 // Gets the name of the TEST and the name of the TEST_F. Note | |
| 3990 // that first_is_TEST and this_is_TEST cannot both be true, as | |
| 3991 // the fixture IDs are different for the two tests. | |
| 3992 const char* const TEST_name = | |
| 3993 first_is_TEST ? first_test_name : this_test_name; | |
| 3994 const char* const TEST_F_name = | |
| 3995 first_is_TEST ? this_test_name : first_test_name; | |
| 3996 | |
| 3997 ADD_FAILURE() | |
| 3998 << "All tests in the same test suite must use the same test fixture\n" | |
| 3999 << "class, so mixing TEST_F and TEST in the same test suite is\n" | |
| 4000 << "illegal. In test suite " << this_test_info->test_suite_name() | |
| 4001 << ",\n" | |
| 4002 << "test " << TEST_F_name << " is defined using TEST_F but\n" | |
| 4003 << "test " << TEST_name << " is defined using TEST. You probably\n" | |
| 4004 << "want to change the TEST to TEST_F or move it to another test\n" | |
| 4005 << "case."; | |
| 4006 } else { | |
| 4007 // Two fixture classes with the same name appear in two different | |
| 4008 // namespaces, which is not allowed. Tell the user how to fix this. | |
| 4009 ADD_FAILURE() | |
| 4010 << "All tests in the same test suite must use the same test fixture\n" | |
| 4011 << "class. However, in test suite " | |
| 4012 << this_test_info->test_suite_name() << ",\n" | |
| 4013 << "you defined test " << first_test_name << " and test " | |
| 4014 << this_test_name << "\n" | |
| 4015 << "using two different test fixture classes. This can happen if\n" | |
| 4016 << "the two classes are from different namespaces or translation\n" | |
| 4017 << "units and have the same name. You should probably rename one\n" | |
| 4018 << "of the classes to put the tests into different test suites."; | |
| 4019 } | |
| 4020 return false; | |
| 4021 } | |
| 4022 | |
| 4023 return true; | |
| 4024 } | |
| 4025 | |
| 4026 #if GTEST_HAS_SEH | |
| 4027 | |
| 4028 // Adds an "exception thrown" fatal failure to the current test. This | |
| 4029 // function returns its result via an output parameter pointer because VC++ | |
| 4030 // prohibits creation of objects with destructors on stack in functions | |
| 4031 // using __try (see error C2712). | |
| 4032 static std::string* FormatSehExceptionMessage(DWORD exception_code, | |
| 4033 const char* location) { | |
| 4034 Message message; | |
| 4035 message << "SEH exception with code 0x" << std::setbase(16) << | |
| 4036 exception_code << std::setbase(10) << " thrown in " << location << "."; | |
| 4037 | |
| 4038 return new std::string(message.GetString()); | |
| 4039 } | |
| 4040 | |
| 4041 #endif // GTEST_HAS_SEH | |
| 4042 | |
| 4043 namespace internal { | |
| 4044 | |
| 4045 #if GTEST_HAS_EXCEPTIONS | |
| 4046 | |
| 4047 // Adds an "exception thrown" fatal failure to the current test. | |
| 4048 static std::string FormatCxxExceptionMessage(const char* description, | |
| 4049 const char* location) { | |
| 4050 Message message; | |
| 4051 if (description != nullptr) { | |
| 4052 message << "C++ exception with description \"" << description << "\""; | |
| 4053 } else { | |
| 4054 message << "Unknown C++ exception"; | |
| 4055 } | |
| 4056 message << " thrown in " << location << "."; | |
| 4057 | |
| 4058 return message.GetString(); | |
| 4059 } | |
| 4060 | |
| 4061 static std::string PrintTestPartResultToString( | |
| 4062 const TestPartResult& test_part_result); | |
| 4063 | |
| 4064 GoogleTestFailureException::GoogleTestFailureException( | |
| 4065 const TestPartResult& failure) | |
| 4066 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} | |
| 4067 | |
| 4068 #endif // GTEST_HAS_EXCEPTIONS | |
| 4069 | |
| 4070 // We put these helper functions in the internal namespace as IBM's xlC | |
| 4071 // compiler rejects the code if they were declared static. | |
| 4072 | |
| 4073 // Runs the given method and handles SEH exceptions it throws, when | |
| 4074 // SEH is supported; returns the 0-value for type Result in case of an | |
| 4075 // SEH exception. (Microsoft compilers cannot handle SEH and C++ | |
| 4076 // exceptions in the same function. Therefore, we provide a separate | |
| 4077 // wrapper function for handling SEH exceptions.) | |
| 4078 template <class T, typename Result> | |
| 4079 Result HandleSehExceptionsInMethodIfSupported( | |
| 4080 T* object, Result (T::*method)(), const char* location) { | |
| 4081 #if GTEST_HAS_SEH | |
| 4082 __try { | |
| 4083 return (object->*method)(); | |
| 4084 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT | |
| 4085 GetExceptionCode())) { | |
| 4086 // We create the exception message on the heap because VC++ prohibits | |
| 4087 // creation of objects with destructors on stack in functions using __try | |
| 4088 // (see error C2712). | |
| 4089 std::string* exception_message = FormatSehExceptionMessage( | |
| 4090 GetExceptionCode(), location); | |
| 4091 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, | |
| 4092 *exception_message); | |
| 4093 delete exception_message; | |
| 4094 return static_cast<Result>(0); | |
| 4095 } | |
| 4096 #else | |
| 4097 (void)location; | |
| 4098 return (object->*method)(); | |
| 4099 #endif // GTEST_HAS_SEH | |
| 4100 } | |
| 4101 | |
| 4102 // Runs the given method and catches and reports C++ and/or SEH-style | |
| 4103 // exceptions, if they are supported; returns the 0-value for type | |
| 4104 // Result in case of an SEH exception. | |
| 4105 template <class T, typename Result> | |
| 4106 Result HandleExceptionsInMethodIfSupported( | |
| 4107 T* object, Result (T::*method)(), const char* location) { | |
| 4108 // NOTE: The user code can affect the way in which Google Test handles | |
| 4109 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before | |
| 4110 // RUN_ALL_TESTS() starts. It is technically possible to check the flag | |
| 4111 // after the exception is caught and either report or re-throw the | |
| 4112 // exception based on the flag's value: | |
| 4113 // | |
| 4114 // try { | |
| 4115 // // Perform the test method. | |
| 4116 // } catch (...) { | |
| 4117 // if (GTEST_FLAG(catch_exceptions)) | |
| 4118 // // Report the exception as failure. | |
| 4119 // else | |
| 4120 // throw; // Re-throws the original exception. | |
| 4121 // } | |
| 4122 // | |
| 4123 // However, the purpose of this flag is to allow the program to drop into | |
| 4124 // the debugger when the exception is thrown. On most platforms, once the | |
| 4125 // control enters the catch block, the exception origin information is | |
| 4126 // lost and the debugger will stop the program at the point of the | |
| 4127 // re-throw in this function -- instead of at the point of the original | |
| 4128 // throw statement in the code under test. For this reason, we perform | |
| 4129 // the check early, sacrificing the ability to affect Google Test's | |
| 4130 // exception handling in the method where the exception is thrown. | |
| 4131 if (internal::GetUnitTestImpl()->catch_exceptions()) { | |
| 4132 #if GTEST_HAS_EXCEPTIONS | |
| 4133 try { | |
| 4134 return HandleSehExceptionsInMethodIfSupported(object, method, location); | |
| 4135 } catch (const AssertionException&) { // NOLINT | |
| 4136 // This failure was reported already. | |
| 4137 } catch (const internal::GoogleTestFailureException&) { // NOLINT | |
| 4138 // This exception type can only be thrown by a failed Google | |
| 4139 // Test assertion with the intention of letting another testing | |
| 4140 // framework catch it. Therefore we just re-throw it. | |
| 4141 throw; | |
| 4142 } catch (const std::exception& e) { // NOLINT | |
| 4143 internal::ReportFailureInUnknownLocation( | |
| 4144 TestPartResult::kFatalFailure, | |
| 4145 FormatCxxExceptionMessage(e.what(), location)); | |
| 4146 } catch (...) { // NOLINT | |
| 4147 internal::ReportFailureInUnknownLocation( | |
| 4148 TestPartResult::kFatalFailure, | |
| 4149 FormatCxxExceptionMessage(nullptr, location)); | |
| 4150 } | |
| 4151 return static_cast<Result>(0); | |
| 4152 #else | |
| 4153 return HandleSehExceptionsInMethodIfSupported(object, method, location); | |
| 4154 #endif // GTEST_HAS_EXCEPTIONS | |
| 4155 } else { | |
| 4156 return (object->*method)(); | |
| 4157 } | |
| 4158 } | |
| 4159 | |
| 4160 } // namespace internal | |
| 4161 | |
| 4162 // Runs the test and updates the test result. | |
| 4163 void Test::Run() { | |
| 4164 if (!HasSameFixtureClass()) return; | |
| 4165 | |
| 4166 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 4167 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4168 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); | |
| 4169 // We will run the test only if SetUp() was successful and didn't call | |
| 4170 // GTEST_SKIP(). | |
| 4171 if (!HasFatalFailure() && !IsSkipped()) { | |
| 4172 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4173 internal::HandleExceptionsInMethodIfSupported( | |
| 4174 this, &Test::TestBody, "the test body"); | |
| 4175 } | |
| 4176 | |
| 4177 // However, we want to clean up as much as possible. Hence we will | |
| 4178 // always call TearDown(), even if SetUp() or the test body has | |
| 4179 // failed. | |
| 4180 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4181 internal::HandleExceptionsInMethodIfSupported( | |
| 4182 this, &Test::TearDown, "TearDown()"); | |
| 4183 } | |
| 4184 | |
| 4185 // Returns true if and only if the current test has a fatal failure. | |
| 4186 bool Test::HasFatalFailure() { | |
| 4187 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); | |
| 4188 } | |
| 4189 | |
| 4190 // Returns true if and only if the current test has a non-fatal failure. | |
| 4191 bool Test::HasNonfatalFailure() { | |
| 4192 return internal::GetUnitTestImpl()->current_test_result()-> | |
| 4193 HasNonfatalFailure(); | |
| 4194 } | |
| 4195 | |
| 4196 // Returns true if and only if the current test was skipped. | |
| 4197 bool Test::IsSkipped() { | |
| 4198 return internal::GetUnitTestImpl()->current_test_result()->Skipped(); | |
| 4199 } | |
| 4200 | |
| 4201 // class TestInfo | |
| 4202 | |
| 4203 // Constructs a TestInfo object. It assumes ownership of the test factory | |
| 4204 // object. | |
| 4205 TestInfo::TestInfo(const std::string& a_test_suite_name, | |
| 4206 const std::string& a_name, const char* a_type_param, | |
| 4207 const char* a_value_param, | |
| 4208 internal::CodeLocation a_code_location, | |
| 4209 internal::TypeId fixture_class_id, | |
| 4210 internal::TestFactoryBase* factory) | |
| 4211 : test_suite_name_(a_test_suite_name), | |
| 4212 name_(a_name), | |
| 4213 type_param_(a_type_param ? new std::string(a_type_param) : nullptr), | |
| 4214 value_param_(a_value_param ? new std::string(a_value_param) : nullptr), | |
| 4215 location_(a_code_location), | |
| 4216 fixture_class_id_(fixture_class_id), | |
| 4217 should_run_(false), | |
| 4218 is_disabled_(false), | |
| 4219 matches_filter_(false), | |
| 4220 is_in_another_shard_(false), | |
| 4221 factory_(factory), | |
| 4222 result_() {} | |
| 4223 | |
| 4224 // Destructs a TestInfo object. | |
| 4225 TestInfo::~TestInfo() { delete factory_; } | |
| 4226 | |
| 4227 namespace internal { | |
| 4228 | |
| 4229 // Creates a new TestInfo object and registers it with Google Test; | |
| 4230 // returns the created object. | |
| 4231 // | |
| 4232 // Arguments: | |
| 4233 // | |
| 4234 // test_suite_name: name of the test suite | |
| 4235 // name: name of the test | |
| 4236 // type_param: the name of the test's type parameter, or NULL if | |
| 4237 // this is not a typed or a type-parameterized test. | |
| 4238 // value_param: text representation of the test's value parameter, | |
| 4239 // or NULL if this is not a value-parameterized test. | |
| 4240 // code_location: code location where the test is defined | |
| 4241 // fixture_class_id: ID of the test fixture class | |
| 4242 // set_up_tc: pointer to the function that sets up the test suite | |
| 4243 // tear_down_tc: pointer to the function that tears down the test suite | |
| 4244 // factory: pointer to the factory that creates a test object. | |
| 4245 // The newly created TestInfo instance will assume | |
| 4246 // ownership of the factory object. | |
| 4247 TestInfo* MakeAndRegisterTestInfo( | |
| 4248 const char* test_suite_name, const char* name, const char* type_param, | |
| 4249 const char* value_param, CodeLocation code_location, | |
| 4250 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, | |
| 4251 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { | |
| 4252 TestInfo* const test_info = | |
| 4253 new TestInfo(test_suite_name, name, type_param, value_param, | |
| 4254 code_location, fixture_class_id, factory); | |
| 4255 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); | |
| 4256 return test_info; | |
| 4257 } | |
| 4258 | |
| 4259 void ReportInvalidTestSuiteType(const char* test_suite_name, | |
| 4260 CodeLocation code_location) { | |
| 4261 Message errors; | |
| 4262 errors | |
| 4263 << "Attempted redefinition of test suite " << test_suite_name << ".\n" | |
| 4264 << "All tests in the same test suite must use the same test fixture\n" | |
| 4265 << "class. However, in test suite " << test_suite_name << ", you tried\n" | |
| 4266 << "to define a test using a fixture class different from the one\n" | |
| 4267 << "used earlier. This can happen if the two fixture classes are\n" | |
| 4268 << "from different namespaces and have the same name. You should\n" | |
| 4269 << "probably rename one of the classes to put the tests into different\n" | |
| 4270 << "test suites."; | |
| 4271 | |
| 4272 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(), | |
| 4273 code_location.line) | |
| 4274 << " " << errors.GetString(); | |
| 4275 } | |
| 4276 } // namespace internal | |
| 4277 | |
| 4278 namespace { | |
| 4279 | |
| 4280 // A predicate that checks the test name of a TestInfo against a known | |
| 4281 // value. | |
| 4282 // | |
| 4283 // This is used for implementation of the TestSuite class only. We put | |
| 4284 // it in the anonymous namespace to prevent polluting the outer | |
| 4285 // namespace. | |
| 4286 // | |
| 4287 // TestNameIs is copyable. | |
| 4288 class TestNameIs { | |
| 4289 public: | |
| 4290 // Constructor. | |
| 4291 // | |
| 4292 // TestNameIs has NO default constructor. | |
| 4293 explicit TestNameIs(const char* name) | |
| 4294 : name_(name) {} | |
| 4295 | |
| 4296 // Returns true if and only if the test name of test_info matches name_. | |
| 4297 bool operator()(const TestInfo * test_info) const { | |
| 4298 return test_info && test_info->name() == name_; | |
| 4299 } | |
| 4300 | |
| 4301 private: | |
| 4302 std::string name_; | |
| 4303 }; | |
| 4304 | |
| 4305 } // namespace | |
| 4306 | |
| 4307 namespace internal { | |
| 4308 | |
| 4309 // This method expands all parameterized tests registered with macros TEST_P | |
| 4310 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those. | |
| 4311 // This will be done just once during the program runtime. | |
| 4312 void UnitTestImpl::RegisterParameterizedTests() { | |
| 4313 if (!parameterized_tests_registered_) { | |
| 4314 parameterized_test_registry_.RegisterTests(); | |
| 4315 type_parameterized_test_registry_.CheckForInstantiations(); | |
| 4316 parameterized_tests_registered_ = true; | |
| 4317 } | |
| 4318 } | |
| 4319 | |
| 4320 } // namespace internal | |
| 4321 | |
| 4322 // Creates the test object, runs it, records its result, and then | |
| 4323 // deletes it. | |
| 4324 void TestInfo::Run() { | |
| 4325 if (!should_run_) return; | |
| 4326 | |
| 4327 // Tells UnitTest where to store test result. | |
| 4328 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 4329 impl->set_current_test_info(this); | |
| 4330 | |
| 4331 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); | |
| 4332 | |
| 4333 // Notifies the unit test event listeners that a test is about to start. | |
| 4334 repeater->OnTestStart(*this); | |
| 4335 | |
| 4336 result_.set_start_timestamp(internal::GetTimeInMillis()); | |
| 4337 internal::Timer timer; | |
| 4338 | |
| 4339 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4340 | |
| 4341 // Creates the test object. | |
| 4342 Test* const test = internal::HandleExceptionsInMethodIfSupported( | |
| 4343 factory_, &internal::TestFactoryBase::CreateTest, | |
| 4344 "the test fixture's constructor"); | |
| 4345 | |
| 4346 // Runs the test if the constructor didn't generate a fatal failure or invoke | |
| 4347 // GTEST_SKIP(). | |
| 4348 // Note that the object will not be null | |
| 4349 if (!Test::HasFatalFailure() && !Test::IsSkipped()) { | |
| 4350 // This doesn't throw as all user code that can throw are wrapped into | |
| 4351 // exception handling code. | |
| 4352 test->Run(); | |
| 4353 } | |
| 4354 | |
| 4355 if (test != nullptr) { | |
| 4356 // Deletes the test object. | |
| 4357 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4358 internal::HandleExceptionsInMethodIfSupported( | |
| 4359 test, &Test::DeleteSelf_, "the test fixture's destructor"); | |
| 4360 } | |
| 4361 | |
| 4362 result_.set_elapsed_time(timer.Elapsed()); | |
| 4363 | |
| 4364 // Notifies the unit test event listener that a test has just finished. | |
| 4365 repeater->OnTestEnd(*this); | |
| 4366 | |
| 4367 // Tells UnitTest to stop associating assertion results to this | |
| 4368 // test. | |
| 4369 impl->set_current_test_info(nullptr); | |
| 4370 } | |
| 4371 | |
| 4372 // Skip and records a skipped test result for this object. | |
| 4373 void TestInfo::Skip() { | |
| 4374 if (!should_run_) return; | |
| 4375 | |
| 4376 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 4377 impl->set_current_test_info(this); | |
| 4378 | |
| 4379 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); | |
| 4380 | |
| 4381 // Notifies the unit test event listeners that a test is about to start. | |
| 4382 repeater->OnTestStart(*this); | |
| 4383 | |
| 4384 const TestPartResult test_part_result = | |
| 4385 TestPartResult(TestPartResult::kSkip, this->file(), this->line(), ""); | |
| 4386 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( | |
| 4387 test_part_result); | |
| 4388 | |
| 4389 // Notifies the unit test event listener that a test has just finished. | |
| 4390 repeater->OnTestEnd(*this); | |
| 4391 impl->set_current_test_info(nullptr); | |
| 4392 } | |
| 4393 | |
| 4394 // class TestSuite | |
| 4395 | |
| 4396 // Gets the number of successful tests in this test suite. | |
| 4397 int TestSuite::successful_test_count() const { | |
| 4398 return CountIf(test_info_list_, TestPassed); | |
| 4399 } | |
| 4400 | |
| 4401 // Gets the number of successful tests in this test suite. | |
| 4402 int TestSuite::skipped_test_count() const { | |
| 4403 return CountIf(test_info_list_, TestSkipped); | |
| 4404 } | |
| 4405 | |
| 4406 // Gets the number of failed tests in this test suite. | |
| 4407 int TestSuite::failed_test_count() const { | |
| 4408 return CountIf(test_info_list_, TestFailed); | |
| 4409 } | |
| 4410 | |
| 4411 // Gets the number of disabled tests that will be reported in the XML report. | |
| 4412 int TestSuite::reportable_disabled_test_count() const { | |
| 4413 return CountIf(test_info_list_, TestReportableDisabled); | |
| 4414 } | |
| 4415 | |
| 4416 // Gets the number of disabled tests in this test suite. | |
| 4417 int TestSuite::disabled_test_count() const { | |
| 4418 return CountIf(test_info_list_, TestDisabled); | |
| 4419 } | |
| 4420 | |
| 4421 // Gets the number of tests to be printed in the XML report. | |
| 4422 int TestSuite::reportable_test_count() const { | |
| 4423 return CountIf(test_info_list_, TestReportable); | |
| 4424 } | |
| 4425 | |
| 4426 // Get the number of tests in this test suite that should run. | |
| 4427 int TestSuite::test_to_run_count() const { | |
| 4428 return CountIf(test_info_list_, ShouldRunTest); | |
| 4429 } | |
| 4430 | |
| 4431 // Gets the number of all tests. | |
| 4432 int TestSuite::total_test_count() const { | |
| 4433 return static_cast<int>(test_info_list_.size()); | |
| 4434 } | |
| 4435 | |
| 4436 // Creates a TestSuite with the given name. | |
| 4437 // | |
| 4438 // Arguments: | |
| 4439 // | |
| 4440 // a_name: name of the test suite | |
| 4441 // a_type_param: the name of the test suite's type parameter, or NULL if | |
| 4442 // this is not a typed or a type-parameterized test suite. | |
| 4443 // set_up_tc: pointer to the function that sets up the test suite | |
| 4444 // tear_down_tc: pointer to the function that tears down the test suite | |
| 4445 TestSuite::TestSuite(const char* a_name, const char* a_type_param, | |
| 4446 internal::SetUpTestSuiteFunc set_up_tc, | |
| 4447 internal::TearDownTestSuiteFunc tear_down_tc) | |
| 4448 : name_(a_name), | |
| 4449 type_param_(a_type_param ? new std::string(a_type_param) : nullptr), | |
| 4450 set_up_tc_(set_up_tc), | |
| 4451 tear_down_tc_(tear_down_tc), | |
| 4452 should_run_(false), | |
| 4453 start_timestamp_(0), | |
| 4454 elapsed_time_(0) {} | |
| 4455 | |
| 4456 // Destructor of TestSuite. | |
| 4457 TestSuite::~TestSuite() { | |
| 4458 // Deletes every Test in the collection. | |
| 4459 ForEach(test_info_list_, internal::Delete<TestInfo>); | |
| 4460 } | |
| 4461 | |
| 4462 // Returns the i-th test among all the tests. i can range from 0 to | |
| 4463 // total_test_count() - 1. If i is not in that range, returns NULL. | |
| 4464 const TestInfo* TestSuite::GetTestInfo(int i) const { | |
| 4465 const int index = GetElementOr(test_indices_, i, -1); | |
| 4466 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)]; | |
| 4467 } | |
| 4468 | |
| 4469 // Returns the i-th test among all the tests. i can range from 0 to | |
| 4470 // total_test_count() - 1. If i is not in that range, returns NULL. | |
| 4471 TestInfo* TestSuite::GetMutableTestInfo(int i) { | |
| 4472 const int index = GetElementOr(test_indices_, i, -1); | |
| 4473 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)]; | |
| 4474 } | |
| 4475 | |
| 4476 // Adds a test to this test suite. Will delete the test upon | |
| 4477 // destruction of the TestSuite object. | |
| 4478 void TestSuite::AddTestInfo(TestInfo* test_info) { | |
| 4479 test_info_list_.push_back(test_info); | |
| 4480 test_indices_.push_back(static_cast<int>(test_indices_.size())); | |
| 4481 } | |
| 4482 | |
| 4483 // Runs every test in this TestSuite. | |
| 4484 void TestSuite::Run() { | |
| 4485 if (!should_run_) return; | |
| 4486 | |
| 4487 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 4488 impl->set_current_test_suite(this); | |
| 4489 | |
| 4490 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); | |
| 4491 | |
| 4492 // Call both legacy and the new API | |
| 4493 repeater->OnTestSuiteStart(*this); | |
| 4494 // Legacy API is deprecated but still available | |
| 4495 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4496 repeater->OnTestCaseStart(*this); | |
| 4497 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4498 | |
| 4499 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4500 internal::HandleExceptionsInMethodIfSupported( | |
| 4501 this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); | |
| 4502 | |
| 4503 start_timestamp_ = internal::GetTimeInMillis(); | |
| 4504 internal::Timer timer; | |
| 4505 for (int i = 0; i < total_test_count(); i++) { | |
| 4506 GetMutableTestInfo(i)->Run(); | |
| 4507 if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) { | |
| 4508 for (int j = i + 1; j < total_test_count(); j++) { | |
| 4509 GetMutableTestInfo(j)->Skip(); | |
| 4510 } | |
| 4511 break; | |
| 4512 } | |
| 4513 } | |
| 4514 elapsed_time_ = timer.Elapsed(); | |
| 4515 | |
| 4516 impl->os_stack_trace_getter()->UponLeavingGTest(); | |
| 4517 internal::HandleExceptionsInMethodIfSupported( | |
| 4518 this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); | |
| 4519 | |
| 4520 // Call both legacy and the new API | |
| 4521 repeater->OnTestSuiteEnd(*this); | |
| 4522 // Legacy API is deprecated but still available | |
| 4523 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4524 repeater->OnTestCaseEnd(*this); | |
| 4525 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4526 | |
| 4527 impl->set_current_test_suite(nullptr); | |
| 4528 } | |
| 4529 | |
| 4530 // Skips all tests under this TestSuite. | |
| 4531 void TestSuite::Skip() { | |
| 4532 if (!should_run_) return; | |
| 4533 | |
| 4534 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); | |
| 4535 impl->set_current_test_suite(this); | |
| 4536 | |
| 4537 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); | |
| 4538 | |
| 4539 // Call both legacy and the new API | |
| 4540 repeater->OnTestSuiteStart(*this); | |
| 4541 // Legacy API is deprecated but still available | |
| 4542 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4543 repeater->OnTestCaseStart(*this); | |
| 4544 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4545 | |
| 4546 for (int i = 0; i < total_test_count(); i++) { | |
| 4547 GetMutableTestInfo(i)->Skip(); | |
| 4548 } | |
| 4549 | |
| 4550 // Call both legacy and the new API | |
| 4551 repeater->OnTestSuiteEnd(*this); | |
| 4552 // Legacy API is deprecated but still available | |
| 4553 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4554 repeater->OnTestCaseEnd(*this); | |
| 4555 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4556 | |
| 4557 impl->set_current_test_suite(nullptr); | |
| 4558 } | |
| 4559 | |
| 4560 // Clears the results of all tests in this test suite. | |
| 4561 void TestSuite::ClearResult() { | |
| 4562 ad_hoc_test_result_.Clear(); | |
| 4563 ForEach(test_info_list_, TestInfo::ClearTestResult); | |
| 4564 } | |
| 4565 | |
| 4566 // Shuffles the tests in this test suite. | |
| 4567 void TestSuite::ShuffleTests(internal::Random* random) { | |
| 4568 Shuffle(random, &test_indices_); | |
| 4569 } | |
| 4570 | |
| 4571 // Restores the test order to before the first shuffle. | |
| 4572 void TestSuite::UnshuffleTests() { | |
| 4573 for (size_t i = 0; i < test_indices_.size(); i++) { | |
| 4574 test_indices_[i] = static_cast<int>(i); | |
| 4575 } | |
| 4576 } | |
| 4577 | |
| 4578 // Formats a countable noun. Depending on its quantity, either the | |
| 4579 // singular form or the plural form is used. e.g. | |
| 4580 // | |
| 4581 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". | |
| 4582 // FormatCountableNoun(5, "book", "books") returns "5 books". | |
| 4583 static std::string FormatCountableNoun(int count, | |
| 4584 const char * singular_form, | |
| 4585 const char * plural_form) { | |
| 4586 return internal::StreamableToString(count) + " " + | |
| 4587 (count == 1 ? singular_form : plural_form); | |
| 4588 } | |
| 4589 | |
| 4590 // Formats the count of tests. | |
| 4591 static std::string FormatTestCount(int test_count) { | |
| 4592 return FormatCountableNoun(test_count, "test", "tests"); | |
| 4593 } | |
| 4594 | |
| 4595 // Formats the count of test suites. | |
| 4596 static std::string FormatTestSuiteCount(int test_suite_count) { | |
| 4597 return FormatCountableNoun(test_suite_count, "test suite", "test suites"); | |
| 4598 } | |
| 4599 | |
| 4600 // Converts a TestPartResult::Type enum to human-friendly string | |
| 4601 // representation. Both kNonFatalFailure and kFatalFailure are translated | |
| 4602 // to "Failure", as the user usually doesn't care about the difference | |
| 4603 // between the two when viewing the test result. | |
| 4604 static const char * TestPartResultTypeToString(TestPartResult::Type type) { | |
| 4605 switch (type) { | |
| 4606 case TestPartResult::kSkip: | |
| 4607 return "Skipped\n"; | |
| 4608 case TestPartResult::kSuccess: | |
| 4609 return "Success"; | |
| 4610 | |
| 4611 case TestPartResult::kNonFatalFailure: | |
| 4612 case TestPartResult::kFatalFailure: | |
| 4613 #ifdef _MSC_VER | |
| 4614 return "error: "; | |
| 4615 #else | |
| 4616 return "Failure\n"; | |
| 4617 #endif | |
| 4618 default: | |
| 4619 return "Unknown result type"; | |
| 4620 } | |
| 4621 } | |
| 4622 | |
| 4623 namespace internal { | |
| 4624 namespace { | |
| 4625 enum class GTestColor { kDefault, kRed, kGreen, kYellow }; | |
| 4626 } // namespace | |
| 4627 | |
| 4628 // Prints a TestPartResult to an std::string. | |
| 4629 static std::string PrintTestPartResultToString( | |
| 4630 const TestPartResult& test_part_result) { | |
| 4631 return (Message() | |
| 4632 << internal::FormatFileLocation(test_part_result.file_name(), | |
| 4633 test_part_result.line_number()) | |
| 4634 << " " << TestPartResultTypeToString(test_part_result.type()) | |
| 4635 << test_part_result.message()).GetString(); | |
| 4636 } | |
| 4637 | |
| 4638 // Prints a TestPartResult. | |
| 4639 static void PrintTestPartResult(const TestPartResult& test_part_result) { | |
| 4640 const std::string& result = | |
| 4641 PrintTestPartResultToString(test_part_result); | |
| 4642 printf("%s\n", result.c_str()); | |
| 4643 fflush(stdout); | |
| 4644 // If the test program runs in Visual Studio or a debugger, the | |
| 4645 // following statements add the test part result message to the Output | |
| 4646 // window such that the user can double-click on it to jump to the | |
| 4647 // corresponding source code location; otherwise they do nothing. | |
| 4648 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE | |
| 4649 // We don't call OutputDebugString*() on Windows Mobile, as printing | |
| 4650 // to stdout is done by OutputDebugString() there already - we don't | |
| 4651 // want the same message printed twice. | |
| 4652 ::OutputDebugStringA(result.c_str()); | |
| 4653 ::OutputDebugStringA("\n"); | |
| 4654 #endif | |
| 4655 } | |
| 4656 | |
| 4657 // class PrettyUnitTestResultPrinter | |
| 4658 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ | |
| 4659 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW | |
| 4660 | |
| 4661 // Returns the character attribute for the given color. | |
| 4662 static WORD GetColorAttribute(GTestColor color) { | |
| 4663 switch (color) { | |
| 4664 case GTestColor::kRed: | |
| 4665 return FOREGROUND_RED; | |
| 4666 case GTestColor::kGreen: | |
| 4667 return FOREGROUND_GREEN; | |
| 4668 case GTestColor::kYellow: | |
| 4669 return FOREGROUND_RED | FOREGROUND_GREEN; | |
| 4670 default: return 0; | |
| 4671 } | |
| 4672 } | |
| 4673 | |
| 4674 static int GetBitOffset(WORD color_mask) { | |
| 4675 if (color_mask == 0) return 0; | |
| 4676 | |
| 4677 int bitOffset = 0; | |
| 4678 while ((color_mask & 1) == 0) { | |
| 4679 color_mask >>= 1; | |
| 4680 ++bitOffset; | |
| 4681 } | |
| 4682 return bitOffset; | |
| 4683 } | |
| 4684 | |
| 4685 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) { | |
| 4686 // Let's reuse the BG | |
| 4687 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | | |
| 4688 BACKGROUND_RED | BACKGROUND_INTENSITY; | |
| 4689 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | | |
| 4690 FOREGROUND_RED | FOREGROUND_INTENSITY; | |
| 4691 const WORD existing_bg = old_color_attrs & background_mask; | |
| 4692 | |
| 4693 WORD new_color = | |
| 4694 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; | |
| 4695 static const int bg_bitOffset = GetBitOffset(background_mask); | |
| 4696 static const int fg_bitOffset = GetBitOffset(foreground_mask); | |
| 4697 | |
| 4698 if (((new_color & background_mask) >> bg_bitOffset) == | |
| 4699 ((new_color & foreground_mask) >> fg_bitOffset)) { | |
| 4700 new_color ^= FOREGROUND_INTENSITY; // invert intensity | |
| 4701 } | |
| 4702 return new_color; | |
| 4703 } | |
| 4704 | |
| 4705 #else | |
| 4706 | |
| 4707 // Returns the ANSI color code for the given color. GTestColor::kDefault is | |
| 4708 // an invalid input. | |
| 4709 static const char* GetAnsiColorCode(GTestColor color) { | |
| 4710 switch (color) { | |
| 4711 case GTestColor::kRed: | |
| 4712 return "1"; | |
| 4713 case GTestColor::kGreen: | |
| 4714 return "2"; | |
| 4715 case GTestColor::kYellow: | |
| 4716 return "3"; | |
| 4717 default: | |
| 4718 return nullptr; | |
| 4719 } | |
| 4720 } | |
| 4721 | |
| 4722 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE | |
| 4723 | |
| 4724 // Returns true if and only if Google Test should use colors in the output. | |
| 4725 bool ShouldUseColor(bool stdout_is_tty) { | |
| 4726 const char* const gtest_color = GTEST_FLAG(color).c_str(); | |
| 4727 | |
| 4728 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { | |
| 4729 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW | |
| 4730 // On Windows the TERM variable is usually not set, but the | |
| 4731 // console there does support colors. | |
| 4732 return stdout_is_tty; | |
| 4733 #else | |
| 4734 // On non-Windows platforms, we rely on the TERM variable. | |
| 4735 const char* const term = posix::GetEnv("TERM"); | |
| 4736 const bool term_supports_color = | |
| 4737 String::CStringEquals(term, "xterm") || | |
| 4738 String::CStringEquals(term, "xterm-color") || | |
| 4739 String::CStringEquals(term, "xterm-256color") || | |
| 4740 String::CStringEquals(term, "screen") || | |
| 4741 String::CStringEquals(term, "screen-256color") || | |
| 4742 String::CStringEquals(term, "tmux") || | |
| 4743 String::CStringEquals(term, "tmux-256color") || | |
| 4744 String::CStringEquals(term, "rxvt-unicode") || | |
| 4745 String::CStringEquals(term, "rxvt-unicode-256color") || | |
| 4746 String::CStringEquals(term, "linux") || | |
| 4747 String::CStringEquals(term, "cygwin"); | |
| 4748 return stdout_is_tty && term_supports_color; | |
| 4749 #endif // GTEST_OS_WINDOWS | |
| 4750 } | |
| 4751 | |
| 4752 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || | |
| 4753 String::CaseInsensitiveCStringEquals(gtest_color, "true") || | |
| 4754 String::CaseInsensitiveCStringEquals(gtest_color, "t") || | |
| 4755 String::CStringEquals(gtest_color, "1"); | |
| 4756 // We take "yes", "true", "t", and "1" as meaning "yes". If the | |
| 4757 // value is neither one of these nor "auto", we treat it as "no" to | |
| 4758 // be conservative. | |
| 4759 } | |
| 4760 | |
| 4761 // Helpers for printing colored strings to stdout. Note that on Windows, we | |
| 4762 // cannot simply emit special characters and have the terminal change colors. | |
| 4763 // This routine must actually emit the characters rather than return a string | |
| 4764 // that would be colored when printed, as can be done on Linux. | |
| 4765 | |
| 4766 GTEST_ATTRIBUTE_PRINTF_(2, 3) | |
| 4767 static void ColoredPrintf(GTestColor color, const char *fmt, ...) { | |
| 4768 va_list args; | |
| 4769 va_start(args, fmt); | |
| 4770 | |
| 4771 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ | |
| 4772 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM) | |
| 4773 const bool use_color = AlwaysFalse(); | |
| 4774 #else | |
| 4775 static const bool in_color_mode = | |
| 4776 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); | |
| 4777 const bool use_color = in_color_mode && (color != GTestColor::kDefault); | |
| 4778 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS | |
| 4779 | |
| 4780 if (!use_color) { | |
| 4781 vprintf(fmt, args); | |
| 4782 va_end(args); | |
| 4783 return; | |
| 4784 } | |
| 4785 | |
| 4786 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ | |
| 4787 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW | |
| 4788 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); | |
| 4789 | |
| 4790 // Gets the current text color. | |
| 4791 CONSOLE_SCREEN_BUFFER_INFO buffer_info; | |
| 4792 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); | |
| 4793 const WORD old_color_attrs = buffer_info.wAttributes; | |
| 4794 const WORD new_color = GetNewColor(color, old_color_attrs); | |
| 4795 | |
| 4796 // We need to flush the stream buffers into the console before each | |
| 4797 // SetConsoleTextAttribute call lest it affect the text that is already | |
| 4798 // printed but has not yet reached the console. | |
| 4799 fflush(stdout); | |
| 4800 SetConsoleTextAttribute(stdout_handle, new_color); | |
| 4801 | |
| 4802 vprintf(fmt, args); | |
| 4803 | |
| 4804 fflush(stdout); | |
| 4805 // Restores the text color. | |
| 4806 SetConsoleTextAttribute(stdout_handle, old_color_attrs); | |
| 4807 #else | |
| 4808 printf("\033[0;3%sm", GetAnsiColorCode(color)); | |
| 4809 vprintf(fmt, args); | |
| 4810 printf("\033[m"); // Resets the terminal to default. | |
| 4811 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE | |
| 4812 va_end(args); | |
| 4813 } | |
| 4814 | |
| 4815 // Text printed in Google Test's text output and --gtest_list_tests | |
| 4816 // output to label the type parameter and value parameter for a test. | |
| 4817 static const char kTypeParamLabel[] = "TypeParam"; | |
| 4818 static const char kValueParamLabel[] = "GetParam()"; | |
| 4819 | |
| 4820 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { | |
| 4821 const char* const type_param = test_info.type_param(); | |
| 4822 const char* const value_param = test_info.value_param(); | |
| 4823 | |
| 4824 if (type_param != nullptr || value_param != nullptr) { | |
| 4825 printf(", where "); | |
| 4826 if (type_param != nullptr) { | |
| 4827 printf("%s = %s", kTypeParamLabel, type_param); | |
| 4828 if (value_param != nullptr) printf(" and "); | |
| 4829 } | |
| 4830 if (value_param != nullptr) { | |
| 4831 printf("%s = %s", kValueParamLabel, value_param); | |
| 4832 } | |
| 4833 } | |
| 4834 } | |
| 4835 | |
| 4836 // This class implements the TestEventListener interface. | |
| 4837 // | |
| 4838 // Class PrettyUnitTestResultPrinter is copyable. | |
| 4839 class PrettyUnitTestResultPrinter : public TestEventListener { | |
| 4840 public: | |
| 4841 PrettyUnitTestResultPrinter() {} | |
| 4842 static void PrintTestName(const char* test_suite, const char* test) { | |
| 4843 printf("%s.%s", test_suite, test); | |
| 4844 } | |
| 4845 | |
| 4846 // The following methods override what's in the TestEventListener class. | |
| 4847 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {} | |
| 4848 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; | |
| 4849 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; | |
| 4850 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} | |
| 4851 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4852 void OnTestCaseStart(const TestCase& test_case) override; | |
| 4853 #else | |
| 4854 void OnTestSuiteStart(const TestSuite& test_suite) override; | |
| 4855 #endif // OnTestCaseStart | |
| 4856 | |
| 4857 void OnTestStart(const TestInfo& test_info) override; | |
| 4858 | |
| 4859 void OnTestPartResult(const TestPartResult& result) override; | |
| 4860 void OnTestEnd(const TestInfo& test_info) override; | |
| 4861 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4862 void OnTestCaseEnd(const TestCase& test_case) override; | |
| 4863 #else | |
| 4864 void OnTestSuiteEnd(const TestSuite& test_suite) override; | |
| 4865 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4866 | |
| 4867 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; | |
| 4868 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} | |
| 4869 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; | |
| 4870 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {} | |
| 4871 | |
| 4872 private: | |
| 4873 static void PrintFailedTests(const UnitTest& unit_test); | |
| 4874 static void PrintFailedTestSuites(const UnitTest& unit_test); | |
| 4875 static void PrintSkippedTests(const UnitTest& unit_test); | |
| 4876 }; | |
| 4877 | |
| 4878 // Fired before each iteration of tests starts. | |
| 4879 void PrettyUnitTestResultPrinter::OnTestIterationStart( | |
| 4880 const UnitTest& unit_test, int iteration) { | |
| 4881 if (GTEST_FLAG(repeat) != 1) | |
| 4882 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); | |
| 4883 | |
| 4884 const char* const filter = GTEST_FLAG(filter).c_str(); | |
| 4885 | |
| 4886 // Prints the filter if it's not *. This reminds the user that some | |
| 4887 // tests may be skipped. | |
| 4888 if (!String::CStringEquals(filter, kUniversalFilter)) { | |
| 4889 ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_, | |
| 4890 filter); | |
| 4891 } | |
| 4892 | |
| 4893 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { | |
| 4894 const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); | |
| 4895 ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n", | |
| 4896 static_cast<int>(shard_index) + 1, | |
| 4897 internal::posix::GetEnv(kTestTotalShards)); | |
| 4898 } | |
| 4899 | |
| 4900 if (GTEST_FLAG(shuffle)) { | |
| 4901 ColoredPrintf(GTestColor::kYellow, | |
| 4902 "Note: Randomizing tests' orders with a seed of %d .\n", | |
| 4903 unit_test.random_seed()); | |
| 4904 } | |
| 4905 | |
| 4906 ColoredPrintf(GTestColor::kGreen, "[==========] "); | |
| 4907 printf("Running %s from %s.\n", | |
| 4908 FormatTestCount(unit_test.test_to_run_count()).c_str(), | |
| 4909 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); | |
| 4910 fflush(stdout); | |
| 4911 } | |
| 4912 | |
| 4913 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( | |
| 4914 const UnitTest& /*unit_test*/) { | |
| 4915 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 4916 printf("Global test environment set-up.\n"); | |
| 4917 fflush(stdout); | |
| 4918 } | |
| 4919 | |
| 4920 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4921 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { | |
| 4922 const std::string counts = | |
| 4923 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); | |
| 4924 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 4925 printf("%s from %s", counts.c_str(), test_case.name()); | |
| 4926 if (test_case.type_param() == nullptr) { | |
| 4927 printf("\n"); | |
| 4928 } else { | |
| 4929 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); | |
| 4930 } | |
| 4931 fflush(stdout); | |
| 4932 } | |
| 4933 #else | |
| 4934 void PrettyUnitTestResultPrinter::OnTestSuiteStart( | |
| 4935 const TestSuite& test_suite) { | |
| 4936 const std::string counts = | |
| 4937 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); | |
| 4938 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 4939 printf("%s from %s", counts.c_str(), test_suite.name()); | |
| 4940 if (test_suite.type_param() == nullptr) { | |
| 4941 printf("\n"); | |
| 4942 } else { | |
| 4943 printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); | |
| 4944 } | |
| 4945 fflush(stdout); | |
| 4946 } | |
| 4947 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4948 | |
| 4949 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { | |
| 4950 ColoredPrintf(GTestColor::kGreen, "[ RUN ] "); | |
| 4951 PrintTestName(test_info.test_suite_name(), test_info.name()); | |
| 4952 printf("\n"); | |
| 4953 fflush(stdout); | |
| 4954 } | |
| 4955 | |
| 4956 // Called after an assertion failure. | |
| 4957 void PrettyUnitTestResultPrinter::OnTestPartResult( | |
| 4958 const TestPartResult& result) { | |
| 4959 switch (result.type()) { | |
| 4960 // If the test part succeeded, we don't need to do anything. | |
| 4961 case TestPartResult::kSuccess: | |
| 4962 return; | |
| 4963 default: | |
| 4964 // Print failure message from the assertion | |
| 4965 // (e.g. expected this and got that). | |
| 4966 PrintTestPartResult(result); | |
| 4967 fflush(stdout); | |
| 4968 } | |
| 4969 } | |
| 4970 | |
| 4971 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { | |
| 4972 if (test_info.result()->Passed()) { | |
| 4973 ColoredPrintf(GTestColor::kGreen, "[ OK ] "); | |
| 4974 } else if (test_info.result()->Skipped()) { | |
| 4975 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); | |
| 4976 } else { | |
| 4977 ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); | |
| 4978 } | |
| 4979 PrintTestName(test_info.test_suite_name(), test_info.name()); | |
| 4980 if (test_info.result()->Failed()) | |
| 4981 PrintFullTestCommentIfPresent(test_info); | |
| 4982 | |
| 4983 if (GTEST_FLAG(print_time)) { | |
| 4984 printf(" (%s ms)\n", internal::StreamableToString( | |
| 4985 test_info.result()->elapsed_time()).c_str()); | |
| 4986 } else { | |
| 4987 printf("\n"); | |
| 4988 } | |
| 4989 fflush(stdout); | |
| 4990 } | |
| 4991 | |
| 4992 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 4993 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { | |
| 4994 if (!GTEST_FLAG(print_time)) return; | |
| 4995 | |
| 4996 const std::string counts = | |
| 4997 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); | |
| 4998 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 4999 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), | |
| 5000 internal::StreamableToString(test_case.elapsed_time()).c_str()); | |
| 5001 fflush(stdout); | |
| 5002 } | |
| 5003 #else | |
| 5004 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) { | |
| 5005 if (!GTEST_FLAG(print_time)) return; | |
| 5006 | |
| 5007 const std::string counts = | |
| 5008 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); | |
| 5009 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 5010 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), | |
| 5011 internal::StreamableToString(test_suite.elapsed_time()).c_str()); | |
| 5012 fflush(stdout); | |
| 5013 } | |
| 5014 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5015 | |
| 5016 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( | |
| 5017 const UnitTest& /*unit_test*/) { | |
| 5018 ColoredPrintf(GTestColor::kGreen, "[----------] "); | |
| 5019 printf("Global test environment tear-down\n"); | |
| 5020 fflush(stdout); | |
| 5021 } | |
| 5022 | |
| 5023 // Internal helper for printing the list of failed tests. | |
| 5024 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { | |
| 5025 const int failed_test_count = unit_test.failed_test_count(); | |
| 5026 ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); | |
| 5027 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); | |
| 5028 | |
| 5029 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { | |
| 5030 const TestSuite& test_suite = *unit_test.GetTestSuite(i); | |
| 5031 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) { | |
| 5032 continue; | |
| 5033 } | |
| 5034 for (int j = 0; j < test_suite.total_test_count(); ++j) { | |
| 5035 const TestInfo& test_info = *test_suite.GetTestInfo(j); | |
| 5036 if (!test_info.should_run() || !test_info.result()->Failed()) { | |
| 5037 continue; | |
| 5038 } | |
| 5039 ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); | |
| 5040 printf("%s.%s", test_suite.name(), test_info.name()); | |
| 5041 PrintFullTestCommentIfPresent(test_info); | |
| 5042 printf("\n"); | |
| 5043 } | |
| 5044 } | |
| 5045 printf("\n%2d FAILED %s\n", failed_test_count, | |
| 5046 failed_test_count == 1 ? "TEST" : "TESTS"); | |
| 5047 } | |
| 5048 | |
| 5049 // Internal helper for printing the list of test suite failures not covered by | |
| 5050 // PrintFailedTests. | |
| 5051 void PrettyUnitTestResultPrinter::PrintFailedTestSuites( | |
| 5052 const UnitTest& unit_test) { | |
| 5053 int suite_failure_count = 0; | |
| 5054 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { | |
| 5055 const TestSuite& test_suite = *unit_test.GetTestSuite(i); | |
| 5056 if (!test_suite.should_run()) { | |
| 5057 continue; | |
| 5058 } | |
| 5059 if (test_suite.ad_hoc_test_result().Failed()) { | |
| 5060 ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); | |
| 5061 printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name()); | |
| 5062 ++suite_failure_count; | |
| 5063 } | |
| 5064 } | |
| 5065 if (suite_failure_count > 0) { | |
| 5066 printf("\n%2d FAILED TEST %s\n", suite_failure_count, | |
| 5067 suite_failure_count == 1 ? "SUITE" : "SUITES"); | |
| 5068 } | |
| 5069 } | |
| 5070 | |
| 5071 // Internal helper for printing the list of skipped tests. | |
| 5072 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { | |
| 5073 const int skipped_test_count = unit_test.skipped_test_count(); | |
| 5074 if (skipped_test_count == 0) { | |
| 5075 return; | |
| 5076 } | |
| 5077 | |
| 5078 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { | |
| 5079 const TestSuite& test_suite = *unit_test.GetTestSuite(i); | |
| 5080 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) { | |
| 5081 continue; | |
| 5082 } | |
| 5083 for (int j = 0; j < test_suite.total_test_count(); ++j) { | |
| 5084 const TestInfo& test_info = *test_suite.GetTestInfo(j); | |
| 5085 if (!test_info.should_run() || !test_info.result()->Skipped()) { | |
| 5086 continue; | |
| 5087 } | |
| 5088 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); | |
| 5089 printf("%s.%s", test_suite.name(), test_info.name()); | |
| 5090 printf("\n"); | |
| 5091 } | |
| 5092 } | |
| 5093 } | |
| 5094 | |
| 5095 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, | |
| 5096 int /*iteration*/) { | |
| 5097 ColoredPrintf(GTestColor::kGreen, "[==========] "); | |
| 5098 printf("%s from %s ran.", | |
| 5099 FormatTestCount(unit_test.test_to_run_count()).c_str(), | |
| 5100 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); | |
| 5101 if (GTEST_FLAG(print_time)) { | |
| 5102 printf(" (%s ms total)", | |
| 5103 internal::StreamableToString(unit_test.elapsed_time()).c_str()); | |
| 5104 } | |
| 5105 printf("\n"); | |
| 5106 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] "); | |
| 5107 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); | |
| 5108 | |
| 5109 const int skipped_test_count = unit_test.skipped_test_count(); | |
| 5110 if (skipped_test_count > 0) { | |
| 5111 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); | |
| 5112 printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str()); | |
| 5113 PrintSkippedTests(unit_test); | |
| 5114 } | |
| 5115 | |
| 5116 if (!unit_test.Passed()) { | |
| 5117 PrintFailedTests(unit_test); | |
| 5118 PrintFailedTestSuites(unit_test); | |
| 5119 } | |
| 5120 | |
| 5121 int num_disabled = unit_test.reportable_disabled_test_count(); | |
| 5122 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { | |
| 5123 if (unit_test.Passed()) { | |
| 5124 printf("\n"); // Add a spacer if no FAILURE banner is displayed. | |
| 5125 } | |
| 5126 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n", | |
| 5127 num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); | |
| 5128 } | |
| 5129 // Ensure that Google Test output is printed before, e.g., heapchecker output. | |
| 5130 fflush(stdout); | |
| 5131 } | |
| 5132 | |
| 5133 // End PrettyUnitTestResultPrinter | |
| 5134 | |
| 5135 // This class implements the TestEventListener interface. | |
| 5136 // | |
| 5137 // Class BriefUnitTestResultPrinter is copyable. | |
| 5138 class BriefUnitTestResultPrinter : public TestEventListener { | |
| 5139 public: | |
| 5140 BriefUnitTestResultPrinter() {} | |
| 5141 static void PrintTestName(const char* test_suite, const char* test) { | |
| 5142 printf("%s.%s", test_suite, test); | |
| 5143 } | |
| 5144 | |
| 5145 // The following methods override what's in the TestEventListener class. | |
| 5146 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {} | |
| 5147 void OnTestIterationStart(const UnitTest& /*unit_test*/, | |
| 5148 int /*iteration*/) override {} | |
| 5149 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {} | |
| 5150 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} | |
| 5151 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5152 void OnTestCaseStart(const TestCase& /*test_case*/) override {} | |
| 5153 #else | |
| 5154 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {} | |
| 5155 #endif // OnTestCaseStart | |
| 5156 | |
| 5157 void OnTestStart(const TestInfo& /*test_info*/) override {} | |
| 5158 | |
| 5159 void OnTestPartResult(const TestPartResult& result) override; | |
| 5160 void OnTestEnd(const TestInfo& test_info) override; | |
| 5161 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5162 void OnTestCaseEnd(const TestCase& /*test_case*/) override {} | |
| 5163 #else | |
| 5164 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {} | |
| 5165 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5166 | |
| 5167 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {} | |
| 5168 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} | |
| 5169 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; | |
| 5170 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {} | |
| 5171 }; | |
| 5172 | |
| 5173 // Called after an assertion failure. | |
| 5174 void BriefUnitTestResultPrinter::OnTestPartResult( | |
| 5175 const TestPartResult& result) { | |
| 5176 switch (result.type()) { | |
| 5177 // If the test part succeeded, we don't need to do anything. | |
| 5178 case TestPartResult::kSuccess: | |
| 5179 return; | |
| 5180 default: | |
| 5181 // Print failure message from the assertion | |
| 5182 // (e.g. expected this and got that). | |
| 5183 PrintTestPartResult(result); | |
| 5184 fflush(stdout); | |
| 5185 } | |
| 5186 } | |
| 5187 | |
| 5188 void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { | |
| 5189 if (test_info.result()->Failed()) { | |
| 5190 ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); | |
| 5191 PrintTestName(test_info.test_suite_name(), test_info.name()); | |
| 5192 PrintFullTestCommentIfPresent(test_info); | |
| 5193 | |
| 5194 if (GTEST_FLAG(print_time)) { | |
| 5195 printf(" (%s ms)\n", | |
| 5196 internal::StreamableToString(test_info.result()->elapsed_time()) | |
| 5197 .c_str()); | |
| 5198 } else { | |
| 5199 printf("\n"); | |
| 5200 } | |
| 5201 fflush(stdout); | |
| 5202 } | |
| 5203 } | |
| 5204 | |
| 5205 void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, | |
| 5206 int /*iteration*/) { | |
| 5207 ColoredPrintf(GTestColor::kGreen, "[==========] "); | |
| 5208 printf("%s from %s ran.", | |
| 5209 FormatTestCount(unit_test.test_to_run_count()).c_str(), | |
| 5210 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); | |
| 5211 if (GTEST_FLAG(print_time)) { | |
| 5212 printf(" (%s ms total)", | |
| 5213 internal::StreamableToString(unit_test.elapsed_time()).c_str()); | |
| 5214 } | |
| 5215 printf("\n"); | |
| 5216 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] "); | |
| 5217 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); | |
| 5218 | |
| 5219 const int skipped_test_count = unit_test.skipped_test_count(); | |
| 5220 if (skipped_test_count > 0) { | |
| 5221 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); | |
| 5222 printf("%s.\n", FormatTestCount(skipped_test_count).c_str()); | |
| 5223 } | |
| 5224 | |
| 5225 int num_disabled = unit_test.reportable_disabled_test_count(); | |
| 5226 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { | |
| 5227 if (unit_test.Passed()) { | |
| 5228 printf("\n"); // Add a spacer if no FAILURE banner is displayed. | |
| 5229 } | |
| 5230 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n", | |
| 5231 num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); | |
| 5232 } | |
| 5233 // Ensure that Google Test output is printed before, e.g., heapchecker output. | |
| 5234 fflush(stdout); | |
| 5235 } | |
| 5236 | |
| 5237 // End BriefUnitTestResultPrinter | |
| 5238 | |
| 5239 // class TestEventRepeater | |
| 5240 // | |
| 5241 // This class forwards events to other event listeners. | |
| 5242 class TestEventRepeater : public TestEventListener { | |
| 5243 public: | |
| 5244 TestEventRepeater() : forwarding_enabled_(true) {} | |
| 5245 ~TestEventRepeater() override; | |
| 5246 void Append(TestEventListener *listener); | |
| 5247 TestEventListener* Release(TestEventListener* listener); | |
| 5248 | |
| 5249 // Controls whether events will be forwarded to listeners_. Set to false | |
| 5250 // in death test child processes. | |
| 5251 bool forwarding_enabled() const { return forwarding_enabled_; } | |
| 5252 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } | |
| 5253 | |
| 5254 void OnTestProgramStart(const UnitTest& unit_test) override; | |
| 5255 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; | |
| 5256 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; | |
| 5257 void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override; | |
| 5258 // Legacy API is deprecated but still available | |
| 5259 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5260 void OnTestCaseStart(const TestSuite& parameter) override; | |
| 5261 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5262 void OnTestSuiteStart(const TestSuite& parameter) override; | |
| 5263 void OnTestStart(const TestInfo& test_info) override; | |
| 5264 void OnTestPartResult(const TestPartResult& result) override; | |
| 5265 void OnTestEnd(const TestInfo& test_info) override; | |
| 5266 // Legacy API is deprecated but still available | |
| 5267 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5268 void OnTestCaseEnd(const TestCase& parameter) override; | |
| 5269 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5270 void OnTestSuiteEnd(const TestSuite& parameter) override; | |
| 5271 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; | |
| 5272 void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override; | |
| 5273 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; | |
| 5274 void OnTestProgramEnd(const UnitTest& unit_test) override; | |
| 5275 | |
| 5276 private: | |
| 5277 // Controls whether events will be forwarded to listeners_. Set to false | |
| 5278 // in death test child processes. | |
| 5279 bool forwarding_enabled_; | |
| 5280 // The list of listeners that receive events. | |
| 5281 std::vector<TestEventListener*> listeners_; | |
| 5282 | |
| 5283 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); | |
| 5284 }; | |
| 5285 | |
| 5286 TestEventRepeater::~TestEventRepeater() { | |
| 5287 ForEach(listeners_, Delete<TestEventListener>); | |
| 5288 } | |
| 5289 | |
| 5290 void TestEventRepeater::Append(TestEventListener *listener) { | |
| 5291 listeners_.push_back(listener); | |
| 5292 } | |
| 5293 | |
| 5294 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { | |
| 5295 for (size_t i = 0; i < listeners_.size(); ++i) { | |
| 5296 if (listeners_[i] == listener) { | |
| 5297 listeners_.erase(listeners_.begin() + static_cast<int>(i)); | |
| 5298 return listener; | |
| 5299 } | |
| 5300 } | |
| 5301 | |
| 5302 return nullptr; | |
| 5303 } | |
| 5304 | |
| 5305 // Since most methods are very similar, use macros to reduce boilerplate. | |
| 5306 // This defines a member that forwards the call to all listeners. | |
| 5307 #define GTEST_REPEATER_METHOD_(Name, Type) \ | |
| 5308 void TestEventRepeater::Name(const Type& parameter) { \ | |
| 5309 if (forwarding_enabled_) { \ | |
| 5310 for (size_t i = 0; i < listeners_.size(); i++) { \ | |
| 5311 listeners_[i]->Name(parameter); \ | |
| 5312 } \ | |
| 5313 } \ | |
| 5314 } | |
| 5315 // This defines a member that forwards the call to all listeners in reverse | |
| 5316 // order. | |
| 5317 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ | |
| 5318 void TestEventRepeater::Name(const Type& parameter) { \ | |
| 5319 if (forwarding_enabled_) { \ | |
| 5320 for (size_t i = listeners_.size(); i != 0; i--) { \ | |
| 5321 listeners_[i - 1]->Name(parameter); \ | |
| 5322 } \ | |
| 5323 } \ | |
| 5324 } | |
| 5325 | |
| 5326 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) | |
| 5327 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) | |
| 5328 // Legacy API is deprecated but still available | |
| 5329 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5330 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite) | |
| 5331 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5332 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite) | |
| 5333 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) | |
| 5334 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) | |
| 5335 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) | |
| 5336 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) | |
| 5337 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) | |
| 5338 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) | |
| 5339 // Legacy API is deprecated but still available | |
| 5340 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5341 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite) | |
| 5342 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 5343 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite) | |
| 5344 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) | |
| 5345 | |
| 5346 #undef GTEST_REPEATER_METHOD_ | |
| 5347 #undef GTEST_REVERSE_REPEATER_METHOD_ | |
| 5348 | |
| 5349 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, | |
| 5350 int iteration) { | |
| 5351 if (forwarding_enabled_) { | |
| 5352 for (size_t i = 0; i < listeners_.size(); i++) { | |
| 5353 listeners_[i]->OnTestIterationStart(unit_test, iteration); | |
| 5354 } | |
| 5355 } | |
| 5356 } | |
| 5357 | |
| 5358 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, | |
| 5359 int iteration) { | |
| 5360 if (forwarding_enabled_) { | |
| 5361 for (size_t i = listeners_.size(); i > 0; i--) { | |
| 5362 listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration); | |
| 5363 } | |
| 5364 } | |
| 5365 } | |
| 5366 | |
| 5367 // End TestEventRepeater | |
| 5368 | |
| 5369 // This class generates an XML output file. | |
| 5370 class XmlUnitTestResultPrinter : public EmptyTestEventListener { | |
| 5371 public: | |
| 5372 explicit XmlUnitTestResultPrinter(const char* output_file); | |
| 5373 | |
| 5374 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; | |
| 5375 void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites); | |
| 5376 | |
| 5377 // Prints an XML summary of all unit tests. | |
| 5378 static void PrintXmlTestsList(std::ostream* stream, | |
| 5379 const std::vector<TestSuite*>& test_suites); | |
| 5380 | |
| 5381 private: | |
| 5382 // Is c a whitespace character that is normalized to a space character | |
| 5383 // when it appears in an XML attribute value? | |
| 5384 static bool IsNormalizableWhitespace(char c) { | |
| 5385 return c == 0x9 || c == 0xA || c == 0xD; | |
| 5386 } | |
| 5387 | |
| 5388 // May c appear in a well-formed XML document? | |
| 5389 static bool IsValidXmlCharacter(char c) { | |
| 5390 return IsNormalizableWhitespace(c) || c >= 0x20; | |
| 5391 } | |
| 5392 | |
| 5393 // Returns an XML-escaped copy of the input string str. If | |
| 5394 // is_attribute is true, the text is meant to appear as an attribute | |
| 5395 // value, and normalizable whitespace is preserved by replacing it | |
| 5396 // with character references. | |
| 5397 static std::string EscapeXml(const std::string& str, bool is_attribute); | |
| 5398 | |
| 5399 // Returns the given string with all characters invalid in XML removed. | |
| 5400 static std::string RemoveInvalidXmlCharacters(const std::string& str); | |
| 5401 | |
| 5402 // Convenience wrapper around EscapeXml when str is an attribute value. | |
| 5403 static std::string EscapeXmlAttribute(const std::string& str) { | |
| 5404 return EscapeXml(str, true); | |
| 5405 } | |
| 5406 | |
| 5407 // Convenience wrapper around EscapeXml when str is not an attribute value. | |
| 5408 static std::string EscapeXmlText(const char* str) { | |
| 5409 return EscapeXml(str, false); | |
| 5410 } | |
| 5411 | |
| 5412 // Verifies that the given attribute belongs to the given element and | |
| 5413 // streams the attribute as XML. | |
| 5414 static void OutputXmlAttribute(std::ostream* stream, | |
| 5415 const std::string& element_name, | |
| 5416 const std::string& name, | |
| 5417 const std::string& value); | |
| 5418 | |
| 5419 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. | |
| 5420 static void OutputXmlCDataSection(::std::ostream* stream, const char* data); | |
| 5421 | |
| 5422 // Streams a test suite XML stanza containing the given test result. | |
| 5423 // | |
| 5424 // Requires: result.Failed() | |
| 5425 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream, | |
| 5426 const TestResult& result); | |
| 5427 | |
| 5428 // Streams an XML representation of a TestResult object. | |
| 5429 static void OutputXmlTestResult(::std::ostream* stream, | |
| 5430 const TestResult& result); | |
| 5431 | |
| 5432 // Streams an XML representation of a TestInfo object. | |
| 5433 static void OutputXmlTestInfo(::std::ostream* stream, | |
| 5434 const char* test_suite_name, | |
| 5435 const TestInfo& test_info); | |
| 5436 | |
| 5437 // Prints an XML representation of a TestSuite object | |
| 5438 static void PrintXmlTestSuite(::std::ostream* stream, | |
| 5439 const TestSuite& test_suite); | |
| 5440 | |
| 5441 // Prints an XML summary of unit_test to output stream out. | |
| 5442 static void PrintXmlUnitTest(::std::ostream* stream, | |
| 5443 const UnitTest& unit_test); | |
| 5444 | |
| 5445 // Produces a string representing the test properties in a result as space | |
| 5446 // delimited XML attributes based on the property key="value" pairs. | |
| 5447 // When the std::string is not empty, it includes a space at the beginning, | |
| 5448 // to delimit this attribute from prior attributes. | |
| 5449 static std::string TestPropertiesAsXmlAttributes(const TestResult& result); | |
| 5450 | |
| 5451 // Streams an XML representation of the test properties of a TestResult | |
| 5452 // object. | |
| 5453 static void OutputXmlTestProperties(std::ostream* stream, | |
| 5454 const TestResult& result); | |
| 5455 | |
| 5456 // The output file. | |
| 5457 const std::string output_file_; | |
| 5458 | |
| 5459 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); | |
| 5460 }; | |
| 5461 | |
| 5462 // Creates a new XmlUnitTestResultPrinter. | |
| 5463 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) | |
| 5464 : output_file_(output_file) { | |
| 5465 if (output_file_.empty()) { | |
| 5466 GTEST_LOG_(FATAL) << "XML output file may not be null"; | |
| 5467 } | |
| 5468 } | |
| 5469 | |
| 5470 // Called after the unit test ends. | |
| 5471 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, | |
| 5472 int /*iteration*/) { | |
| 5473 FILE* xmlout = OpenFileForWriting(output_file_); | |
| 5474 std::stringstream stream; | |
| 5475 PrintXmlUnitTest(&stream, unit_test); | |
| 5476 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); | |
| 5477 fclose(xmlout); | |
| 5478 } | |
| 5479 | |
| 5480 void XmlUnitTestResultPrinter::ListTestsMatchingFilter( | |
| 5481 const std::vector<TestSuite*>& test_suites) { | |
| 5482 FILE* xmlout = OpenFileForWriting(output_file_); | |
| 5483 std::stringstream stream; | |
| 5484 PrintXmlTestsList(&stream, test_suites); | |
| 5485 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); | |
| 5486 fclose(xmlout); | |
| 5487 } | |
| 5488 | |
| 5489 // Returns an XML-escaped copy of the input string str. If is_attribute | |
| 5490 // is true, the text is meant to appear as an attribute value, and | |
| 5491 // normalizable whitespace is preserved by replacing it with character | |
| 5492 // references. | |
| 5493 // | |
| 5494 // Invalid XML characters in str, if any, are stripped from the output. | |
| 5495 // It is expected that most, if not all, of the text processed by this | |
| 5496 // module will consist of ordinary English text. | |
| 5497 // If this module is ever modified to produce version 1.1 XML output, | |
| 5498 // most invalid characters can be retained using character references. | |
| 5499 std::string XmlUnitTestResultPrinter::EscapeXml( | |
| 5500 const std::string& str, bool is_attribute) { | |
| 5501 Message m; | |
| 5502 | |
| 5503 for (size_t i = 0; i < str.size(); ++i) { | |
| 5504 const char ch = str[i]; | |
| 5505 switch (ch) { | |
| 5506 case '<': | |
| 5507 m << "<"; | |
| 5508 break; | |
| 5509 case '>': | |
| 5510 m << ">"; | |
| 5511 break; | |
| 5512 case '&': | |
| 5513 m << "&"; | |
| 5514 break; | |
| 5515 case '\'': | |
| 5516 if (is_attribute) | |
| 5517 m << "'"; | |
| 5518 else | |
| 5519 m << '\''; | |
| 5520 break; | |
| 5521 case '"': | |
| 5522 if (is_attribute) | |
| 5523 m << """; | |
| 5524 else | |
| 5525 m << '"'; | |
| 5526 break; | |
| 5527 default: | |
| 5528 if (IsValidXmlCharacter(ch)) { | |
| 5529 if (is_attribute && IsNormalizableWhitespace(ch)) | |
| 5530 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) | |
| 5531 << ";"; | |
| 5532 else | |
| 5533 m << ch; | |
| 5534 } | |
| 5535 break; | |
| 5536 } | |
| 5537 } | |
| 5538 | |
| 5539 return m.GetString(); | |
| 5540 } | |
| 5541 | |
| 5542 // Returns the given string with all characters invalid in XML removed. | |
| 5543 // Currently invalid characters are dropped from the string. An | |
| 5544 // alternative is to replace them with certain characters such as . or ?. | |
| 5545 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( | |
| 5546 const std::string& str) { | |
| 5547 std::string output; | |
| 5548 output.reserve(str.size()); | |
| 5549 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) | |
| 5550 if (IsValidXmlCharacter(*it)) | |
| 5551 output.push_back(*it); | |
| 5552 | |
| 5553 return output; | |
| 5554 } | |
| 5555 | |
| 5556 // The following routines generate an XML representation of a UnitTest | |
| 5557 // object. | |
| 5558 // GOOGLETEST_CM0009 DO NOT DELETE | |
| 5559 // | |
| 5560 // This is how Google Test concepts map to the DTD: | |
| 5561 // | |
| 5562 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object | |
| 5563 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object | |
| 5564 // <testcase name="test-name"> <-- corresponds to a TestInfo object | |
| 5565 // <failure message="...">...</failure> | |
| 5566 // <failure message="...">...</failure> | |
| 5567 // <failure message="...">...</failure> | |
| 5568 // <-- individual assertion failures | |
| 5569 // </testcase> | |
| 5570 // </testsuite> | |
| 5571 // </testsuites> | |
| 5572 | |
| 5573 // Formats the given time in milliseconds as seconds. | |
| 5574 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { | |
| 5575 ::std::stringstream ss; | |
| 5576 ss << (static_cast<double>(ms) * 1e-3); | |
| 5577 return ss.str(); | |
| 5578 } | |
| 5579 | |
| 5580 static bool PortableLocaltime(time_t seconds, struct tm* out) { | |
| 5581 #if defined(_MSC_VER) | |
| 5582 return localtime_s(out, &seconds) == 0; | |
| 5583 #elif defined(__MINGW32__) || defined(__MINGW64__) | |
| 5584 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses | |
| 5585 // Windows' localtime(), which has a thread-local tm buffer. | |
| 5586 struct tm* tm_ptr = localtime(&seconds); // NOLINT | |
| 5587 if (tm_ptr == nullptr) return false; | |
| 5588 *out = *tm_ptr; | |
| 5589 return true; | |
| 5590 #elif defined(__STDC_LIB_EXT1__) | |
| 5591 // Uses localtime_s when available as localtime_r is only available from | |
| 5592 // C23 standard. | |
| 5593 return localtime_s(&seconds, out) != nullptr; | |
| 5594 #else | |
| 5595 return localtime_r(&seconds, out) != nullptr; | |
| 5596 #endif | |
| 5597 } | |
| 5598 | |
| 5599 // Converts the given epoch time in milliseconds to a date string in the ISO | |
| 5600 // 8601 format, without the timezone information. | |
| 5601 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { | |
| 5602 struct tm time_struct; | |
| 5603 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) | |
| 5604 return ""; | |
| 5605 // YYYY-MM-DDThh:mm:ss.sss | |
| 5606 return StreamableToString(time_struct.tm_year + 1900) + "-" + | |
| 5607 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + | |
| 5608 String::FormatIntWidth2(time_struct.tm_mday) + "T" + | |
| 5609 String::FormatIntWidth2(time_struct.tm_hour) + ":" + | |
| 5610 String::FormatIntWidth2(time_struct.tm_min) + ":" + | |
| 5611 String::FormatIntWidth2(time_struct.tm_sec) + "." + | |
| 5612 String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); | |
| 5613 } | |
| 5614 | |
| 5615 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. | |
| 5616 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, | |
| 5617 const char* data) { | |
| 5618 const char* segment = data; | |
| 5619 *stream << "<![CDATA["; | |
| 5620 for (;;) { | |
| 5621 const char* const next_segment = strstr(segment, "]]>"); | |
| 5622 if (next_segment != nullptr) { | |
| 5623 stream->write( | |
| 5624 segment, static_cast<std::streamsize>(next_segment - segment)); | |
| 5625 *stream << "]]>]]><![CDATA["; | |
| 5626 segment = next_segment + strlen("]]>"); | |
| 5627 } else { | |
| 5628 *stream << segment; | |
| 5629 break; | |
| 5630 } | |
| 5631 } | |
| 5632 *stream << "]]>"; | |
| 5633 } | |
| 5634 | |
| 5635 void XmlUnitTestResultPrinter::OutputXmlAttribute( | |
| 5636 std::ostream* stream, | |
| 5637 const std::string& element_name, | |
| 5638 const std::string& name, | |
| 5639 const std::string& value) { | |
| 5640 const std::vector<std::string>& allowed_names = | |
| 5641 GetReservedOutputAttributesForElement(element_name); | |
| 5642 | |
| 5643 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != | |
| 5644 allowed_names.end()) | |
| 5645 << "Attribute " << name << " is not allowed for element <" << element_name | |
| 5646 << ">."; | |
| 5647 | |
| 5648 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; | |
| 5649 } | |
| 5650 | |
| 5651 // Streams a test suite XML stanza containing the given test result. | |
| 5652 void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult( | |
| 5653 ::std::ostream* stream, const TestResult& result) { | |
| 5654 // Output the boilerplate for a minimal test suite with one test. | |
| 5655 *stream << " <testsuite"; | |
| 5656 OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure"); | |
| 5657 OutputXmlAttribute(stream, "testsuite", "tests", "1"); | |
| 5658 OutputXmlAttribute(stream, "testsuite", "failures", "1"); | |
| 5659 OutputXmlAttribute(stream, "testsuite", "disabled", "0"); | |
| 5660 OutputXmlAttribute(stream, "testsuite", "skipped", "0"); | |
| 5661 OutputXmlAttribute(stream, "testsuite", "errors", "0"); | |
| 5662 OutputXmlAttribute(stream, "testsuite", "time", | |
| 5663 FormatTimeInMillisAsSeconds(result.elapsed_time())); | |
| 5664 OutputXmlAttribute( | |
| 5665 stream, "testsuite", "timestamp", | |
| 5666 FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); | |
| 5667 *stream << ">"; | |
| 5668 | |
| 5669 // Output the boilerplate for a minimal test case with a single test. | |
| 5670 *stream << " <testcase"; | |
| 5671 OutputXmlAttribute(stream, "testcase", "name", ""); | |
| 5672 OutputXmlAttribute(stream, "testcase", "status", "run"); | |
| 5673 OutputXmlAttribute(stream, "testcase", "result", "completed"); | |
| 5674 OutputXmlAttribute(stream, "testcase", "classname", ""); | |
| 5675 OutputXmlAttribute(stream, "testcase", "time", | |
| 5676 FormatTimeInMillisAsSeconds(result.elapsed_time())); | |
| 5677 OutputXmlAttribute( | |
| 5678 stream, "testcase", "timestamp", | |
| 5679 FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); | |
| 5680 | |
| 5681 // Output the actual test result. | |
| 5682 OutputXmlTestResult(stream, result); | |
| 5683 | |
| 5684 // Complete the test suite. | |
| 5685 *stream << " </testsuite>\n"; | |
| 5686 } | |
| 5687 | |
| 5688 // Prints an XML representation of a TestInfo object. | |
| 5689 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, | |
| 5690 const char* test_suite_name, | |
| 5691 const TestInfo& test_info) { | |
| 5692 const TestResult& result = *test_info.result(); | |
| 5693 const std::string kTestsuite = "testcase"; | |
| 5694 | |
| 5695 if (test_info.is_in_another_shard()) { | |
| 5696 return; | |
| 5697 } | |
| 5698 | |
| 5699 *stream << " <testcase"; | |
| 5700 OutputXmlAttribute(stream, kTestsuite, "name", test_info.name()); | |
| 5701 | |
| 5702 if (test_info.value_param() != nullptr) { | |
| 5703 OutputXmlAttribute(stream, kTestsuite, "value_param", | |
| 5704 test_info.value_param()); | |
| 5705 } | |
| 5706 if (test_info.type_param() != nullptr) { | |
| 5707 OutputXmlAttribute(stream, kTestsuite, "type_param", | |
| 5708 test_info.type_param()); | |
| 5709 } | |
| 5710 if (GTEST_FLAG(list_tests)) { | |
| 5711 OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); | |
| 5712 OutputXmlAttribute(stream, kTestsuite, "line", | |
| 5713 StreamableToString(test_info.line())); | |
| 5714 *stream << " />\n"; | |
| 5715 return; | |
| 5716 } | |
| 5717 | |
| 5718 OutputXmlAttribute(stream, kTestsuite, "status", | |
| 5719 test_info.should_run() ? "run" : "notrun"); | |
| 5720 OutputXmlAttribute(stream, kTestsuite, "result", | |
| 5721 test_info.should_run() | |
| 5722 ? (result.Skipped() ? "skipped" : "completed") | |
| 5723 : "suppressed"); | |
| 5724 OutputXmlAttribute(stream, kTestsuite, "time", | |
| 5725 FormatTimeInMillisAsSeconds(result.elapsed_time())); | |
| 5726 OutputXmlAttribute( | |
| 5727 stream, kTestsuite, "timestamp", | |
| 5728 FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); | |
| 5729 OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name); | |
| 5730 | |
| 5731 OutputXmlTestResult(stream, result); | |
| 5732 } | |
| 5733 | |
| 5734 void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, | |
| 5735 const TestResult& result) { | |
| 5736 int failures = 0; | |
| 5737 int skips = 0; | |
| 5738 for (int i = 0; i < result.total_part_count(); ++i) { | |
| 5739 const TestPartResult& part = result.GetTestPartResult(i); | |
| 5740 if (part.failed()) { | |
| 5741 if (++failures == 1 && skips == 0) { | |
| 5742 *stream << ">\n"; | |
| 5743 } | |
| 5744 const std::string location = | |
| 5745 internal::FormatCompilerIndependentFileLocation(part.file_name(), | |
| 5746 part.line_number()); | |
| 5747 const std::string summary = location + "\n" + part.summary(); | |
| 5748 *stream << " <failure message=\"" | |
| 5749 << EscapeXmlAttribute(summary) | |
| 5750 << "\" type=\"\">"; | |
| 5751 const std::string detail = location + "\n" + part.message(); | |
| 5752 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); | |
| 5753 *stream << "</failure>\n"; | |
| 5754 } else if (part.skipped()) { | |
| 5755 if (++skips == 1 && failures == 0) { | |
| 5756 *stream << ">\n"; | |
| 5757 } | |
| 5758 const std::string location = | |
| 5759 internal::FormatCompilerIndependentFileLocation(part.file_name(), | |
| 5760 part.line_number()); | |
| 5761 const std::string summary = location + "\n" + part.summary(); | |
| 5762 *stream << " <skipped message=\"" | |
| 5763 << EscapeXmlAttribute(summary.c_str()) << "\">"; | |
| 5764 const std::string detail = location + "\n" + part.message(); | |
| 5765 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); | |
| 5766 *stream << "</skipped>\n"; | |
| 5767 } | |
| 5768 } | |
| 5769 | |
| 5770 if (failures == 0 && skips == 0 && result.test_property_count() == 0) { | |
| 5771 *stream << " />\n"; | |
| 5772 } else { | |
| 5773 if (failures == 0 && skips == 0) { | |
| 5774 *stream << ">\n"; | |
| 5775 } | |
| 5776 OutputXmlTestProperties(stream, result); | |
| 5777 *stream << " </testcase>\n"; | |
| 5778 } | |
| 5779 } | |
| 5780 | |
| 5781 // Prints an XML representation of a TestSuite object | |
| 5782 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, | |
| 5783 const TestSuite& test_suite) { | |
| 5784 const std::string kTestsuite = "testsuite"; | |
| 5785 *stream << " <" << kTestsuite; | |
| 5786 OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); | |
| 5787 OutputXmlAttribute(stream, kTestsuite, "tests", | |
| 5788 StreamableToString(test_suite.reportable_test_count())); | |
| 5789 if (!GTEST_FLAG(list_tests)) { | |
| 5790 OutputXmlAttribute(stream, kTestsuite, "failures", | |
| 5791 StreamableToString(test_suite.failed_test_count())); | |
| 5792 OutputXmlAttribute( | |
| 5793 stream, kTestsuite, "disabled", | |
| 5794 StreamableToString(test_suite.reportable_disabled_test_count())); | |
| 5795 OutputXmlAttribute(stream, kTestsuite, "skipped", | |
| 5796 StreamableToString(test_suite.skipped_test_count())); | |
| 5797 | |
| 5798 OutputXmlAttribute(stream, kTestsuite, "errors", "0"); | |
| 5799 | |
| 5800 OutputXmlAttribute(stream, kTestsuite, "time", | |
| 5801 FormatTimeInMillisAsSeconds(test_suite.elapsed_time())); | |
| 5802 OutputXmlAttribute( | |
| 5803 stream, kTestsuite, "timestamp", | |
| 5804 FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp())); | |
| 5805 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result()); | |
| 5806 } | |
| 5807 *stream << ">\n"; | |
| 5808 for (int i = 0; i < test_suite.total_test_count(); ++i) { | |
| 5809 if (test_suite.GetTestInfo(i)->is_reportable()) | |
| 5810 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); | |
| 5811 } | |
| 5812 *stream << " </" << kTestsuite << ">\n"; | |
| 5813 } | |
| 5814 | |
| 5815 // Prints an XML summary of unit_test to output stream out. | |
| 5816 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, | |
| 5817 const UnitTest& unit_test) { | |
| 5818 const std::string kTestsuites = "testsuites"; | |
| 5819 | |
| 5820 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; | |
| 5821 *stream << "<" << kTestsuites; | |
| 5822 | |
| 5823 OutputXmlAttribute(stream, kTestsuites, "tests", | |
| 5824 StreamableToString(unit_test.reportable_test_count())); | |
| 5825 OutputXmlAttribute(stream, kTestsuites, "failures", | |
| 5826 StreamableToString(unit_test.failed_test_count())); | |
| 5827 OutputXmlAttribute( | |
| 5828 stream, kTestsuites, "disabled", | |
| 5829 StreamableToString(unit_test.reportable_disabled_test_count())); | |
| 5830 OutputXmlAttribute(stream, kTestsuites, "errors", "0"); | |
| 5831 OutputXmlAttribute(stream, kTestsuites, "time", | |
| 5832 FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); | |
| 5833 OutputXmlAttribute( | |
| 5834 stream, kTestsuites, "timestamp", | |
| 5835 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); | |
| 5836 | |
| 5837 if (GTEST_FLAG(shuffle)) { | |
| 5838 OutputXmlAttribute(stream, kTestsuites, "random_seed", | |
| 5839 StreamableToString(unit_test.random_seed())); | |
| 5840 } | |
| 5841 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); | |
| 5842 | |
| 5843 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); | |
| 5844 *stream << ">\n"; | |
| 5845 | |
| 5846 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { | |
| 5847 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) | |
| 5848 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i)); | |
| 5849 } | |
| 5850 | |
| 5851 // If there was a test failure outside of one of the test suites (like in a | |
| 5852 // test environment) include that in the output. | |
| 5853 if (unit_test.ad_hoc_test_result().Failed()) { | |
| 5854 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); | |
| 5855 } | |
| 5856 | |
| 5857 *stream << "</" << kTestsuites << ">\n"; | |
| 5858 } | |
| 5859 | |
| 5860 void XmlUnitTestResultPrinter::PrintXmlTestsList( | |
| 5861 std::ostream* stream, const std::vector<TestSuite*>& test_suites) { | |
| 5862 const std::string kTestsuites = "testsuites"; | |
| 5863 | |
| 5864 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; | |
| 5865 *stream << "<" << kTestsuites; | |
| 5866 | |
| 5867 int total_tests = 0; | |
| 5868 for (auto test_suite : test_suites) { | |
| 5869 total_tests += test_suite->total_test_count(); | |
| 5870 } | |
| 5871 OutputXmlAttribute(stream, kTestsuites, "tests", | |
| 5872 StreamableToString(total_tests)); | |
| 5873 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); | |
| 5874 *stream << ">\n"; | |
| 5875 | |
| 5876 for (auto test_suite : test_suites) { | |
| 5877 PrintXmlTestSuite(stream, *test_suite); | |
| 5878 } | |
| 5879 *stream << "</" << kTestsuites << ">\n"; | |
| 5880 } | |
| 5881 | |
| 5882 // Produces a string representing the test properties in a result as space | |
| 5883 // delimited XML attributes based on the property key="value" pairs. | |
| 5884 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( | |
| 5885 const TestResult& result) { | |
| 5886 Message attributes; | |
| 5887 for (int i = 0; i < result.test_property_count(); ++i) { | |
| 5888 const TestProperty& property = result.GetTestProperty(i); | |
| 5889 attributes << " " << property.key() << "=" | |
| 5890 << "\"" << EscapeXmlAttribute(property.value()) << "\""; | |
| 5891 } | |
| 5892 return attributes.GetString(); | |
| 5893 } | |
| 5894 | |
| 5895 void XmlUnitTestResultPrinter::OutputXmlTestProperties( | |
| 5896 std::ostream* stream, const TestResult& result) { | |
| 5897 const std::string kProperties = "properties"; | |
| 5898 const std::string kProperty = "property"; | |
| 5899 | |
| 5900 if (result.test_property_count() <= 0) { | |
| 5901 return; | |
| 5902 } | |
| 5903 | |
| 5904 *stream << "<" << kProperties << ">\n"; | |
| 5905 for (int i = 0; i < result.test_property_count(); ++i) { | |
| 5906 const TestProperty& property = result.GetTestProperty(i); | |
| 5907 *stream << "<" << kProperty; | |
| 5908 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\""; | |
| 5909 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\""; | |
| 5910 *stream << "/>\n"; | |
| 5911 } | |
| 5912 *stream << "</" << kProperties << ">\n"; | |
| 5913 } | |
| 5914 | |
| 5915 // End XmlUnitTestResultPrinter | |
| 5916 | |
| 5917 // This class generates an JSON output file. | |
| 5918 class JsonUnitTestResultPrinter : public EmptyTestEventListener { | |
| 5919 public: | |
| 5920 explicit JsonUnitTestResultPrinter(const char* output_file); | |
| 5921 | |
| 5922 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; | |
| 5923 | |
| 5924 // Prints an JSON summary of all unit tests. | |
| 5925 static void PrintJsonTestList(::std::ostream* stream, | |
| 5926 const std::vector<TestSuite*>& test_suites); | |
| 5927 | |
| 5928 private: | |
| 5929 // Returns an JSON-escaped copy of the input string str. | |
| 5930 static std::string EscapeJson(const std::string& str); | |
| 5931 | |
| 5932 //// Verifies that the given attribute belongs to the given element and | |
| 5933 //// streams the attribute as JSON. | |
| 5934 static void OutputJsonKey(std::ostream* stream, | |
| 5935 const std::string& element_name, | |
| 5936 const std::string& name, | |
| 5937 const std::string& value, | |
| 5938 const std::string& indent, | |
| 5939 bool comma = true); | |
| 5940 static void OutputJsonKey(std::ostream* stream, | |
| 5941 const std::string& element_name, | |
| 5942 const std::string& name, | |
| 5943 int value, | |
| 5944 const std::string& indent, | |
| 5945 bool comma = true); | |
| 5946 | |
| 5947 // Streams a test suite JSON stanza containing the given test result. | |
| 5948 // | |
| 5949 // Requires: result.Failed() | |
| 5950 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream, | |
| 5951 const TestResult& result); | |
| 5952 | |
| 5953 // Streams a JSON representation of a TestResult object. | |
| 5954 static void OutputJsonTestResult(::std::ostream* stream, | |
| 5955 const TestResult& result); | |
| 5956 | |
| 5957 // Streams a JSON representation of a TestInfo object. | |
| 5958 static void OutputJsonTestInfo(::std::ostream* stream, | |
| 5959 const char* test_suite_name, | |
| 5960 const TestInfo& test_info); | |
| 5961 | |
| 5962 // Prints a JSON representation of a TestSuite object | |
| 5963 static void PrintJsonTestSuite(::std::ostream* stream, | |
| 5964 const TestSuite& test_suite); | |
| 5965 | |
| 5966 // Prints a JSON summary of unit_test to output stream out. | |
| 5967 static void PrintJsonUnitTest(::std::ostream* stream, | |
| 5968 const UnitTest& unit_test); | |
| 5969 | |
| 5970 // Produces a string representing the test properties in a result as | |
| 5971 // a JSON dictionary. | |
| 5972 static std::string TestPropertiesAsJson(const TestResult& result, | |
| 5973 const std::string& indent); | |
| 5974 | |
| 5975 // The output file. | |
| 5976 const std::string output_file_; | |
| 5977 | |
| 5978 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter); | |
| 5979 }; | |
| 5980 | |
| 5981 // Creates a new JsonUnitTestResultPrinter. | |
| 5982 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) | |
| 5983 : output_file_(output_file) { | |
| 5984 if (output_file_.empty()) { | |
| 5985 GTEST_LOG_(FATAL) << "JSON output file may not be null"; | |
| 5986 } | |
| 5987 } | |
| 5988 | |
| 5989 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, | |
| 5990 int /*iteration*/) { | |
| 5991 FILE* jsonout = OpenFileForWriting(output_file_); | |
| 5992 std::stringstream stream; | |
| 5993 PrintJsonUnitTest(&stream, unit_test); | |
| 5994 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str()); | |
| 5995 fclose(jsonout); | |
| 5996 } | |
| 5997 | |
| 5998 // Returns an JSON-escaped copy of the input string str. | |
| 5999 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) { | |
| 6000 Message m; | |
| 6001 | |
| 6002 for (size_t i = 0; i < str.size(); ++i) { | |
| 6003 const char ch = str[i]; | |
| 6004 switch (ch) { | |
| 6005 case '\\': | |
| 6006 case '"': | |
| 6007 case '/': | |
| 6008 m << '\\' << ch; | |
| 6009 break; | |
| 6010 case '\b': | |
| 6011 m << "\\b"; | |
| 6012 break; | |
| 6013 case '\t': | |
| 6014 m << "\\t"; | |
| 6015 break; | |
| 6016 case '\n': | |
| 6017 m << "\\n"; | |
| 6018 break; | |
| 6019 case '\f': | |
| 6020 m << "\\f"; | |
| 6021 break; | |
| 6022 case '\r': | |
| 6023 m << "\\r"; | |
| 6024 break; | |
| 6025 default: | |
| 6026 if (ch < ' ') { | |
| 6027 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch)); | |
| 6028 } else { | |
| 6029 m << ch; | |
| 6030 } | |
| 6031 break; | |
| 6032 } | |
| 6033 } | |
| 6034 | |
| 6035 return m.GetString(); | |
| 6036 } | |
| 6037 | |
| 6038 // The following routines generate an JSON representation of a UnitTest | |
| 6039 // object. | |
| 6040 | |
| 6041 // Formats the given time in milliseconds as seconds. | |
| 6042 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) { | |
| 6043 ::std::stringstream ss; | |
| 6044 ss << (static_cast<double>(ms) * 1e-3) << "s"; | |
| 6045 return ss.str(); | |
| 6046 } | |
| 6047 | |
| 6048 // Converts the given epoch time in milliseconds to a date string in the | |
| 6049 // RFC3339 format, without the timezone information. | |
| 6050 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { | |
| 6051 struct tm time_struct; | |
| 6052 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) | |
| 6053 return ""; | |
| 6054 // YYYY-MM-DDThh:mm:ss | |
| 6055 return StreamableToString(time_struct.tm_year + 1900) + "-" + | |
| 6056 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + | |
| 6057 String::FormatIntWidth2(time_struct.tm_mday) + "T" + | |
| 6058 String::FormatIntWidth2(time_struct.tm_hour) + ":" + | |
| 6059 String::FormatIntWidth2(time_struct.tm_min) + ":" + | |
| 6060 String::FormatIntWidth2(time_struct.tm_sec) + "Z"; | |
| 6061 } | |
| 6062 | |
| 6063 static inline std::string Indent(size_t width) { | |
| 6064 return std::string(width, ' '); | |
| 6065 } | |
| 6066 | |
| 6067 void JsonUnitTestResultPrinter::OutputJsonKey( | |
| 6068 std::ostream* stream, | |
| 6069 const std::string& element_name, | |
| 6070 const std::string& name, | |
| 6071 const std::string& value, | |
| 6072 const std::string& indent, | |
| 6073 bool comma) { | |
| 6074 const std::vector<std::string>& allowed_names = | |
| 6075 GetReservedOutputAttributesForElement(element_name); | |
| 6076 | |
| 6077 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != | |
| 6078 allowed_names.end()) | |
| 6079 << "Key \"" << name << "\" is not allowed for value \"" << element_name | |
| 6080 << "\"."; | |
| 6081 | |
| 6082 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; | |
| 6083 if (comma) | |
| 6084 *stream << ",\n"; | |
| 6085 } | |
| 6086 | |
| 6087 void JsonUnitTestResultPrinter::OutputJsonKey( | |
| 6088 std::ostream* stream, | |
| 6089 const std::string& element_name, | |
| 6090 const std::string& name, | |
| 6091 int value, | |
| 6092 const std::string& indent, | |
| 6093 bool comma) { | |
| 6094 const std::vector<std::string>& allowed_names = | |
| 6095 GetReservedOutputAttributesForElement(element_name); | |
| 6096 | |
| 6097 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != | |
| 6098 allowed_names.end()) | |
| 6099 << "Key \"" << name << "\" is not allowed for value \"" << element_name | |
| 6100 << "\"."; | |
| 6101 | |
| 6102 *stream << indent << "\"" << name << "\": " << StreamableToString(value); | |
| 6103 if (comma) | |
| 6104 *stream << ",\n"; | |
| 6105 } | |
| 6106 | |
| 6107 // Streams a test suite JSON stanza containing the given test result. | |
| 6108 void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult( | |
| 6109 ::std::ostream* stream, const TestResult& result) { | |
| 6110 // Output the boilerplate for a new test suite. | |
| 6111 *stream << Indent(4) << "{\n"; | |
| 6112 OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6)); | |
| 6113 OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6)); | |
| 6114 if (!GTEST_FLAG(list_tests)) { | |
| 6115 OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6)); | |
| 6116 OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6)); | |
| 6117 OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6)); | |
| 6118 OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6)); | |
| 6119 OutputJsonKey(stream, "testsuite", "time", | |
| 6120 FormatTimeInMillisAsDuration(result.elapsed_time()), | |
| 6121 Indent(6)); | |
| 6122 OutputJsonKey(stream, "testsuite", "timestamp", | |
| 6123 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), | |
| 6124 Indent(6)); | |
| 6125 } | |
| 6126 *stream << Indent(6) << "\"testsuite\": [\n"; | |
| 6127 | |
| 6128 // Output the boilerplate for a new test case. | |
| 6129 *stream << Indent(8) << "{\n"; | |
| 6130 OutputJsonKey(stream, "testcase", "name", "", Indent(10)); | |
| 6131 OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10)); | |
| 6132 OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10)); | |
| 6133 OutputJsonKey(stream, "testcase", "timestamp", | |
| 6134 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), | |
| 6135 Indent(10)); | |
| 6136 OutputJsonKey(stream, "testcase", "time", | |
| 6137 FormatTimeInMillisAsDuration(result.elapsed_time()), | |
| 6138 Indent(10)); | |
| 6139 OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false); | |
| 6140 *stream << TestPropertiesAsJson(result, Indent(10)); | |
| 6141 | |
| 6142 // Output the actual test result. | |
| 6143 OutputJsonTestResult(stream, result); | |
| 6144 | |
| 6145 // Finish the test suite. | |
| 6146 *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}"; | |
| 6147 } | |
| 6148 | |
| 6149 // Prints a JSON representation of a TestInfo object. | |
| 6150 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, | |
| 6151 const char* test_suite_name, | |
| 6152 const TestInfo& test_info) { | |
| 6153 const TestResult& result = *test_info.result(); | |
| 6154 const std::string kTestsuite = "testcase"; | |
| 6155 const std::string kIndent = Indent(10); | |
| 6156 | |
| 6157 *stream << Indent(8) << "{\n"; | |
| 6158 OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent); | |
| 6159 | |
| 6160 if (test_info.value_param() != nullptr) { | |
| 6161 OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(), | |
| 6162 kIndent); | |
| 6163 } | |
| 6164 if (test_info.type_param() != nullptr) { | |
| 6165 OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), | |
| 6166 kIndent); | |
| 6167 } | |
| 6168 if (GTEST_FLAG(list_tests)) { | |
| 6169 OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); | |
| 6170 OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); | |
| 6171 *stream << "\n" << Indent(8) << "}"; | |
| 6172 return; | |
| 6173 } | |
| 6174 | |
| 6175 OutputJsonKey(stream, kTestsuite, "status", | |
| 6176 test_info.should_run() ? "RUN" : "NOTRUN", kIndent); | |
| 6177 OutputJsonKey(stream, kTestsuite, "result", | |
| 6178 test_info.should_run() | |
| 6179 ? (result.Skipped() ? "SKIPPED" : "COMPLETED") | |
| 6180 : "SUPPRESSED", | |
| 6181 kIndent); | |
| 6182 OutputJsonKey(stream, kTestsuite, "timestamp", | |
| 6183 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), | |
| 6184 kIndent); | |
| 6185 OutputJsonKey(stream, kTestsuite, "time", | |
| 6186 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); | |
| 6187 OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent, | |
| 6188 false); | |
| 6189 *stream << TestPropertiesAsJson(result, kIndent); | |
| 6190 | |
| 6191 OutputJsonTestResult(stream, result); | |
| 6192 } | |
| 6193 | |
| 6194 void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, | |
| 6195 const TestResult& result) { | |
| 6196 const std::string kIndent = Indent(10); | |
| 6197 | |
| 6198 int failures = 0; | |
| 6199 for (int i = 0; i < result.total_part_count(); ++i) { | |
| 6200 const TestPartResult& part = result.GetTestPartResult(i); | |
| 6201 if (part.failed()) { | |
| 6202 *stream << ",\n"; | |
| 6203 if (++failures == 1) { | |
| 6204 *stream << kIndent << "\"" << "failures" << "\": [\n"; | |
| 6205 } | |
| 6206 const std::string location = | |
| 6207 internal::FormatCompilerIndependentFileLocation(part.file_name(), | |
| 6208 part.line_number()); | |
| 6209 const std::string message = EscapeJson(location + "\n" + part.message()); | |
| 6210 *stream << kIndent << " {\n" | |
| 6211 << kIndent << " \"failure\": \"" << message << "\",\n" | |
| 6212 << kIndent << " \"type\": \"\"\n" | |
| 6213 << kIndent << " }"; | |
| 6214 } | |
| 6215 } | |
| 6216 | |
| 6217 if (failures > 0) | |
| 6218 *stream << "\n" << kIndent << "]"; | |
| 6219 *stream << "\n" << Indent(8) << "}"; | |
| 6220 } | |
| 6221 | |
| 6222 // Prints an JSON representation of a TestSuite object | |
| 6223 void JsonUnitTestResultPrinter::PrintJsonTestSuite( | |
| 6224 std::ostream* stream, const TestSuite& test_suite) { | |
| 6225 const std::string kTestsuite = "testsuite"; | |
| 6226 const std::string kIndent = Indent(6); | |
| 6227 | |
| 6228 *stream << Indent(4) << "{\n"; | |
| 6229 OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); | |
| 6230 OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), | |
| 6231 kIndent); | |
| 6232 if (!GTEST_FLAG(list_tests)) { | |
| 6233 OutputJsonKey(stream, kTestsuite, "failures", | |
| 6234 test_suite.failed_test_count(), kIndent); | |
| 6235 OutputJsonKey(stream, kTestsuite, "disabled", | |
| 6236 test_suite.reportable_disabled_test_count(), kIndent); | |
| 6237 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent); | |
| 6238 OutputJsonKey( | |
| 6239 stream, kTestsuite, "timestamp", | |
| 6240 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()), | |
| 6241 kIndent); | |
| 6242 OutputJsonKey(stream, kTestsuite, "time", | |
| 6243 FormatTimeInMillisAsDuration(test_suite.elapsed_time()), | |
| 6244 kIndent, false); | |
| 6245 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent) | |
| 6246 << ",\n"; | |
| 6247 } | |
| 6248 | |
| 6249 *stream << kIndent << "\"" << kTestsuite << "\": [\n"; | |
| 6250 | |
| 6251 bool comma = false; | |
| 6252 for (int i = 0; i < test_suite.total_test_count(); ++i) { | |
| 6253 if (test_suite.GetTestInfo(i)->is_reportable()) { | |
| 6254 if (comma) { | |
| 6255 *stream << ",\n"; | |
| 6256 } else { | |
| 6257 comma = true; | |
| 6258 } | |
| 6259 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); | |
| 6260 } | |
| 6261 } | |
| 6262 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}"; | |
| 6263 } | |
| 6264 | |
| 6265 // Prints a JSON summary of unit_test to output stream out. | |
| 6266 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, | |
| 6267 const UnitTest& unit_test) { | |
| 6268 const std::string kTestsuites = "testsuites"; | |
| 6269 const std::string kIndent = Indent(2); | |
| 6270 *stream << "{\n"; | |
| 6271 | |
| 6272 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(), | |
| 6273 kIndent); | |
| 6274 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(), | |
| 6275 kIndent); | |
| 6276 OutputJsonKey(stream, kTestsuites, "disabled", | |
| 6277 unit_test.reportable_disabled_test_count(), kIndent); | |
| 6278 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent); | |
| 6279 if (GTEST_FLAG(shuffle)) { | |
| 6280 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(), | |
| 6281 kIndent); | |
| 6282 } | |
| 6283 OutputJsonKey(stream, kTestsuites, "timestamp", | |
| 6284 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()), | |
| 6285 kIndent); | |
| 6286 OutputJsonKey(stream, kTestsuites, "time", | |
| 6287 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent, | |
| 6288 false); | |
| 6289 | |
| 6290 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent) | |
| 6291 << ",\n"; | |
| 6292 | |
| 6293 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); | |
| 6294 *stream << kIndent << "\"" << kTestsuites << "\": [\n"; | |
| 6295 | |
| 6296 bool comma = false; | |
| 6297 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { | |
| 6298 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) { | |
| 6299 if (comma) { | |
| 6300 *stream << ",\n"; | |
| 6301 } else { | |
| 6302 comma = true; | |
| 6303 } | |
| 6304 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i)); | |
| 6305 } | |
| 6306 } | |
| 6307 | |
| 6308 // If there was a test failure outside of one of the test suites (like in a | |
| 6309 // test environment) include that in the output. | |
| 6310 if (unit_test.ad_hoc_test_result().Failed()) { | |
| 6311 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); | |
| 6312 } | |
| 6313 | |
| 6314 *stream << "\n" << kIndent << "]\n" << "}\n"; | |
| 6315 } | |
| 6316 | |
| 6317 void JsonUnitTestResultPrinter::PrintJsonTestList( | |
| 6318 std::ostream* stream, const std::vector<TestSuite*>& test_suites) { | |
| 6319 const std::string kTestsuites = "testsuites"; | |
| 6320 const std::string kIndent = Indent(2); | |
| 6321 *stream << "{\n"; | |
| 6322 int total_tests = 0; | |
| 6323 for (auto test_suite : test_suites) { | |
| 6324 total_tests += test_suite->total_test_count(); | |
| 6325 } | |
| 6326 OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent); | |
| 6327 | |
| 6328 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); | |
| 6329 *stream << kIndent << "\"" << kTestsuites << "\": [\n"; | |
| 6330 | |
| 6331 for (size_t i = 0; i < test_suites.size(); ++i) { | |
| 6332 if (i != 0) { | |
| 6333 *stream << ",\n"; | |
| 6334 } | |
| 6335 PrintJsonTestSuite(stream, *test_suites[i]); | |
| 6336 } | |
| 6337 | |
| 6338 *stream << "\n" | |
| 6339 << kIndent << "]\n" | |
| 6340 << "}\n"; | |
| 6341 } | |
| 6342 // Produces a string representing the test properties in a result as | |
| 6343 // a JSON dictionary. | |
| 6344 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( | |
| 6345 const TestResult& result, const std::string& indent) { | |
| 6346 Message attributes; | |
| 6347 for (int i = 0; i < result.test_property_count(); ++i) { | |
| 6348 const TestProperty& property = result.GetTestProperty(i); | |
| 6349 attributes << ",\n" << indent << "\"" << property.key() << "\": " | |
| 6350 << "\"" << EscapeJson(property.value()) << "\""; | |
| 6351 } | |
| 6352 return attributes.GetString(); | |
| 6353 } | |
| 6354 | |
| 6355 // End JsonUnitTestResultPrinter | |
| 6356 | |
| 6357 #if GTEST_CAN_STREAM_RESULTS_ | |
| 6358 | |
| 6359 // Checks if str contains '=', '&', '%' or '\n' characters. If yes, | |
| 6360 // replaces them by "%xx" where xx is their hexadecimal value. For | |
| 6361 // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) | |
| 6362 // in both time and space -- important as the input str may contain an | |
| 6363 // arbitrarily long test failure message and stack trace. | |
| 6364 std::string StreamingListener::UrlEncode(const char* str) { | |
| 6365 std::string result; | |
| 6366 result.reserve(strlen(str) + 1); | |
| 6367 for (char ch = *str; ch != '\0'; ch = *++str) { | |
| 6368 switch (ch) { | |
| 6369 case '%': | |
| 6370 case '=': | |
| 6371 case '&': | |
| 6372 case '\n': | |
| 6373 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); | |
| 6374 break; | |
| 6375 default: | |
| 6376 result.push_back(ch); | |
| 6377 break; | |
| 6378 } | |
| 6379 } | |
| 6380 return result; | |
| 6381 } | |
| 6382 | |
| 6383 void StreamingListener::SocketWriter::MakeConnection() { | |
| 6384 GTEST_CHECK_(sockfd_ == -1) | |
| 6385 << "MakeConnection() can't be called when there is already a connection."; | |
| 6386 | |
| 6387 addrinfo hints; | |
| 6388 memset(&hints, 0, sizeof(hints)); | |
| 6389 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. | |
| 6390 hints.ai_socktype = SOCK_STREAM; | |
| 6391 addrinfo* servinfo = nullptr; | |
| 6392 | |
| 6393 // Use the getaddrinfo() to get a linked list of IP addresses for | |
| 6394 // the given host name. | |
| 6395 const int error_num = getaddrinfo( | |
| 6396 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); | |
| 6397 if (error_num != 0) { | |
| 6398 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " | |
| 6399 << gai_strerror(error_num); | |
| 6400 } | |
| 6401 | |
| 6402 // Loop through all the results and connect to the first we can. | |
| 6403 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; | |
| 6404 cur_addr = cur_addr->ai_next) { | |
| 6405 sockfd_ = socket( | |
| 6406 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); | |
| 6407 if (sockfd_ != -1) { | |
| 6408 // Connect the client socket to the server socket. | |
| 6409 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { | |
| 6410 close(sockfd_); | |
| 6411 sockfd_ = -1; | |
| 6412 } | |
| 6413 } | |
| 6414 } | |
| 6415 | |
| 6416 freeaddrinfo(servinfo); // all done with this structure | |
| 6417 | |
| 6418 if (sockfd_ == -1) { | |
| 6419 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " | |
| 6420 << host_name_ << ":" << port_num_; | |
| 6421 } | |
| 6422 } | |
| 6423 | |
| 6424 // End of class Streaming Listener | |
| 6425 #endif // GTEST_CAN_STREAM_RESULTS__ | |
| 6426 | |
| 6427 // class OsStackTraceGetter | |
| 6428 | |
| 6429 const char* const OsStackTraceGetterInterface::kElidedFramesMarker = | |
| 6430 "... " GTEST_NAME_ " internal frames ..."; | |
| 6431 | |
| 6432 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) | |
| 6433 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6434 #if GTEST_HAS_ABSL | |
| 6435 std::string result; | |
| 6436 | |
| 6437 if (max_depth <= 0) { | |
| 6438 return result; | |
| 6439 } | |
| 6440 | |
| 6441 max_depth = std::min(max_depth, kMaxStackTraceDepth); | |
| 6442 | |
| 6443 std::vector<void*> raw_stack(max_depth); | |
| 6444 // Skips the frames requested by the caller, plus this function. | |
| 6445 const int raw_stack_size = | |
| 6446 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); | |
| 6447 | |
| 6448 void* caller_frame = nullptr; | |
| 6449 { | |
| 6450 MutexLock lock(&mutex_); | |
| 6451 caller_frame = caller_frame_; | |
| 6452 } | |
| 6453 | |
| 6454 for (int i = 0; i < raw_stack_size; ++i) { | |
| 6455 if (raw_stack[i] == caller_frame && | |
| 6456 !GTEST_FLAG(show_internal_stack_frames)) { | |
| 6457 // Add a marker to the trace and stop adding frames. | |
| 6458 absl::StrAppend(&result, kElidedFramesMarker, "\n"); | |
| 6459 break; | |
| 6460 } | |
| 6461 | |
| 6462 char tmp[1024]; | |
| 6463 const char* symbol = "(unknown)"; | |
| 6464 if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { | |
| 6465 symbol = tmp; | |
| 6466 } | |
| 6467 | |
| 6468 char line[1024]; | |
| 6469 snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); | |
| 6470 result += line; | |
| 6471 } | |
| 6472 | |
| 6473 return result; | |
| 6474 | |
| 6475 #else // !GTEST_HAS_ABSL | |
| 6476 static_cast<void>(max_depth); | |
| 6477 static_cast<void>(skip_count); | |
| 6478 return ""; | |
| 6479 #endif // GTEST_HAS_ABSL | |
| 6480 } | |
| 6481 | |
| 6482 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6483 #if GTEST_HAS_ABSL | |
| 6484 void* caller_frame = nullptr; | |
| 6485 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { | |
| 6486 caller_frame = nullptr; | |
| 6487 } | |
| 6488 | |
| 6489 MutexLock lock(&mutex_); | |
| 6490 caller_frame_ = caller_frame; | |
| 6491 #endif // GTEST_HAS_ABSL | |
| 6492 } | |
| 6493 | |
| 6494 // A helper class that creates the premature-exit file in its | |
| 6495 // constructor and deletes the file in its destructor. | |
| 6496 class ScopedPrematureExitFile { | |
| 6497 public: | |
| 6498 explicit ScopedPrematureExitFile(const char* premature_exit_filepath) | |
| 6499 : premature_exit_filepath_(premature_exit_filepath ? | |
| 6500 premature_exit_filepath : "") { | |
| 6501 // If a path to the premature-exit file is specified... | |
| 6502 if (!premature_exit_filepath_.empty()) { | |
| 6503 // create the file with a single "0" character in it. I/O | |
| 6504 // errors are ignored as there's nothing better we can do and we | |
| 6505 // don't want to fail the test because of this. | |
| 6506 FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); | |
| 6507 fwrite("0", 1, 1, pfile); | |
| 6508 fclose(pfile); | |
| 6509 } | |
| 6510 } | |
| 6511 | |
| 6512 ~ScopedPrematureExitFile() { | |
| 6513 #if !defined GTEST_OS_ESP8266 | |
| 6514 if (!premature_exit_filepath_.empty()) { | |
| 6515 int retval = remove(premature_exit_filepath_.c_str()); | |
| 6516 if (retval) { | |
| 6517 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \"" | |
| 6518 << premature_exit_filepath_ << "\" with error " | |
| 6519 << retval; | |
| 6520 } | |
| 6521 } | |
| 6522 #endif | |
| 6523 } | |
| 6524 | |
| 6525 private: | |
| 6526 const std::string premature_exit_filepath_; | |
| 6527 | |
| 6528 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); | |
| 6529 }; | |
| 6530 | |
| 6531 } // namespace internal | |
| 6532 | |
| 6533 // class TestEventListeners | |
| 6534 | |
| 6535 TestEventListeners::TestEventListeners() | |
| 6536 : repeater_(new internal::TestEventRepeater()), | |
| 6537 default_result_printer_(nullptr), | |
| 6538 default_xml_generator_(nullptr) {} | |
| 6539 | |
| 6540 TestEventListeners::~TestEventListeners() { delete repeater_; } | |
| 6541 | |
| 6542 // Returns the standard listener responsible for the default console | |
| 6543 // output. Can be removed from the listeners list to shut down default | |
| 6544 // console output. Note that removing this object from the listener list | |
| 6545 // with Release transfers its ownership to the user. | |
| 6546 void TestEventListeners::Append(TestEventListener* listener) { | |
| 6547 repeater_->Append(listener); | |
| 6548 } | |
| 6549 | |
| 6550 // Removes the given event listener from the list and returns it. It then | |
| 6551 // becomes the caller's responsibility to delete the listener. Returns | |
| 6552 // NULL if the listener is not found in the list. | |
| 6553 TestEventListener* TestEventListeners::Release(TestEventListener* listener) { | |
| 6554 if (listener == default_result_printer_) | |
| 6555 default_result_printer_ = nullptr; | |
| 6556 else if (listener == default_xml_generator_) | |
| 6557 default_xml_generator_ = nullptr; | |
| 6558 return repeater_->Release(listener); | |
| 6559 } | |
| 6560 | |
| 6561 // Returns repeater that broadcasts the TestEventListener events to all | |
| 6562 // subscribers. | |
| 6563 TestEventListener* TestEventListeners::repeater() { return repeater_; } | |
| 6564 | |
| 6565 // Sets the default_result_printer attribute to the provided listener. | |
| 6566 // The listener is also added to the listener list and previous | |
| 6567 // default_result_printer is removed from it and deleted. The listener can | |
| 6568 // also be NULL in which case it will not be added to the list. Does | |
| 6569 // nothing if the previous and the current listener objects are the same. | |
| 6570 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { | |
| 6571 if (default_result_printer_ != listener) { | |
| 6572 // It is an error to pass this method a listener that is already in the | |
| 6573 // list. | |
| 6574 delete Release(default_result_printer_); | |
| 6575 default_result_printer_ = listener; | |
| 6576 if (listener != nullptr) Append(listener); | |
| 6577 } | |
| 6578 } | |
| 6579 | |
| 6580 // Sets the default_xml_generator attribute to the provided listener. The | |
| 6581 // listener is also added to the listener list and previous | |
| 6582 // default_xml_generator is removed from it and deleted. The listener can | |
| 6583 // also be NULL in which case it will not be added to the list. Does | |
| 6584 // nothing if the previous and the current listener objects are the same. | |
| 6585 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { | |
| 6586 if (default_xml_generator_ != listener) { | |
| 6587 // It is an error to pass this method a listener that is already in the | |
| 6588 // list. | |
| 6589 delete Release(default_xml_generator_); | |
| 6590 default_xml_generator_ = listener; | |
| 6591 if (listener != nullptr) Append(listener); | |
| 6592 } | |
| 6593 } | |
| 6594 | |
| 6595 // Controls whether events will be forwarded by the repeater to the | |
| 6596 // listeners in the list. | |
| 6597 bool TestEventListeners::EventForwardingEnabled() const { | |
| 6598 return repeater_->forwarding_enabled(); | |
| 6599 } | |
| 6600 | |
| 6601 void TestEventListeners::SuppressEventForwarding() { | |
| 6602 repeater_->set_forwarding_enabled(false); | |
| 6603 } | |
| 6604 | |
| 6605 // class UnitTest | |
| 6606 | |
| 6607 // Gets the singleton UnitTest object. The first time this method is | |
| 6608 // called, a UnitTest object is constructed and returned. Consecutive | |
| 6609 // calls will return the same object. | |
| 6610 // | |
| 6611 // We don't protect this under mutex_ as a user is not supposed to | |
| 6612 // call this before main() starts, from which point on the return | |
| 6613 // value will never change. | |
| 6614 UnitTest* UnitTest::GetInstance() { | |
| 6615 // CodeGear C++Builder insists on a public destructor for the | |
| 6616 // default implementation. Use this implementation to keep good OO | |
| 6617 // design with private destructor. | |
| 6618 | |
| 6619 #if defined(__BORLANDC__) | |
| 6620 static UnitTest* const instance = new UnitTest; | |
| 6621 return instance; | |
| 6622 #else | |
| 6623 static UnitTest instance; | |
| 6624 return &instance; | |
| 6625 #endif // defined(__BORLANDC__) | |
| 6626 } | |
| 6627 | |
| 6628 // Gets the number of successful test suites. | |
| 6629 int UnitTest::successful_test_suite_count() const { | |
| 6630 return impl()->successful_test_suite_count(); | |
| 6631 } | |
| 6632 | |
| 6633 // Gets the number of failed test suites. | |
| 6634 int UnitTest::failed_test_suite_count() const { | |
| 6635 return impl()->failed_test_suite_count(); | |
| 6636 } | |
| 6637 | |
| 6638 // Gets the number of all test suites. | |
| 6639 int UnitTest::total_test_suite_count() const { | |
| 6640 return impl()->total_test_suite_count(); | |
| 6641 } | |
| 6642 | |
| 6643 // Gets the number of all test suites that contain at least one test | |
| 6644 // that should run. | |
| 6645 int UnitTest::test_suite_to_run_count() const { | |
| 6646 return impl()->test_suite_to_run_count(); | |
| 6647 } | |
| 6648 | |
| 6649 // Legacy API is deprecated but still available | |
| 6650 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 6651 int UnitTest::successful_test_case_count() const { | |
| 6652 return impl()->successful_test_suite_count(); | |
| 6653 } | |
| 6654 int UnitTest::failed_test_case_count() const { | |
| 6655 return impl()->failed_test_suite_count(); | |
| 6656 } | |
| 6657 int UnitTest::total_test_case_count() const { | |
| 6658 return impl()->total_test_suite_count(); | |
| 6659 } | |
| 6660 int UnitTest::test_case_to_run_count() const { | |
| 6661 return impl()->test_suite_to_run_count(); | |
| 6662 } | |
| 6663 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 6664 | |
| 6665 // Gets the number of successful tests. | |
| 6666 int UnitTest::successful_test_count() const { | |
| 6667 return impl()->successful_test_count(); | |
| 6668 } | |
| 6669 | |
| 6670 // Gets the number of skipped tests. | |
| 6671 int UnitTest::skipped_test_count() const { | |
| 6672 return impl()->skipped_test_count(); | |
| 6673 } | |
| 6674 | |
| 6675 // Gets the number of failed tests. | |
| 6676 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } | |
| 6677 | |
| 6678 // Gets the number of disabled tests that will be reported in the XML report. | |
| 6679 int UnitTest::reportable_disabled_test_count() const { | |
| 6680 return impl()->reportable_disabled_test_count(); | |
| 6681 } | |
| 6682 | |
| 6683 // Gets the number of disabled tests. | |
| 6684 int UnitTest::disabled_test_count() const { | |
| 6685 return impl()->disabled_test_count(); | |
| 6686 } | |
| 6687 | |
| 6688 // Gets the number of tests to be printed in the XML report. | |
| 6689 int UnitTest::reportable_test_count() const { | |
| 6690 return impl()->reportable_test_count(); | |
| 6691 } | |
| 6692 | |
| 6693 // Gets the number of all tests. | |
| 6694 int UnitTest::total_test_count() const { return impl()->total_test_count(); } | |
| 6695 | |
| 6696 // Gets the number of tests that should run. | |
| 6697 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } | |
| 6698 | |
| 6699 // Gets the time of the test program start, in ms from the start of the | |
| 6700 // UNIX epoch. | |
| 6701 internal::TimeInMillis UnitTest::start_timestamp() const { | |
| 6702 return impl()->start_timestamp(); | |
| 6703 } | |
| 6704 | |
| 6705 // Gets the elapsed time, in milliseconds. | |
| 6706 internal::TimeInMillis UnitTest::elapsed_time() const { | |
| 6707 return impl()->elapsed_time(); | |
| 6708 } | |
| 6709 | |
| 6710 // Returns true if and only if the unit test passed (i.e. all test suites | |
| 6711 // passed). | |
| 6712 bool UnitTest::Passed() const { return impl()->Passed(); } | |
| 6713 | |
| 6714 // Returns true if and only if the unit test failed (i.e. some test suite | |
| 6715 // failed or something outside of all tests failed). | |
| 6716 bool UnitTest::Failed() const { return impl()->Failed(); } | |
| 6717 | |
| 6718 // Gets the i-th test suite among all the test suites. i can range from 0 to | |
| 6719 // total_test_suite_count() - 1. If i is not in that range, returns NULL. | |
| 6720 const TestSuite* UnitTest::GetTestSuite(int i) const { | |
| 6721 return impl()->GetTestSuite(i); | |
| 6722 } | |
| 6723 | |
| 6724 // Legacy API is deprecated but still available | |
| 6725 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 6726 const TestCase* UnitTest::GetTestCase(int i) const { | |
| 6727 return impl()->GetTestCase(i); | |
| 6728 } | |
| 6729 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 6730 | |
| 6731 // Returns the TestResult containing information on test failures and | |
| 6732 // properties logged outside of individual test suites. | |
| 6733 const TestResult& UnitTest::ad_hoc_test_result() const { | |
| 6734 return *impl()->ad_hoc_test_result(); | |
| 6735 } | |
| 6736 | |
| 6737 // Gets the i-th test suite among all the test suites. i can range from 0 to | |
| 6738 // total_test_suite_count() - 1. If i is not in that range, returns NULL. | |
| 6739 TestSuite* UnitTest::GetMutableTestSuite(int i) { | |
| 6740 return impl()->GetMutableSuiteCase(i); | |
| 6741 } | |
| 6742 | |
| 6743 // Returns the list of event listeners that can be used to track events | |
| 6744 // inside Google Test. | |
| 6745 TestEventListeners& UnitTest::listeners() { | |
| 6746 return *impl()->listeners(); | |
| 6747 } | |
| 6748 | |
| 6749 // Registers and returns a global test environment. When a test | |
| 6750 // program is run, all global test environments will be set-up in the | |
| 6751 // order they were registered. After all tests in the program have | |
| 6752 // finished, all global test environments will be torn-down in the | |
| 6753 // *reverse* order they were registered. | |
| 6754 // | |
| 6755 // The UnitTest object takes ownership of the given environment. | |
| 6756 // | |
| 6757 // We don't protect this under mutex_, as we only support calling it | |
| 6758 // from the main thread. | |
| 6759 Environment* UnitTest::AddEnvironment(Environment* env) { | |
| 6760 if (env == nullptr) { | |
| 6761 return nullptr; | |
| 6762 } | |
| 6763 | |
| 6764 impl_->environments().push_back(env); | |
| 6765 return env; | |
| 6766 } | |
| 6767 | |
| 6768 // Adds a TestPartResult to the current TestResult object. All Google Test | |
| 6769 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call | |
| 6770 // this to report their results. The user code should use the | |
| 6771 // assertion macros instead of calling this directly. | |
| 6772 void UnitTest::AddTestPartResult( | |
| 6773 TestPartResult::Type result_type, | |
| 6774 const char* file_name, | |
| 6775 int line_number, | |
| 6776 const std::string& message, | |
| 6777 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6778 Message msg; | |
| 6779 msg << message; | |
| 6780 | |
| 6781 internal::MutexLock lock(&mutex_); | |
| 6782 if (impl_->gtest_trace_stack().size() > 0) { | |
| 6783 msg << "\n" << GTEST_NAME_ << " trace:"; | |
| 6784 | |
| 6785 for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { | |
| 6786 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; | |
| 6787 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) | |
| 6788 << " " << trace.message; | |
| 6789 } | |
| 6790 } | |
| 6791 | |
| 6792 if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) { | |
| 6793 msg << internal::kStackTraceMarker << os_stack_trace; | |
| 6794 } | |
| 6795 | |
| 6796 const TestPartResult result = TestPartResult( | |
| 6797 result_type, file_name, line_number, msg.GetString().c_str()); | |
| 6798 impl_->GetTestPartResultReporterForCurrentThread()-> | |
| 6799 ReportTestPartResult(result); | |
| 6800 | |
| 6801 if (result_type != TestPartResult::kSuccess && | |
| 6802 result_type != TestPartResult::kSkip) { | |
| 6803 // gtest_break_on_failure takes precedence over | |
| 6804 // gtest_throw_on_failure. This allows a user to set the latter | |
| 6805 // in the code (perhaps in order to use Google Test assertions | |
| 6806 // with another testing framework) and specify the former on the | |
| 6807 // command line for debugging. | |
| 6808 if (GTEST_FLAG(break_on_failure)) { | |
| 6809 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT | |
| 6810 // Using DebugBreak on Windows allows gtest to still break into a debugger | |
| 6811 // when a failure happens and both the --gtest_break_on_failure and | |
| 6812 // the --gtest_catch_exceptions flags are specified. | |
| 6813 DebugBreak(); | |
| 6814 #elif (!defined(__native_client__)) && \ | |
| 6815 ((defined(__clang__) || defined(__GNUC__)) && \ | |
| 6816 (defined(__x86_64__) || defined(__i386__))) | |
| 6817 // with clang/gcc we can achieve the same effect on x86 by invoking int3 | |
| 6818 asm("int3"); | |
| 6819 #else | |
| 6820 // Dereference nullptr through a volatile pointer to prevent the compiler | |
| 6821 // from removing. We use this rather than abort() or __builtin_trap() for | |
| 6822 // portability: some debuggers don't correctly trap abort(). | |
| 6823 *static_cast<volatile int*>(nullptr) = 1; | |
| 6824 #endif // GTEST_OS_WINDOWS | |
| 6825 } else if (GTEST_FLAG(throw_on_failure)) { | |
| 6826 #if GTEST_HAS_EXCEPTIONS | |
| 6827 throw internal::GoogleTestFailureException(result); | |
| 6828 #else | |
| 6829 // We cannot call abort() as it generates a pop-up in debug mode | |
| 6830 // that cannot be suppressed in VC 7.1 or below. | |
| 6831 exit(1); | |
| 6832 #endif | |
| 6833 } | |
| 6834 } | |
| 6835 } | |
| 6836 | |
| 6837 // Adds a TestProperty to the current TestResult object when invoked from | |
| 6838 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked | |
| 6839 // from SetUpTestSuite or TearDownTestSuite, or to the global property set | |
| 6840 // when invoked elsewhere. If the result already contains a property with | |
| 6841 // the same key, the value will be updated. | |
| 6842 void UnitTest::RecordProperty(const std::string& key, | |
| 6843 const std::string& value) { | |
| 6844 impl_->RecordProperty(TestProperty(key, value)); | |
| 6845 } | |
| 6846 | |
| 6847 // Runs all tests in this UnitTest object and prints the result. | |
| 6848 // Returns 0 if successful, or 1 otherwise. | |
| 6849 // | |
| 6850 // We don't protect this under mutex_, as we only support calling it | |
| 6851 // from the main thread. | |
| 6852 int UnitTest::Run() { | |
| 6853 const bool in_death_test_child_process = | |
| 6854 internal::GTEST_FLAG(internal_run_death_test).length() > 0; | |
| 6855 | |
| 6856 // Google Test implements this protocol for catching that a test | |
| 6857 // program exits before returning control to Google Test: | |
| 6858 // | |
| 6859 // 1. Upon start, Google Test creates a file whose absolute path | |
| 6860 // is specified by the environment variable | |
| 6861 // TEST_PREMATURE_EXIT_FILE. | |
| 6862 // 2. When Google Test has finished its work, it deletes the file. | |
| 6863 // | |
| 6864 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before | |
| 6865 // running a Google-Test-based test program and check the existence | |
| 6866 // of the file at the end of the test execution to see if it has | |
| 6867 // exited prematurely. | |
| 6868 | |
| 6869 // If we are in the child process of a death test, don't | |
| 6870 // create/delete the premature exit file, as doing so is unnecessary | |
| 6871 // and will confuse the parent process. Otherwise, create/delete | |
| 6872 // the file upon entering/leaving this function. If the program | |
| 6873 // somehow exits before this function has a chance to return, the | |
| 6874 // premature-exit file will be left undeleted, causing a test runner | |
| 6875 // that understands the premature-exit-file protocol to report the | |
| 6876 // test as having failed. | |
| 6877 const internal::ScopedPrematureExitFile premature_exit_file( | |
| 6878 in_death_test_child_process | |
| 6879 ? nullptr | |
| 6880 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); | |
| 6881 | |
| 6882 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be | |
| 6883 // used for the duration of the program. | |
| 6884 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); | |
| 6885 | |
| 6886 #if GTEST_OS_WINDOWS | |
| 6887 // Either the user wants Google Test to catch exceptions thrown by the | |
| 6888 // tests or this is executing in the context of death test child | |
| 6889 // process. In either case the user does not want to see pop-up dialogs | |
| 6890 // about crashes - they are expected. | |
| 6891 if (impl()->catch_exceptions() || in_death_test_child_process) { | |
| 6892 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT | |
| 6893 // SetErrorMode doesn't exist on CE. | |
| 6894 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | | |
| 6895 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); | |
| 6896 # endif // !GTEST_OS_WINDOWS_MOBILE | |
| 6897 | |
| 6898 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE | |
| 6899 // Death test children can be terminated with _abort(). On Windows, | |
| 6900 // _abort() can show a dialog with a warning message. This forces the | |
| 6901 // abort message to go to stderr instead. | |
| 6902 _set_error_mode(_OUT_TO_STDERR); | |
| 6903 # endif | |
| 6904 | |
| 6905 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE | |
| 6906 // In the debug version, Visual Studio pops up a separate dialog | |
| 6907 // offering a choice to debug the aborted program. We need to suppress | |
| 6908 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement | |
| 6909 // executed. Google Test will notify the user of any unexpected | |
| 6910 // failure via stderr. | |
| 6911 if (!GTEST_FLAG(break_on_failure)) | |
| 6912 _set_abort_behavior( | |
| 6913 0x0, // Clear the following flags: | |
| 6914 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. | |
| 6915 | |
| 6916 // In debug mode, the Windows CRT can crash with an assertion over invalid | |
| 6917 // input (e.g. passing an invalid file descriptor). The default handling | |
| 6918 // for these assertions is to pop up a dialog and wait for user input. | |
| 6919 // Instead ask the CRT to dump such assertions to stderr non-interactively. | |
| 6920 if (!IsDebuggerPresent()) { | |
| 6921 (void)_CrtSetReportMode(_CRT_ASSERT, | |
| 6922 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); | |
| 6923 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); | |
| 6924 } | |
| 6925 # endif | |
| 6926 } | |
| 6927 #endif // GTEST_OS_WINDOWS | |
| 6928 | |
| 6929 return internal::HandleExceptionsInMethodIfSupported( | |
| 6930 impl(), | |
| 6931 &internal::UnitTestImpl::RunAllTests, | |
| 6932 "auxiliary test code (environments or event listeners)") ? 0 : 1; | |
| 6933 } | |
| 6934 | |
| 6935 // Returns the working directory when the first TEST() or TEST_F() was | |
| 6936 // executed. | |
| 6937 const char* UnitTest::original_working_dir() const { | |
| 6938 return impl_->original_working_dir_.c_str(); | |
| 6939 } | |
| 6940 | |
| 6941 // Returns the TestSuite object for the test that's currently running, | |
| 6942 // or NULL if no test is running. | |
| 6943 const TestSuite* UnitTest::current_test_suite() const | |
| 6944 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6945 internal::MutexLock lock(&mutex_); | |
| 6946 return impl_->current_test_suite(); | |
| 6947 } | |
| 6948 | |
| 6949 // Legacy API is still available but deprecated | |
| 6950 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ | |
| 6951 const TestCase* UnitTest::current_test_case() const | |
| 6952 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6953 internal::MutexLock lock(&mutex_); | |
| 6954 return impl_->current_test_suite(); | |
| 6955 } | |
| 6956 #endif | |
| 6957 | |
| 6958 // Returns the TestInfo object for the test that's currently running, | |
| 6959 // or NULL if no test is running. | |
| 6960 const TestInfo* UnitTest::current_test_info() const | |
| 6961 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6962 internal::MutexLock lock(&mutex_); | |
| 6963 return impl_->current_test_info(); | |
| 6964 } | |
| 6965 | |
| 6966 // Returns the random seed used at the start of the current test run. | |
| 6967 int UnitTest::random_seed() const { return impl_->random_seed(); } | |
| 6968 | |
| 6969 // Returns ParameterizedTestSuiteRegistry object used to keep track of | |
| 6970 // value-parameterized tests and instantiate and register them. | |
| 6971 internal::ParameterizedTestSuiteRegistry& | |
| 6972 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6973 return impl_->parameterized_test_registry(); | |
| 6974 } | |
| 6975 | |
| 6976 // Creates an empty UnitTest. | |
| 6977 UnitTest::UnitTest() { | |
| 6978 impl_ = new internal::UnitTestImpl(this); | |
| 6979 } | |
| 6980 | |
| 6981 // Destructor of UnitTest. | |
| 6982 UnitTest::~UnitTest() { | |
| 6983 delete impl_; | |
| 6984 } | |
| 6985 | |
| 6986 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread | |
| 6987 // Google Test trace stack. | |
| 6988 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) | |
| 6989 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6990 internal::MutexLock lock(&mutex_); | |
| 6991 impl_->gtest_trace_stack().push_back(trace); | |
| 6992 } | |
| 6993 | |
| 6994 // Pops a trace from the per-thread Google Test trace stack. | |
| 6995 void UnitTest::PopGTestTrace() | |
| 6996 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 6997 internal::MutexLock lock(&mutex_); | |
| 6998 impl_->gtest_trace_stack().pop_back(); | |
| 6999 } | |
| 7000 | |
| 7001 namespace internal { | |
| 7002 | |
| 7003 UnitTestImpl::UnitTestImpl(UnitTest* parent) | |
| 7004 : parent_(parent), | |
| 7005 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) | |
| 7006 default_global_test_part_result_reporter_(this), | |
| 7007 default_per_thread_test_part_result_reporter_(this), | |
| 7008 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( | |
| 7009 &default_global_test_part_result_reporter_), | |
| 7010 per_thread_test_part_result_reporter_( | |
| 7011 &default_per_thread_test_part_result_reporter_), | |
| 7012 parameterized_test_registry_(), | |
| 7013 parameterized_tests_registered_(false), | |
| 7014 last_death_test_suite_(-1), | |
| 7015 current_test_suite_(nullptr), | |
| 7016 current_test_info_(nullptr), | |
| 7017 ad_hoc_test_result_(), | |
| 7018 os_stack_trace_getter_(nullptr), | |
| 7019 post_flag_parse_init_performed_(false), | |
| 7020 random_seed_(0), // Will be overridden by the flag before first use. | |
| 7021 random_(0), // Will be reseeded before first use. | |
| 7022 start_timestamp_(0), | |
| 7023 elapsed_time_(0), | |
| 7024 #if GTEST_HAS_DEATH_TEST | |
| 7025 death_test_factory_(new DefaultDeathTestFactory), | |
| 7026 #endif | |
| 7027 // Will be overridden by the flag before first use. | |
| 7028 catch_exceptions_(false) { | |
| 7029 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); | |
| 7030 } | |
| 7031 | |
| 7032 UnitTestImpl::~UnitTestImpl() { | |
| 7033 // Deletes every TestSuite. | |
| 7034 ForEach(test_suites_, internal::Delete<TestSuite>); | |
| 7035 | |
| 7036 // Deletes every Environment. | |
| 7037 ForEach(environments_, internal::Delete<Environment>); | |
| 7038 | |
| 7039 delete os_stack_trace_getter_; | |
| 7040 } | |
| 7041 | |
| 7042 // Adds a TestProperty to the current TestResult object when invoked in a | |
| 7043 // context of a test, to current test suite's ad_hoc_test_result when invoke | |
| 7044 // from SetUpTestSuite/TearDownTestSuite, or to the global property set | |
| 7045 // otherwise. If the result already contains a property with the same key, | |
| 7046 // the value will be updated. | |
| 7047 void UnitTestImpl::RecordProperty(const TestProperty& test_property) { | |
| 7048 std::string xml_element; | |
| 7049 TestResult* test_result; // TestResult appropriate for property recording. | |
| 7050 | |
| 7051 if (current_test_info_ != nullptr) { | |
| 7052 xml_element = "testcase"; | |
| 7053 test_result = &(current_test_info_->result_); | |
| 7054 } else if (current_test_suite_ != nullptr) { | |
| 7055 xml_element = "testsuite"; | |
| 7056 test_result = &(current_test_suite_->ad_hoc_test_result_); | |
| 7057 } else { | |
| 7058 xml_element = "testsuites"; | |
| 7059 test_result = &ad_hoc_test_result_; | |
| 7060 } | |
| 7061 test_result->RecordProperty(xml_element, test_property); | |
| 7062 } | |
| 7063 | |
| 7064 #if GTEST_HAS_DEATH_TEST | |
| 7065 // Disables event forwarding if the control is currently in a death test | |
| 7066 // subprocess. Must not be called before InitGoogleTest. | |
| 7067 void UnitTestImpl::SuppressTestEventsIfInSubprocess() { | |
| 7068 if (internal_run_death_test_flag_.get() != nullptr) | |
| 7069 listeners()->SuppressEventForwarding(); | |
| 7070 } | |
| 7071 #endif // GTEST_HAS_DEATH_TEST | |
| 7072 | |
| 7073 // Initializes event listeners performing XML output as specified by | |
| 7074 // UnitTestOptions. Must not be called before InitGoogleTest. | |
| 7075 void UnitTestImpl::ConfigureXmlOutput() { | |
| 7076 const std::string& output_format = UnitTestOptions::GetOutputFormat(); | |
| 7077 if (output_format == "xml") { | |
| 7078 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( | |
| 7079 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); | |
| 7080 } else if (output_format == "json") { | |
| 7081 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter( | |
| 7082 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); | |
| 7083 } else if (output_format != "") { | |
| 7084 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \"" | |
| 7085 << output_format << "\" ignored."; | |
| 7086 } | |
| 7087 } | |
| 7088 | |
| 7089 #if GTEST_CAN_STREAM_RESULTS_ | |
| 7090 // Initializes event listeners for streaming test results in string form. | |
| 7091 // Must not be called before InitGoogleTest. | |
| 7092 void UnitTestImpl::ConfigureStreamingOutput() { | |
| 7093 const std::string& target = GTEST_FLAG(stream_result_to); | |
| 7094 if (!target.empty()) { | |
| 7095 const size_t pos = target.find(':'); | |
| 7096 if (pos != std::string::npos) { | |
| 7097 listeners()->Append(new StreamingListener(target.substr(0, pos), | |
| 7098 target.substr(pos+1))); | |
| 7099 } else { | |
| 7100 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target | |
| 7101 << "\" ignored."; | |
| 7102 } | |
| 7103 } | |
| 7104 } | |
| 7105 #endif // GTEST_CAN_STREAM_RESULTS_ | |
| 7106 | |
| 7107 // Performs initialization dependent upon flag values obtained in | |
| 7108 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to | |
| 7109 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest | |
| 7110 // this function is also called from RunAllTests. Since this function can be | |
| 7111 // called more than once, it has to be idempotent. | |
| 7112 void UnitTestImpl::PostFlagParsingInit() { | |
| 7113 // Ensures that this function does not execute more than once. | |
| 7114 if (!post_flag_parse_init_performed_) { | |
| 7115 post_flag_parse_init_performed_ = true; | |
| 7116 | |
| 7117 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) | |
| 7118 // Register to send notifications about key process state changes. | |
| 7119 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); | |
| 7120 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) | |
| 7121 | |
| 7122 #if GTEST_HAS_DEATH_TEST | |
| 7123 InitDeathTestSubprocessControlInfo(); | |
| 7124 SuppressTestEventsIfInSubprocess(); | |
| 7125 #endif // GTEST_HAS_DEATH_TEST | |
| 7126 | |
| 7127 // Registers parameterized tests. This makes parameterized tests | |
| 7128 // available to the UnitTest reflection API without running | |
| 7129 // RUN_ALL_TESTS. | |
| 7130 RegisterParameterizedTests(); | |
| 7131 | |
| 7132 // Configures listeners for XML output. This makes it possible for users | |
| 7133 // to shut down the default XML output before invoking RUN_ALL_TESTS. | |
| 7134 ConfigureXmlOutput(); | |
| 7135 | |
| 7136 if (GTEST_FLAG(brief)) { | |
| 7137 listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter); | |
| 7138 } | |
| 7139 | |
| 7140 #if GTEST_CAN_STREAM_RESULTS_ | |
| 7141 // Configures listeners for streaming test results to the specified server. | |
| 7142 ConfigureStreamingOutput(); | |
| 7143 #endif // GTEST_CAN_STREAM_RESULTS_ | |
| 7144 | |
| 7145 #if GTEST_HAS_ABSL | |
| 7146 if (GTEST_FLAG(install_failure_signal_handler)) { | |
| 7147 absl::FailureSignalHandlerOptions options; | |
| 7148 absl::InstallFailureSignalHandler(options); | |
| 7149 } | |
| 7150 #endif // GTEST_HAS_ABSL | |
| 7151 } | |
| 7152 } | |
| 7153 | |
| 7154 // A predicate that checks the name of a TestSuite against a known | |
| 7155 // value. | |
| 7156 // | |
| 7157 // This is used for implementation of the UnitTest class only. We put | |
| 7158 // it in the anonymous namespace to prevent polluting the outer | |
| 7159 // namespace. | |
| 7160 // | |
| 7161 // TestSuiteNameIs is copyable. | |
| 7162 class TestSuiteNameIs { | |
| 7163 public: | |
| 7164 // Constructor. | |
| 7165 explicit TestSuiteNameIs(const std::string& name) : name_(name) {} | |
| 7166 | |
| 7167 // Returns true if and only if the name of test_suite matches name_. | |
| 7168 bool operator()(const TestSuite* test_suite) const { | |
| 7169 return test_suite != nullptr && | |
| 7170 strcmp(test_suite->name(), name_.c_str()) == 0; | |
| 7171 } | |
| 7172 | |
| 7173 private: | |
| 7174 std::string name_; | |
| 7175 }; | |
| 7176 | |
| 7177 // Finds and returns a TestSuite with the given name. If one doesn't | |
| 7178 // exist, creates one and returns it. It's the CALLER'S | |
| 7179 // RESPONSIBILITY to ensure that this function is only called WHEN THE | |
| 7180 // TESTS ARE NOT SHUFFLED. | |
| 7181 // | |
| 7182 // Arguments: | |
| 7183 // | |
| 7184 // test_suite_name: name of the test suite | |
| 7185 // type_param: the name of the test suite's type parameter, or NULL if | |
| 7186 // this is not a typed or a type-parameterized test suite. | |
| 7187 // set_up_tc: pointer to the function that sets up the test suite | |
| 7188 // tear_down_tc: pointer to the function that tears down the test suite | |
| 7189 TestSuite* UnitTestImpl::GetTestSuite( | |
| 7190 const char* test_suite_name, const char* type_param, | |
| 7191 internal::SetUpTestSuiteFunc set_up_tc, | |
| 7192 internal::TearDownTestSuiteFunc tear_down_tc) { | |
| 7193 // Can we find a TestSuite with the given name? | |
| 7194 const auto test_suite = | |
| 7195 std::find_if(test_suites_.rbegin(), test_suites_.rend(), | |
| 7196 TestSuiteNameIs(test_suite_name)); | |
| 7197 | |
| 7198 if (test_suite != test_suites_.rend()) return *test_suite; | |
| 7199 | |
| 7200 // No. Let's create one. | |
| 7201 auto* const new_test_suite = | |
| 7202 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); | |
| 7203 | |
| 7204 // Is this a death test suite? | |
| 7205 if (internal::UnitTestOptions::MatchesFilter(test_suite_name, | |
| 7206 kDeathTestSuiteFilter)) { | |
| 7207 // Yes. Inserts the test suite after the last death test suite | |
| 7208 // defined so far. This only works when the test suites haven't | |
| 7209 // been shuffled. Otherwise we may end up running a death test | |
| 7210 // after a non-death test. | |
| 7211 ++last_death_test_suite_; | |
| 7212 test_suites_.insert(test_suites_.begin() + last_death_test_suite_, | |
| 7213 new_test_suite); | |
| 7214 } else { | |
| 7215 // No. Appends to the end of the list. | |
| 7216 test_suites_.push_back(new_test_suite); | |
| 7217 } | |
| 7218 | |
| 7219 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size())); | |
| 7220 return new_test_suite; | |
| 7221 } | |
| 7222 | |
| 7223 // Helpers for setting up / tearing down the given environment. They | |
| 7224 // are for use in the ForEach() function. | |
| 7225 static void SetUpEnvironment(Environment* env) { env->SetUp(); } | |
| 7226 static void TearDownEnvironment(Environment* env) { env->TearDown(); } | |
| 7227 | |
| 7228 // Runs all tests in this UnitTest object, prints the result, and | |
| 7229 // returns true if all tests are successful. If any exception is | |
| 7230 // thrown during a test, the test is considered to be failed, but the | |
| 7231 // rest of the tests will still be run. | |
| 7232 // | |
| 7233 // When parameterized tests are enabled, it expands and registers | |
| 7234 // parameterized tests first in RegisterParameterizedTests(). | |
| 7235 // All other functions called from RunAllTests() may safely assume that | |
| 7236 // parameterized tests are ready to be counted and run. | |
| 7237 bool UnitTestImpl::RunAllTests() { | |
| 7238 // True if and only if Google Test is initialized before RUN_ALL_TESTS() is | |
| 7239 // called. | |
| 7240 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); | |
| 7241 | |
| 7242 // Do not run any test if the --help flag was specified. | |
| 7243 if (g_help_flag) | |
| 7244 return true; | |
| 7245 | |
| 7246 // Repeats the call to the post-flag parsing initialization in case the | |
| 7247 // user didn't call InitGoogleTest. | |
| 7248 PostFlagParsingInit(); | |
| 7249 | |
| 7250 // Even if sharding is not on, test runners may want to use the | |
| 7251 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding | |
| 7252 // protocol. | |
| 7253 internal::WriteToShardStatusFileIfNeeded(); | |
| 7254 | |
| 7255 // True if and only if we are in a subprocess for running a thread-safe-style | |
| 7256 // death test. | |
| 7257 bool in_subprocess_for_death_test = false; | |
| 7258 | |
| 7259 #if GTEST_HAS_DEATH_TEST | |
| 7260 in_subprocess_for_death_test = | |
| 7261 (internal_run_death_test_flag_.get() != nullptr); | |
| 7262 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) | |
| 7263 if (in_subprocess_for_death_test) { | |
| 7264 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); | |
| 7265 } | |
| 7266 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) | |
| 7267 #endif // GTEST_HAS_DEATH_TEST | |
| 7268 | |
| 7269 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, | |
| 7270 in_subprocess_for_death_test); | |
| 7271 | |
| 7272 // Compares the full test names with the filter to decide which | |
| 7273 // tests to run. | |
| 7274 const bool has_tests_to_run = FilterTests(should_shard | |
| 7275 ? HONOR_SHARDING_PROTOCOL | |
| 7276 : IGNORE_SHARDING_PROTOCOL) > 0; | |
| 7277 | |
| 7278 // Lists the tests and exits if the --gtest_list_tests flag was specified. | |
| 7279 if (GTEST_FLAG(list_tests)) { | |
| 7280 // This must be called *after* FilterTests() has been called. | |
| 7281 ListTestsMatchingFilter(); | |
| 7282 return true; | |
| 7283 } | |
| 7284 | |
| 7285 random_seed_ = GTEST_FLAG(shuffle) ? | |
| 7286 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; | |
| 7287 | |
| 7288 // True if and only if at least one test has failed. | |
| 7289 bool failed = false; | |
| 7290 | |
| 7291 TestEventListener* repeater = listeners()->repeater(); | |
| 7292 | |
| 7293 start_timestamp_ = GetTimeInMillis(); | |
| 7294 repeater->OnTestProgramStart(*parent_); | |
| 7295 | |
| 7296 // How many times to repeat the tests? We don't want to repeat them | |
| 7297 // when we are inside the subprocess of a death test. | |
| 7298 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); | |
| 7299 // Repeats forever if the repeat count is negative. | |
| 7300 const bool gtest_repeat_forever = repeat < 0; | |
| 7301 for (int i = 0; gtest_repeat_forever || i != repeat; i++) { | |
| 7302 // We want to preserve failures generated by ad-hoc test | |
| 7303 // assertions executed before RUN_ALL_TESTS(). | |
| 7304 ClearNonAdHocTestResult(); | |
| 7305 | |
| 7306 Timer timer; | |
| 7307 | |
| 7308 // Shuffles test suites and tests if requested. | |
| 7309 if (has_tests_to_run && GTEST_FLAG(shuffle)) { | |
| 7310 random()->Reseed(static_cast<uint32_t>(random_seed_)); | |
| 7311 // This should be done before calling OnTestIterationStart(), | |
| 7312 // such that a test event listener can see the actual test order | |
| 7313 // in the event. | |
| 7314 ShuffleTests(); | |
| 7315 } | |
| 7316 | |
| 7317 // Tells the unit test event listeners that the tests are about to start. | |
| 7318 repeater->OnTestIterationStart(*parent_, i); | |
| 7319 | |
| 7320 // Runs each test suite if there is at least one test to run. | |
| 7321 if (has_tests_to_run) { | |
| 7322 // Sets up all environments beforehand. | |
| 7323 repeater->OnEnvironmentsSetUpStart(*parent_); | |
| 7324 ForEach(environments_, SetUpEnvironment); | |
| 7325 repeater->OnEnvironmentsSetUpEnd(*parent_); | |
| 7326 | |
| 7327 // Runs the tests only if there was no fatal failure or skip triggered | |
| 7328 // during global set-up. | |
| 7329 if (Test::IsSkipped()) { | |
| 7330 // Emit diagnostics when global set-up calls skip, as it will not be | |
| 7331 // emitted by default. | |
| 7332 TestResult& test_result = | |
| 7333 *internal::GetUnitTestImpl()->current_test_result(); | |
| 7334 for (int j = 0; j < test_result.total_part_count(); ++j) { | |
| 7335 const TestPartResult& test_part_result = | |
| 7336 test_result.GetTestPartResult(j); | |
| 7337 if (test_part_result.type() == TestPartResult::kSkip) { | |
| 7338 const std::string& result = test_part_result.message(); | |
| 7339 printf("%s\n", result.c_str()); | |
| 7340 } | |
| 7341 } | |
| 7342 fflush(stdout); | |
| 7343 } else if (!Test::HasFatalFailure()) { | |
| 7344 for (int test_index = 0; test_index < total_test_suite_count(); | |
| 7345 test_index++) { | |
| 7346 GetMutableSuiteCase(test_index)->Run(); | |
| 7347 if (GTEST_FLAG(fail_fast) && | |
| 7348 GetMutableSuiteCase(test_index)->Failed()) { | |
| 7349 for (int j = test_index + 1; j < total_test_suite_count(); j++) { | |
| 7350 GetMutableSuiteCase(j)->Skip(); | |
| 7351 } | |
| 7352 break; | |
| 7353 } | |
| 7354 } | |
| 7355 } else if (Test::HasFatalFailure()) { | |
| 7356 // If there was a fatal failure during the global setup then we know we | |
| 7357 // aren't going to run any tests. Explicitly mark all of the tests as | |
| 7358 // skipped to make this obvious in the output. | |
| 7359 for (int test_index = 0; test_index < total_test_suite_count(); | |
| 7360 test_index++) { | |
| 7361 GetMutableSuiteCase(test_index)->Skip(); | |
| 7362 } | |
| 7363 } | |
| 7364 | |
| 7365 // Tears down all environments in reverse order afterwards. | |
| 7366 repeater->OnEnvironmentsTearDownStart(*parent_); | |
| 7367 std::for_each(environments_.rbegin(), environments_.rend(), | |
| 7368 TearDownEnvironment); | |
| 7369 repeater->OnEnvironmentsTearDownEnd(*parent_); | |
| 7370 } | |
| 7371 | |
| 7372 elapsed_time_ = timer.Elapsed(); | |
| 7373 | |
| 7374 // Tells the unit test event listener that the tests have just finished. | |
| 7375 repeater->OnTestIterationEnd(*parent_, i); | |
| 7376 | |
| 7377 // Gets the result and clears it. | |
| 7378 if (!Passed()) { | |
| 7379 failed = true; | |
| 7380 } | |
| 7381 | |
| 7382 // Restores the original test order after the iteration. This | |
| 7383 // allows the user to quickly repro a failure that happens in the | |
| 7384 // N-th iteration without repeating the first (N - 1) iterations. | |
| 7385 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in | |
| 7386 // case the user somehow changes the value of the flag somewhere | |
| 7387 // (it's always safe to unshuffle the tests). | |
| 7388 UnshuffleTests(); | |
| 7389 | |
| 7390 if (GTEST_FLAG(shuffle)) { | |
| 7391 // Picks a new random seed for each iteration. | |
| 7392 random_seed_ = GetNextRandomSeed(random_seed_); | |
| 7393 } | |
| 7394 } | |
| 7395 | |
| 7396 repeater->OnTestProgramEnd(*parent_); | |
| 7397 | |
| 7398 if (!gtest_is_initialized_before_run_all_tests) { | |
| 7399 ColoredPrintf( | |
| 7400 GTestColor::kRed, | |
| 7401 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n" | |
| 7402 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_ | |
| 7403 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ | |
| 7404 " will start to enforce the valid usage. " | |
| 7405 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT | |
| 7406 #if GTEST_FOR_GOOGLE_ | |
| 7407 ColoredPrintf(GTestColor::kRed, | |
| 7408 "For more details, see http://wiki/Main/ValidGUnitMain.\n"); | |
| 7409 #endif // GTEST_FOR_GOOGLE_ | |
| 7410 } | |
| 7411 | |
| 7412 return !failed; | |
| 7413 } | |
| 7414 | |
| 7415 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file | |
| 7416 // if the variable is present. If a file already exists at this location, this | |
| 7417 // function will write over it. If the variable is present, but the file cannot | |
| 7418 // be created, prints an error and exits. | |
| 7419 void WriteToShardStatusFileIfNeeded() { | |
| 7420 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); | |
| 7421 if (test_shard_file != nullptr) { | |
| 7422 FILE* const file = posix::FOpen(test_shard_file, "w"); | |
| 7423 if (file == nullptr) { | |
| 7424 ColoredPrintf(GTestColor::kRed, | |
| 7425 "Could not write to the test shard status file \"%s\" " | |
| 7426 "specified by the %s environment variable.\n", | |
| 7427 test_shard_file, kTestShardStatusFile); | |
| 7428 fflush(stdout); | |
| 7429 exit(EXIT_FAILURE); | |
| 7430 } | |
| 7431 fclose(file); | |
| 7432 } | |
| 7433 } | |
| 7434 | |
| 7435 // Checks whether sharding is enabled by examining the relevant | |
| 7436 // environment variable values. If the variables are present, | |
| 7437 // but inconsistent (i.e., shard_index >= total_shards), prints | |
| 7438 // an error and exits. If in_subprocess_for_death_test, sharding is | |
| 7439 // disabled because it must only be applied to the original test | |
| 7440 // process. Otherwise, we could filter out death tests we intended to execute. | |
| 7441 bool ShouldShard(const char* total_shards_env, | |
| 7442 const char* shard_index_env, | |
| 7443 bool in_subprocess_for_death_test) { | |
| 7444 if (in_subprocess_for_death_test) { | |
| 7445 return false; | |
| 7446 } | |
| 7447 | |
| 7448 const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1); | |
| 7449 const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1); | |
| 7450 | |
| 7451 if (total_shards == -1 && shard_index == -1) { | |
| 7452 return false; | |
| 7453 } else if (total_shards == -1 && shard_index != -1) { | |
| 7454 const Message msg = Message() | |
| 7455 << "Invalid environment variables: you have " | |
| 7456 << kTestShardIndex << " = " << shard_index | |
| 7457 << ", but have left " << kTestTotalShards << " unset.\n"; | |
| 7458 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); | |
| 7459 fflush(stdout); | |
| 7460 exit(EXIT_FAILURE); | |
| 7461 } else if (total_shards != -1 && shard_index == -1) { | |
| 7462 const Message msg = Message() | |
| 7463 << "Invalid environment variables: you have " | |
| 7464 << kTestTotalShards << " = " << total_shards | |
| 7465 << ", but have left " << kTestShardIndex << " unset.\n"; | |
| 7466 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); | |
| 7467 fflush(stdout); | |
| 7468 exit(EXIT_FAILURE); | |
| 7469 } else if (shard_index < 0 || shard_index >= total_shards) { | |
| 7470 const Message msg = Message() | |
| 7471 << "Invalid environment variables: we require 0 <= " | |
| 7472 << kTestShardIndex << " < " << kTestTotalShards | |
| 7473 << ", but you have " << kTestShardIndex << "=" << shard_index | |
| 7474 << ", " << kTestTotalShards << "=" << total_shards << ".\n"; | |
| 7475 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); | |
| 7476 fflush(stdout); | |
| 7477 exit(EXIT_FAILURE); | |
| 7478 } | |
| 7479 | |
| 7480 return total_shards > 1; | |
| 7481 } | |
| 7482 | |
| 7483 // Parses the environment variable var as an Int32. If it is unset, | |
| 7484 // returns default_val. If it is not an Int32, prints an error | |
| 7485 // and aborts. | |
| 7486 int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) { | |
| 7487 const char* str_val = posix::GetEnv(var); | |
| 7488 if (str_val == nullptr) { | |
| 7489 return default_val; | |
| 7490 } | |
| 7491 | |
| 7492 int32_t result; | |
| 7493 if (!ParseInt32(Message() << "The value of environment variable " << var, | |
| 7494 str_val, &result)) { | |
| 7495 exit(EXIT_FAILURE); | |
| 7496 } | |
| 7497 return result; | |
| 7498 } | |
| 7499 | |
| 7500 // Given the total number of shards, the shard index, and the test id, | |
| 7501 // returns true if and only if the test should be run on this shard. The test id | |
| 7502 // is some arbitrary but unique non-negative integer assigned to each test | |
| 7503 // method. Assumes that 0 <= shard_index < total_shards. | |
| 7504 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { | |
| 7505 return (test_id % total_shards) == shard_index; | |
| 7506 } | |
| 7507 | |
| 7508 // Compares the name of each test with the user-specified filter to | |
| 7509 // decide whether the test should be run, then records the result in | |
| 7510 // each TestSuite and TestInfo object. | |
| 7511 // If shard_tests == true, further filters tests based on sharding | |
| 7512 // variables in the environment - see | |
| 7513 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md | |
| 7514 // . Returns the number of tests that should run. | |
| 7515 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { | |
| 7516 const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? | |
| 7517 Int32FromEnvOrDie(kTestTotalShards, -1) : -1; | |
| 7518 const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? | |
| 7519 Int32FromEnvOrDie(kTestShardIndex, -1) : -1; | |
| 7520 | |
| 7521 // num_runnable_tests are the number of tests that will | |
| 7522 // run across all shards (i.e., match filter and are not disabled). | |
| 7523 // num_selected_tests are the number of tests to be run on | |
| 7524 // this shard. | |
| 7525 int num_runnable_tests = 0; | |
| 7526 int num_selected_tests = 0; | |
| 7527 for (auto* test_suite : test_suites_) { | |
| 7528 const std::string& test_suite_name = test_suite->name(); | |
| 7529 test_suite->set_should_run(false); | |
| 7530 | |
| 7531 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { | |
| 7532 TestInfo* const test_info = test_suite->test_info_list()[j]; | |
| 7533 const std::string test_name(test_info->name()); | |
| 7534 // A test is disabled if test suite name or test name matches | |
| 7535 // kDisableTestFilter. | |
| 7536 const bool is_disabled = internal::UnitTestOptions::MatchesFilter( | |
| 7537 test_suite_name, kDisableTestFilter) || | |
| 7538 internal::UnitTestOptions::MatchesFilter( | |
| 7539 test_name, kDisableTestFilter); | |
| 7540 test_info->is_disabled_ = is_disabled; | |
| 7541 | |
| 7542 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest( | |
| 7543 test_suite_name, test_name); | |
| 7544 test_info->matches_filter_ = matches_filter; | |
| 7545 | |
| 7546 const bool is_runnable = | |
| 7547 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && | |
| 7548 matches_filter; | |
| 7549 | |
| 7550 const bool is_in_another_shard = | |
| 7551 shard_tests != IGNORE_SHARDING_PROTOCOL && | |
| 7552 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests); | |
| 7553 test_info->is_in_another_shard_ = is_in_another_shard; | |
| 7554 const bool is_selected = is_runnable && !is_in_another_shard; | |
| 7555 | |
| 7556 num_runnable_tests += is_runnable; | |
| 7557 num_selected_tests += is_selected; | |
| 7558 | |
| 7559 test_info->should_run_ = is_selected; | |
| 7560 test_suite->set_should_run(test_suite->should_run() || is_selected); | |
| 7561 } | |
| 7562 } | |
| 7563 return num_selected_tests; | |
| 7564 } | |
| 7565 | |
| 7566 // Prints the given C-string on a single line by replacing all '\n' | |
| 7567 // characters with string "\\n". If the output takes more than | |
| 7568 // max_length characters, only prints the first max_length characters | |
| 7569 // and "...". | |
| 7570 static void PrintOnOneLine(const char* str, int max_length) { | |
| 7571 if (str != nullptr) { | |
| 7572 for (int i = 0; *str != '\0'; ++str) { | |
| 7573 if (i >= max_length) { | |
| 7574 printf("..."); | |
| 7575 break; | |
| 7576 } | |
| 7577 if (*str == '\n') { | |
| 7578 printf("\\n"); | |
| 7579 i += 2; | |
| 7580 } else { | |
| 7581 printf("%c", *str); | |
| 7582 ++i; | |
| 7583 } | |
| 7584 } | |
| 7585 } | |
| 7586 } | |
| 7587 | |
| 7588 // Prints the names of the tests matching the user-specified filter flag. | |
| 7589 void UnitTestImpl::ListTestsMatchingFilter() { | |
| 7590 // Print at most this many characters for each type/value parameter. | |
| 7591 const int kMaxParamLength = 250; | |
| 7592 | |
| 7593 for (auto* test_suite : test_suites_) { | |
| 7594 bool printed_test_suite_name = false; | |
| 7595 | |
| 7596 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { | |
| 7597 const TestInfo* const test_info = test_suite->test_info_list()[j]; | |
| 7598 if (test_info->matches_filter_) { | |
| 7599 if (!printed_test_suite_name) { | |
| 7600 printed_test_suite_name = true; | |
| 7601 printf("%s.", test_suite->name()); | |
| 7602 if (test_suite->type_param() != nullptr) { | |
| 7603 printf(" # %s = ", kTypeParamLabel); | |
| 7604 // We print the type parameter on a single line to make | |
| 7605 // the output easy to parse by a program. | |
| 7606 PrintOnOneLine(test_suite->type_param(), kMaxParamLength); | |
| 7607 } | |
| 7608 printf("\n"); | |
| 7609 } | |
| 7610 printf(" %s", test_info->name()); | |
| 7611 if (test_info->value_param() != nullptr) { | |
| 7612 printf(" # %s = ", kValueParamLabel); | |
| 7613 // We print the value parameter on a single line to make the | |
| 7614 // output easy to parse by a program. | |
| 7615 PrintOnOneLine(test_info->value_param(), kMaxParamLength); | |
| 7616 } | |
| 7617 printf("\n"); | |
| 7618 } | |
| 7619 } | |
| 7620 } | |
| 7621 fflush(stdout); | |
| 7622 const std::string& output_format = UnitTestOptions::GetOutputFormat(); | |
| 7623 if (output_format == "xml" || output_format == "json") { | |
| 7624 FILE* fileout = OpenFileForWriting( | |
| 7625 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); | |
| 7626 std::stringstream stream; | |
| 7627 if (output_format == "xml") { | |
| 7628 XmlUnitTestResultPrinter( | |
| 7629 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) | |
| 7630 .PrintXmlTestsList(&stream, test_suites_); | |
| 7631 } else if (output_format == "json") { | |
| 7632 JsonUnitTestResultPrinter( | |
| 7633 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) | |
| 7634 .PrintJsonTestList(&stream, test_suites_); | |
| 7635 } | |
| 7636 fprintf(fileout, "%s", StringStreamToString(&stream).c_str()); | |
| 7637 fclose(fileout); | |
| 7638 } | |
| 7639 } | |
| 7640 | |
| 7641 // Sets the OS stack trace getter. | |
| 7642 // | |
| 7643 // Does nothing if the input and the current OS stack trace getter are | |
| 7644 // the same; otherwise, deletes the old getter and makes the input the | |
| 7645 // current getter. | |
| 7646 void UnitTestImpl::set_os_stack_trace_getter( | |
| 7647 OsStackTraceGetterInterface* getter) { | |
| 7648 if (os_stack_trace_getter_ != getter) { | |
| 7649 delete os_stack_trace_getter_; | |
| 7650 os_stack_trace_getter_ = getter; | |
| 7651 } | |
| 7652 } | |
| 7653 | |
| 7654 // Returns the current OS stack trace getter if it is not NULL; | |
| 7655 // otherwise, creates an OsStackTraceGetter, makes it the current | |
| 7656 // getter, and returns it. | |
| 7657 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { | |
| 7658 if (os_stack_trace_getter_ == nullptr) { | |
| 7659 #ifdef GTEST_OS_STACK_TRACE_GETTER_ | |
| 7660 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; | |
| 7661 #else | |
| 7662 os_stack_trace_getter_ = new OsStackTraceGetter; | |
| 7663 #endif // GTEST_OS_STACK_TRACE_GETTER_ | |
| 7664 } | |
| 7665 | |
| 7666 return os_stack_trace_getter_; | |
| 7667 } | |
| 7668 | |
| 7669 // Returns the most specific TestResult currently running. | |
| 7670 TestResult* UnitTestImpl::current_test_result() { | |
| 7671 if (current_test_info_ != nullptr) { | |
| 7672 return ¤t_test_info_->result_; | |
| 7673 } | |
| 7674 if (current_test_suite_ != nullptr) { | |
| 7675 return ¤t_test_suite_->ad_hoc_test_result_; | |
| 7676 } | |
| 7677 return &ad_hoc_test_result_; | |
| 7678 } | |
| 7679 | |
| 7680 // Shuffles all test suites, and the tests within each test suite, | |
| 7681 // making sure that death tests are still run first. | |
| 7682 void UnitTestImpl::ShuffleTests() { | |
| 7683 // Shuffles the death test suites. | |
| 7684 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_); | |
| 7685 | |
| 7686 // Shuffles the non-death test suites. | |
| 7687 ShuffleRange(random(), last_death_test_suite_ + 1, | |
| 7688 static_cast<int>(test_suites_.size()), &test_suite_indices_); | |
| 7689 | |
| 7690 // Shuffles the tests inside each test suite. | |
| 7691 for (auto& test_suite : test_suites_) { | |
| 7692 test_suite->ShuffleTests(random()); | |
| 7693 } | |
| 7694 } | |
| 7695 | |
| 7696 // Restores the test suites and tests to their order before the first shuffle. | |
| 7697 void UnitTestImpl::UnshuffleTests() { | |
| 7698 for (size_t i = 0; i < test_suites_.size(); i++) { | |
| 7699 // Unshuffles the tests in each test suite. | |
| 7700 test_suites_[i]->UnshuffleTests(); | |
| 7701 // Resets the index of each test suite. | |
| 7702 test_suite_indices_[i] = static_cast<int>(i); | |
| 7703 } | |
| 7704 } | |
| 7705 | |
| 7706 // Returns the current OS stack trace as an std::string. | |
| 7707 // | |
| 7708 // The maximum number of stack frames to be included is specified by | |
| 7709 // the gtest_stack_trace_depth flag. The skip_count parameter | |
| 7710 // specifies the number of top frames to be skipped, which doesn't | |
| 7711 // count against the number of frames to be included. | |
| 7712 // | |
| 7713 // For example, if Foo() calls Bar(), which in turn calls | |
| 7714 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in | |
| 7715 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. | |
| 7716 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, | |
| 7717 int skip_count) { | |
| 7718 // We pass skip_count + 1 to skip this wrapper function in addition | |
| 7719 // to what the user really wants to skip. | |
| 7720 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); | |
| 7721 } | |
| 7722 | |
| 7723 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to | |
| 7724 // suppress unreachable code warnings. | |
| 7725 namespace { | |
| 7726 class ClassUniqueToAlwaysTrue {}; | |
| 7727 } | |
| 7728 | |
| 7729 bool IsTrue(bool condition) { return condition; } | |
| 7730 | |
| 7731 bool AlwaysTrue() { | |
| 7732 #if GTEST_HAS_EXCEPTIONS | |
| 7733 // This condition is always false so AlwaysTrue() never actually throws, | |
| 7734 // but it makes the compiler think that it may throw. | |
| 7735 if (IsTrue(false)) | |
| 7736 throw ClassUniqueToAlwaysTrue(); | |
| 7737 #endif // GTEST_HAS_EXCEPTIONS | |
| 7738 return true; | |
| 7739 } | |
| 7740 | |
| 7741 // If *pstr starts with the given prefix, modifies *pstr to be right | |
| 7742 // past the prefix and returns true; otherwise leaves *pstr unchanged | |
| 7743 // and returns false. None of pstr, *pstr, and prefix can be NULL. | |
| 7744 bool SkipPrefix(const char* prefix, const char** pstr) { | |
| 7745 const size_t prefix_len = strlen(prefix); | |
| 7746 if (strncmp(*pstr, prefix, prefix_len) == 0) { | |
| 7747 *pstr += prefix_len; | |
| 7748 return true; | |
| 7749 } | |
| 7750 return false; | |
| 7751 } | |
| 7752 | |
| 7753 // Parses a string as a command line flag. The string should have | |
| 7754 // the format "--flag=value". When def_optional is true, the "=value" | |
| 7755 // part can be omitted. | |
| 7756 // | |
| 7757 // Returns the value of the flag, or NULL if the parsing failed. | |
| 7758 static const char* ParseFlagValue(const char* str, const char* flag, | |
| 7759 bool def_optional) { | |
| 7760 // str and flag must not be NULL. | |
| 7761 if (str == nullptr || flag == nullptr) return nullptr; | |
| 7762 | |
| 7763 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. | |
| 7764 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; | |
| 7765 const size_t flag_len = flag_str.length(); | |
| 7766 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; | |
| 7767 | |
| 7768 // Skips the flag name. | |
| 7769 const char* flag_end = str + flag_len; | |
| 7770 | |
| 7771 // When def_optional is true, it's OK to not have a "=value" part. | |
| 7772 if (def_optional && (flag_end[0] == '\0')) { | |
| 7773 return flag_end; | |
| 7774 } | |
| 7775 | |
| 7776 // If def_optional is true and there are more characters after the | |
| 7777 // flag name, or if def_optional is false, there must be a '=' after | |
| 7778 // the flag name. | |
| 7779 if (flag_end[0] != '=') return nullptr; | |
| 7780 | |
| 7781 // Returns the string after "=". | |
| 7782 return flag_end + 1; | |
| 7783 } | |
| 7784 | |
| 7785 // Parses a string for a bool flag, in the form of either | |
| 7786 // "--flag=value" or "--flag". | |
| 7787 // | |
| 7788 // In the former case, the value is taken as true as long as it does | |
| 7789 // not start with '0', 'f', or 'F'. | |
| 7790 // | |
| 7791 // In the latter case, the value is taken as true. | |
| 7792 // | |
| 7793 // On success, stores the value of the flag in *value, and returns | |
| 7794 // true. On failure, returns false without changing *value. | |
| 7795 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { | |
| 7796 // Gets the value of the flag as a string. | |
| 7797 const char* const value_str = ParseFlagValue(str, flag, true); | |
| 7798 | |
| 7799 // Aborts if the parsing failed. | |
| 7800 if (value_str == nullptr) return false; | |
| 7801 | |
| 7802 // Converts the string value to a bool. | |
| 7803 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); | |
| 7804 return true; | |
| 7805 } | |
| 7806 | |
| 7807 // Parses a string for an int32_t flag, in the form of "--flag=value". | |
| 7808 // | |
| 7809 // On success, stores the value of the flag in *value, and returns | |
| 7810 // true. On failure, returns false without changing *value. | |
| 7811 bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { | |
| 7812 // Gets the value of the flag as a string. | |
| 7813 const char* const value_str = ParseFlagValue(str, flag, false); | |
| 7814 | |
| 7815 // Aborts if the parsing failed. | |
| 7816 if (value_str == nullptr) return false; | |
| 7817 | |
| 7818 // Sets *value to the value of the flag. | |
| 7819 return ParseInt32(Message() << "The value of flag --" << flag, | |
| 7820 value_str, value); | |
| 7821 } | |
| 7822 | |
| 7823 // Parses a string for a string flag, in the form of "--flag=value". | |
| 7824 // | |
| 7825 // On success, stores the value of the flag in *value, and returns | |
| 7826 // true. On failure, returns false without changing *value. | |
| 7827 template <typename String> | |
| 7828 static bool ParseStringFlag(const char* str, const char* flag, String* value) { | |
| 7829 // Gets the value of the flag as a string. | |
| 7830 const char* const value_str = ParseFlagValue(str, flag, false); | |
| 7831 | |
| 7832 // Aborts if the parsing failed. | |
| 7833 if (value_str == nullptr) return false; | |
| 7834 | |
| 7835 // Sets *value to the value of the flag. | |
| 7836 *value = value_str; | |
| 7837 return true; | |
| 7838 } | |
| 7839 | |
| 7840 // Determines whether a string has a prefix that Google Test uses for its | |
| 7841 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. | |
| 7842 // If Google Test detects that a command line flag has its prefix but is not | |
| 7843 // recognized, it will print its help message. Flags starting with | |
| 7844 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test | |
| 7845 // internal flags and do not trigger the help message. | |
| 7846 static bool HasGoogleTestFlagPrefix(const char* str) { | |
| 7847 return (SkipPrefix("--", &str) || | |
| 7848 SkipPrefix("-", &str) || | |
| 7849 SkipPrefix("/", &str)) && | |
| 7850 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && | |
| 7851 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || | |
| 7852 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); | |
| 7853 } | |
| 7854 | |
| 7855 // Prints a string containing code-encoded text. The following escape | |
| 7856 // sequences can be used in the string to control the text color: | |
| 7857 // | |
| 7858 // @@ prints a single '@' character. | |
| 7859 // @R changes the color to red. | |
| 7860 // @G changes the color to green. | |
| 7861 // @Y changes the color to yellow. | |
| 7862 // @D changes to the default terminal text color. | |
| 7863 // | |
| 7864 static void PrintColorEncoded(const char* str) { | |
| 7865 GTestColor color = GTestColor::kDefault; // The current color. | |
| 7866 | |
| 7867 // Conceptually, we split the string into segments divided by escape | |
| 7868 // sequences. Then we print one segment at a time. At the end of | |
| 7869 // each iteration, the str pointer advances to the beginning of the | |
| 7870 // next segment. | |
| 7871 for (;;) { | |
| 7872 const char* p = strchr(str, '@'); | |
| 7873 if (p == nullptr) { | |
| 7874 ColoredPrintf(color, "%s", str); | |
| 7875 return; | |
| 7876 } | |
| 7877 | |
| 7878 ColoredPrintf(color, "%s", std::string(str, p).c_str()); | |
| 7879 | |
| 7880 const char ch = p[1]; | |
| 7881 str = p + 2; | |
| 7882 if (ch == '@') { | |
| 7883 ColoredPrintf(color, "@"); | |
| 7884 } else if (ch == 'D') { | |
| 7885 color = GTestColor::kDefault; | |
| 7886 } else if (ch == 'R') { | |
| 7887 color = GTestColor::kRed; | |
| 7888 } else if (ch == 'G') { | |
| 7889 color = GTestColor::kGreen; | |
| 7890 } else if (ch == 'Y') { | |
| 7891 color = GTestColor::kYellow; | |
| 7892 } else { | |
| 7893 --str; | |
| 7894 } | |
| 7895 } | |
| 7896 } | |
| 7897 | |
| 7898 static const char kColorEncodedHelpMessage[] = | |
| 7899 "This program contains tests written using " GTEST_NAME_ | |
| 7900 ". You can use the\n" | |
| 7901 "following command line flags to control its behavior:\n" | |
| 7902 "\n" | |
| 7903 "Test Selection:\n" | |
| 7904 " @G--" GTEST_FLAG_PREFIX_ | |
| 7905 "list_tests@D\n" | |
| 7906 " List the names of all tests instead of running them. The name of\n" | |
| 7907 " TEST(Foo, Bar) is \"Foo.Bar\".\n" | |
| 7908 " @G--" GTEST_FLAG_PREFIX_ | |
| 7909 "filter=@YPOSITIVE_PATTERNS" | |
| 7910 "[@G-@YNEGATIVE_PATTERNS]@D\n" | |
| 7911 " Run only the tests whose name matches one of the positive patterns " | |
| 7912 "but\n" | |
| 7913 " none of the negative patterns. '?' matches any single character; " | |
| 7914 "'*'\n" | |
| 7915 " matches any substring; ':' separates two patterns.\n" | |
| 7916 " @G--" GTEST_FLAG_PREFIX_ | |
| 7917 "also_run_disabled_tests@D\n" | |
| 7918 " Run all disabled tests too.\n" | |
| 7919 "\n" | |
| 7920 "Test Execution:\n" | |
| 7921 " @G--" GTEST_FLAG_PREFIX_ | |
| 7922 "repeat=@Y[COUNT]@D\n" | |
| 7923 " Run the tests repeatedly; use a negative count to repeat forever.\n" | |
| 7924 " @G--" GTEST_FLAG_PREFIX_ | |
| 7925 "shuffle@D\n" | |
| 7926 " Randomize tests' orders on every iteration.\n" | |
| 7927 " @G--" GTEST_FLAG_PREFIX_ | |
| 7928 "random_seed=@Y[NUMBER]@D\n" | |
| 7929 " Random number seed to use for shuffling test orders (between 1 and\n" | |
| 7930 " 99999, or 0 to use a seed based on the current time).\n" | |
| 7931 "\n" | |
| 7932 "Test Output:\n" | |
| 7933 " @G--" GTEST_FLAG_PREFIX_ | |
| 7934 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" | |
| 7935 " Enable/disable colored output. The default is @Gauto@D.\n" | |
| 7936 " @G--" GTEST_FLAG_PREFIX_ | |
| 7937 "brief=1@D\n" | |
| 7938 " Only print test failures.\n" | |
| 7939 " @G--" GTEST_FLAG_PREFIX_ | |
| 7940 "print_time=0@D\n" | |
| 7941 " Don't print the elapsed time of each test.\n" | |
| 7942 " @G--" GTEST_FLAG_PREFIX_ | |
| 7943 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ | |
| 7944 "@Y|@G:@YFILE_PATH]@D\n" | |
| 7945 " Generate a JSON or XML report in the given directory or with the " | |
| 7946 "given\n" | |
| 7947 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" | |
| 7948 # if GTEST_CAN_STREAM_RESULTS_ | |
| 7949 " @G--" GTEST_FLAG_PREFIX_ | |
| 7950 "stream_result_to=@YHOST@G:@YPORT@D\n" | |
| 7951 " Stream test results to the given server.\n" | |
| 7952 # endif // GTEST_CAN_STREAM_RESULTS_ | |
| 7953 "\n" | |
| 7954 "Assertion Behavior:\n" | |
| 7955 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS | |
| 7956 " @G--" GTEST_FLAG_PREFIX_ | |
| 7957 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" | |
| 7958 " Set the default death test style.\n" | |
| 7959 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS | |
| 7960 " @G--" GTEST_FLAG_PREFIX_ | |
| 7961 "break_on_failure@D\n" | |
| 7962 " Turn assertion failures into debugger break-points.\n" | |
| 7963 " @G--" GTEST_FLAG_PREFIX_ | |
| 7964 "throw_on_failure@D\n" | |
| 7965 " Turn assertion failures into C++ exceptions for use by an external\n" | |
| 7966 " test framework.\n" | |
| 7967 " @G--" GTEST_FLAG_PREFIX_ | |
| 7968 "catch_exceptions=0@D\n" | |
| 7969 " Do not report exceptions as test failures. Instead, allow them\n" | |
| 7970 " to crash the program or throw a pop-up (on Windows).\n" | |
| 7971 "\n" | |
| 7972 "Except for @G--" GTEST_FLAG_PREFIX_ | |
| 7973 "list_tests@D, you can alternatively set " | |
| 7974 "the corresponding\n" | |
| 7975 "environment variable of a flag (all letters in upper-case). For example, " | |
| 7976 "to\n" | |
| 7977 "disable colored text output, you can either specify " | |
| 7978 "@G--" GTEST_FLAG_PREFIX_ | |
| 7979 "color=no@D or set\n" | |
| 7980 "the @G" GTEST_FLAG_PREFIX_UPPER_ | |
| 7981 "COLOR@D environment variable to @Gno@D.\n" | |
| 7982 "\n" | |
| 7983 "For more information, please read the " GTEST_NAME_ | |
| 7984 " documentation at\n" | |
| 7985 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ | |
| 7986 "\n" | |
| 7987 "(not one in your own code or tests), please report it to\n" | |
| 7988 "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; | |
| 7989 | |
| 7990 static bool ParseGoogleTestFlag(const char* const arg) { | |
| 7991 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, | |
| 7992 >EST_FLAG(also_run_disabled_tests)) || | |
| 7993 ParseBoolFlag(arg, kBreakOnFailureFlag, | |
| 7994 >EST_FLAG(break_on_failure)) || | |
| 7995 ParseBoolFlag(arg, kCatchExceptionsFlag, | |
| 7996 >EST_FLAG(catch_exceptions)) || | |
| 7997 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || | |
| 7998 ParseStringFlag(arg, kDeathTestStyleFlag, | |
| 7999 >EST_FLAG(death_test_style)) || | |
| 8000 ParseBoolFlag(arg, kDeathTestUseFork, | |
| 8001 >EST_FLAG(death_test_use_fork)) || | |
| 8002 ParseBoolFlag(arg, kFailFast, >EST_FLAG(fail_fast)) || | |
| 8003 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || | |
| 8004 ParseStringFlag(arg, kInternalRunDeathTestFlag, | |
| 8005 >EST_FLAG(internal_run_death_test)) || | |
| 8006 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || | |
| 8007 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || | |
| 8008 ParseBoolFlag(arg, kBriefFlag, >EST_FLAG(brief)) || | |
| 8009 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || | |
| 8010 ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) || | |
| 8011 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || | |
| 8012 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || | |
| 8013 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || | |
| 8014 ParseInt32Flag(arg, kStackTraceDepthFlag, | |
| 8015 >EST_FLAG(stack_trace_depth)) || | |
| 8016 ParseStringFlag(arg, kStreamResultToFlag, | |
| 8017 >EST_FLAG(stream_result_to)) || | |
| 8018 ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)); | |
| 8019 } | |
| 8020 | |
| 8021 #if GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 8022 static void LoadFlagsFromFile(const std::string& path) { | |
| 8023 FILE* flagfile = posix::FOpen(path.c_str(), "r"); | |
| 8024 if (!flagfile) { | |
| 8025 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile) | |
| 8026 << "\""; | |
| 8027 } | |
| 8028 std::string contents(ReadEntireFile(flagfile)); | |
| 8029 posix::FClose(flagfile); | |
| 8030 std::vector<std::string> lines; | |
| 8031 SplitString(contents, '\n', &lines); | |
| 8032 for (size_t i = 0; i < lines.size(); ++i) { | |
| 8033 if (lines[i].empty()) | |
| 8034 continue; | |
| 8035 if (!ParseGoogleTestFlag(lines[i].c_str())) | |
| 8036 g_help_flag = true; | |
| 8037 } | |
| 8038 } | |
| 8039 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 8040 | |
| 8041 // Parses the command line for Google Test flags, without initializing | |
| 8042 // other parts of Google Test. The type parameter CharType can be | |
| 8043 // instantiated to either char or wchar_t. | |
| 8044 template <typename CharType> | |
| 8045 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { | |
| 8046 for (int i = 1; i < *argc; i++) { | |
| 8047 const std::string arg_string = StreamableToString(argv[i]); | |
| 8048 const char* const arg = arg_string.c_str(); | |
| 8049 | |
| 8050 using internal::ParseBoolFlag; | |
| 8051 using internal::ParseInt32Flag; | |
| 8052 using internal::ParseStringFlag; | |
| 8053 | |
| 8054 bool remove_flag = false; | |
| 8055 if (ParseGoogleTestFlag(arg)) { | |
| 8056 remove_flag = true; | |
| 8057 #if GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 8058 } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { | |
| 8059 LoadFlagsFromFile(GTEST_FLAG(flagfile)); | |
| 8060 remove_flag = true; | |
| 8061 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ | |
| 8062 } else if (arg_string == "--help" || arg_string == "-h" || | |
| 8063 arg_string == "-?" || arg_string == "/?" || | |
| 8064 HasGoogleTestFlagPrefix(arg)) { | |
| 8065 // Both help flag and unrecognized Google Test flags (excluding | |
| 8066 // internal ones) trigger help display. | |
| 8067 g_help_flag = true; | |
| 8068 } | |
| 8069 | |
| 8070 if (remove_flag) { | |
| 8071 // Shift the remainder of the argv list left by one. Note | |
| 8072 // that argv has (*argc + 1) elements, the last one always being | |
| 8073 // NULL. The following loop moves the trailing NULL element as | |
| 8074 // well. | |
| 8075 for (int j = i; j != *argc; j++) { | |
| 8076 argv[j] = argv[j + 1]; | |
| 8077 } | |
| 8078 | |
| 8079 // Decrements the argument count. | |
| 8080 (*argc)--; | |
| 8081 | |
| 8082 // We also need to decrement the iterator as we just removed | |
| 8083 // an element. | |
| 8084 i--; | |
| 8085 } | |
| 8086 } | |
| 8087 | |
| 8088 if (g_help_flag) { | |
| 8089 // We print the help here instead of in RUN_ALL_TESTS(), as the | |
| 8090 // latter may not be called at all if the user is using Google | |
| 8091 // Test with another testing framework. | |
| 8092 PrintColorEncoded(kColorEncodedHelpMessage); | |
| 8093 } | |
| 8094 } | |
| 8095 | |
| 8096 // Parses the command line for Google Test flags, without initializing | |
| 8097 // other parts of Google Test. | |
| 8098 void ParseGoogleTestFlagsOnly(int* argc, char** argv) { | |
| 8099 ParseGoogleTestFlagsOnlyImpl(argc, argv); | |
| 8100 | |
| 8101 // Fix the value of *_NSGetArgc() on macOS, but if and only if | |
| 8102 // *_NSGetArgv() == argv | |
| 8103 // Only applicable to char** version of argv | |
| 8104 #if GTEST_OS_MAC | |
| 8105 #ifndef GTEST_OS_IOS | |
| 8106 if (*_NSGetArgv() == argv) { | |
| 8107 *_NSGetArgc() = *argc; | |
| 8108 } | |
| 8109 #endif | |
| 8110 #endif | |
| 8111 } | |
| 8112 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { | |
| 8113 ParseGoogleTestFlagsOnlyImpl(argc, argv); | |
| 8114 } | |
| 8115 | |
| 8116 // The internal implementation of InitGoogleTest(). | |
| 8117 // | |
| 8118 // The type parameter CharType can be instantiated to either char or | |
| 8119 // wchar_t. | |
| 8120 template <typename CharType> | |
| 8121 void InitGoogleTestImpl(int* argc, CharType** argv) { | |
| 8122 // We don't want to run the initialization code twice. | |
| 8123 if (GTestIsInitialized()) return; | |
| 8124 | |
| 8125 if (*argc <= 0) return; | |
| 8126 | |
| 8127 g_argvs.clear(); | |
| 8128 for (int i = 0; i != *argc; i++) { | |
| 8129 g_argvs.push_back(StreamableToString(argv[i])); | |
| 8130 } | |
| 8131 | |
| 8132 #if GTEST_HAS_ABSL | |
| 8133 absl::InitializeSymbolizer(g_argvs[0].c_str()); | |
| 8134 #endif // GTEST_HAS_ABSL | |
| 8135 | |
| 8136 ParseGoogleTestFlagsOnly(argc, argv); | |
| 8137 GetUnitTestImpl()->PostFlagParsingInit(); | |
| 8138 } | |
| 8139 | |
| 8140 } // namespace internal | |
| 8141 | |
| 8142 // Initializes Google Test. This must be called before calling | |
| 8143 // RUN_ALL_TESTS(). In particular, it parses a command line for the | |
| 8144 // flags that Google Test recognizes. Whenever a Google Test flag is | |
| 8145 // seen, it is removed from argv, and *argc is decremented. | |
| 8146 // | |
| 8147 // No value is returned. Instead, the Google Test flag variables are | |
| 8148 // updated. | |
| 8149 // | |
| 8150 // Calling the function for the second time has no user-visible effect. | |
| 8151 void InitGoogleTest(int* argc, char** argv) { | |
| 8152 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8153 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); | |
| 8154 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8155 internal::InitGoogleTestImpl(argc, argv); | |
| 8156 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8157 } | |
| 8158 | |
| 8159 // This overloaded version can be used in Windows programs compiled in | |
| 8160 // UNICODE mode. | |
| 8161 void InitGoogleTest(int* argc, wchar_t** argv) { | |
| 8162 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8163 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); | |
| 8164 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8165 internal::InitGoogleTestImpl(argc, argv); | |
| 8166 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8167 } | |
| 8168 | |
| 8169 // This overloaded version can be used on Arduino/embedded platforms where | |
| 8170 // there is no argc/argv. | |
| 8171 void InitGoogleTest() { | |
| 8172 // Since Arduino doesn't have a command line, fake out the argc/argv arguments | |
| 8173 int argc = 1; | |
| 8174 const auto arg0 = "dummy"; | |
| 8175 char* argv0 = const_cast<char*>(arg0); | |
| 8176 char** argv = &argv0; | |
| 8177 | |
| 8178 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8179 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); | |
| 8180 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8181 internal::InitGoogleTestImpl(&argc, argv); | |
| 8182 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) | |
| 8183 } | |
| 8184 | |
| 8185 std::string TempDir() { | |
| 8186 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) | |
| 8187 return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); | |
| 8188 #elif GTEST_OS_WINDOWS_MOBILE | |
| 8189 return "\\temp\\"; | |
| 8190 #elif GTEST_OS_WINDOWS | |
| 8191 const char* temp_dir = internal::posix::GetEnv("TEMP"); | |
| 8192 if (temp_dir == nullptr || temp_dir[0] == '\0') { | |
| 8193 return "\\temp\\"; | |
| 8194 } else if (temp_dir[strlen(temp_dir) - 1] == '\\') { | |
| 8195 return temp_dir; | |
| 8196 } else { | |
| 8197 return std::string(temp_dir) + "\\"; | |
| 8198 } | |
| 8199 #elif GTEST_OS_LINUX_ANDROID | |
| 8200 const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR"); | |
| 8201 if (temp_dir == nullptr || temp_dir[0] == '\0') { | |
| 8202 return "/data/local/tmp/"; | |
| 8203 } else { | |
| 8204 return temp_dir; | |
| 8205 } | |
| 8206 #elif GTEST_OS_LINUX | |
| 8207 const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR"); | |
| 8208 if (temp_dir == nullptr || temp_dir[0] == '\0') { | |
| 8209 return "/tmp/"; | |
| 8210 } else { | |
| 8211 return temp_dir; | |
| 8212 } | |
| 8213 #else | |
| 8214 return "/tmp/"; | |
| 8215 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 8216 } | |
| 8217 | |
| 8218 // Class ScopedTrace | |
| 8219 | |
| 8220 // Pushes the given source file location and message onto a per-thread | |
| 8221 // trace stack maintained by Google Test. | |
| 8222 void ScopedTrace::PushTrace(const char* file, int line, std::string message) { | |
| 8223 internal::TraceInfo trace; | |
| 8224 trace.file = file; | |
| 8225 trace.line = line; | |
| 8226 trace.message.swap(message); | |
| 8227 | |
| 8228 UnitTest::GetInstance()->PushGTestTrace(trace); | |
| 8229 } | |
| 8230 | |
| 8231 // Pops the info pushed by the c'tor. | |
| 8232 ScopedTrace::~ScopedTrace() | |
| 8233 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { | |
| 8234 UnitTest::GetInstance()->PopGTestTrace(); | |
| 8235 } | |
| 8236 | |
| 8237 } // namespace testing | |
| 8238 // Copyright 2005, Google Inc. | |
| 8239 // All rights reserved. | |
| 8240 // | |
| 8241 // Redistribution and use in source and binary forms, with or without | |
| 8242 // modification, are permitted provided that the following conditions are | |
| 8243 // met: | |
| 8244 // | |
| 8245 // * Redistributions of source code must retain the above copyright | |
| 8246 // notice, this list of conditions and the following disclaimer. | |
| 8247 // * Redistributions in binary form must reproduce the above | |
| 8248 // copyright notice, this list of conditions and the following disclaimer | |
| 8249 // in the documentation and/or other materials provided with the | |
| 8250 // distribution. | |
| 8251 // * Neither the name of Google Inc. nor the names of its | |
| 8252 // contributors may be used to endorse or promote products derived from | |
| 8253 // this software without specific prior written permission. | |
| 8254 // | |
| 8255 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 8256 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 8257 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 8258 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 8259 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 8260 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 8261 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 8262 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 8263 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 8264 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 8265 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 8266 | |
| 8267 // | |
| 8268 // This file implements death tests. | |
| 8269 | |
| 8270 | |
| 8271 #include <functional> | |
| 8272 #include <utility> | |
| 8273 | |
| 8274 | |
| 8275 #if GTEST_HAS_DEATH_TEST | |
| 8276 | |
| 8277 # if GTEST_OS_MAC | |
| 8278 # include <crt_externs.h> | |
| 8279 # endif // GTEST_OS_MAC | |
| 8280 | |
| 8281 # include <errno.h> | |
| 8282 # include <fcntl.h> | |
| 8283 # include <limits.h> | |
| 8284 | |
| 8285 # if GTEST_OS_LINUX | |
| 8286 # include <signal.h> | |
| 8287 # endif // GTEST_OS_LINUX | |
| 8288 | |
| 8289 # include <stdarg.h> | |
| 8290 | |
| 8291 # if GTEST_OS_WINDOWS | |
| 8292 # include <windows.h> | |
| 8293 # else | |
| 8294 # include <sys/mman.h> | |
| 8295 # include <sys/wait.h> | |
| 8296 # endif // GTEST_OS_WINDOWS | |
| 8297 | |
| 8298 # if GTEST_OS_QNX | |
| 8299 # include <spawn.h> | |
| 8300 # endif // GTEST_OS_QNX | |
| 8301 | |
| 8302 # if GTEST_OS_FUCHSIA | |
| 8303 # include <lib/fdio/fd.h> | |
| 8304 # include <lib/fdio/io.h> | |
| 8305 # include <lib/fdio/spawn.h> | |
| 8306 # include <lib/zx/channel.h> | |
| 8307 # include <lib/zx/port.h> | |
| 8308 # include <lib/zx/process.h> | |
| 8309 # include <lib/zx/socket.h> | |
| 8310 # include <zircon/processargs.h> | |
| 8311 # include <zircon/syscalls.h> | |
| 8312 # include <zircon/syscalls/policy.h> | |
| 8313 # include <zircon/syscalls/port.h> | |
| 8314 # endif // GTEST_OS_FUCHSIA | |
| 8315 | |
| 8316 #endif // GTEST_HAS_DEATH_TEST | |
| 8317 | |
| 8318 | |
| 8319 namespace testing { | |
| 8320 | |
| 8321 // Constants. | |
| 8322 | |
| 8323 // The default death test style. | |
| 8324 // | |
| 8325 // This is defined in internal/gtest-port.h as "fast", but can be overridden by | |
| 8326 // a definition in internal/custom/gtest-port.h. The recommended value, which is | |
| 8327 // used internally at Google, is "threadsafe". | |
| 8328 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE; | |
| 8329 | |
| 8330 GTEST_DEFINE_string_( | |
| 8331 death_test_style, | |
| 8332 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), | |
| 8333 "Indicates how to run a death test in a forked child process: " | |
| 8334 "\"threadsafe\" (child process re-executes the test binary " | |
| 8335 "from the beginning, running only the specific death test) or " | |
| 8336 "\"fast\" (child process runs the death test immediately " | |
| 8337 "after forking)."); | |
| 8338 | |
| 8339 GTEST_DEFINE_bool_( | |
| 8340 death_test_use_fork, | |
| 8341 internal::BoolFromGTestEnv("death_test_use_fork", false), | |
| 8342 "Instructs to use fork()/_exit() instead of clone() in death tests. " | |
| 8343 "Ignored and always uses fork() on POSIX systems where clone() is not " | |
| 8344 "implemented. Useful when running under valgrind or similar tools if " | |
| 8345 "those do not support clone(). Valgrind 3.3.1 will just fail if " | |
| 8346 "it sees an unsupported combination of clone() flags. " | |
| 8347 "It is not recommended to use this flag w/o valgrind though it will " | |
| 8348 "work in 99% of the cases. Once valgrind is fixed, this flag will " | |
| 8349 "most likely be removed."); | |
| 8350 | |
| 8351 namespace internal { | |
| 8352 GTEST_DEFINE_string_( | |
| 8353 internal_run_death_test, "", | |
| 8354 "Indicates the file, line number, temporal index of " | |
| 8355 "the single death test to run, and a file descriptor to " | |
| 8356 "which a success code may be sent, all separated by " | |
| 8357 "the '|' characters. This flag is specified if and only if the " | |
| 8358 "current process is a sub-process launched for running a thread-safe " | |
| 8359 "death test. FOR INTERNAL USE ONLY."); | |
| 8360 } // namespace internal | |
| 8361 | |
| 8362 #if GTEST_HAS_DEATH_TEST | |
| 8363 | |
| 8364 namespace internal { | |
| 8365 | |
| 8366 // Valid only for fast death tests. Indicates the code is running in the | |
| 8367 // child process of a fast style death test. | |
| 8368 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA | |
| 8369 static bool g_in_fast_death_test_child = false; | |
| 8370 # endif | |
| 8371 | |
| 8372 // Returns a Boolean value indicating whether the caller is currently | |
| 8373 // executing in the context of the death test child process. Tools such as | |
| 8374 // Valgrind heap checkers may need this to modify their behavior in death | |
| 8375 // tests. IMPORTANT: This is an internal utility. Using it may break the | |
| 8376 // implementation of death tests. User code MUST NOT use it. | |
| 8377 bool InDeathTestChild() { | |
| 8378 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA | |
| 8379 | |
| 8380 // On Windows and Fuchsia, death tests are thread-safe regardless of the value | |
| 8381 // of the death_test_style flag. | |
| 8382 return !GTEST_FLAG(internal_run_death_test).empty(); | |
| 8383 | |
| 8384 # else | |
| 8385 | |
| 8386 if (GTEST_FLAG(death_test_style) == "threadsafe") | |
| 8387 return !GTEST_FLAG(internal_run_death_test).empty(); | |
| 8388 else | |
| 8389 return g_in_fast_death_test_child; | |
| 8390 #endif | |
| 8391 } | |
| 8392 | |
| 8393 } // namespace internal | |
| 8394 | |
| 8395 // ExitedWithCode constructor. | |
| 8396 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { | |
| 8397 } | |
| 8398 | |
| 8399 // ExitedWithCode function-call operator. | |
| 8400 bool ExitedWithCode::operator()(int exit_status) const { | |
| 8401 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA | |
| 8402 | |
| 8403 return exit_status == exit_code_; | |
| 8404 | |
| 8405 # else | |
| 8406 | |
| 8407 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; | |
| 8408 | |
| 8409 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA | |
| 8410 } | |
| 8411 | |
| 8412 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA | |
| 8413 // KilledBySignal constructor. | |
| 8414 KilledBySignal::KilledBySignal(int signum) : signum_(signum) { | |
| 8415 } | |
| 8416 | |
| 8417 // KilledBySignal function-call operator. | |
| 8418 bool KilledBySignal::operator()(int exit_status) const { | |
| 8419 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) | |
| 8420 { | |
| 8421 bool result; | |
| 8422 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { | |
| 8423 return result; | |
| 8424 } | |
| 8425 } | |
| 8426 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) | |
| 8427 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; | |
| 8428 } | |
| 8429 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA | |
| 8430 | |
| 8431 namespace internal { | |
| 8432 | |
| 8433 // Utilities needed for death tests. | |
| 8434 | |
| 8435 // Generates a textual description of a given exit code, in the format | |
| 8436 // specified by wait(2). | |
| 8437 static std::string ExitSummary(int exit_code) { | |
| 8438 Message m; | |
| 8439 | |
| 8440 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA | |
| 8441 | |
| 8442 m << "Exited with exit status " << exit_code; | |
| 8443 | |
| 8444 # else | |
| 8445 | |
| 8446 if (WIFEXITED(exit_code)) { | |
| 8447 m << "Exited with exit status " << WEXITSTATUS(exit_code); | |
| 8448 } else if (WIFSIGNALED(exit_code)) { | |
| 8449 m << "Terminated by signal " << WTERMSIG(exit_code); | |
| 8450 } | |
| 8451 # ifdef WCOREDUMP | |
| 8452 if (WCOREDUMP(exit_code)) { | |
| 8453 m << " (core dumped)"; | |
| 8454 } | |
| 8455 # endif | |
| 8456 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA | |
| 8457 | |
| 8458 return m.GetString(); | |
| 8459 } | |
| 8460 | |
| 8461 // Returns true if exit_status describes a process that was terminated | |
| 8462 // by a signal, or exited normally with a nonzero exit code. | |
| 8463 bool ExitedUnsuccessfully(int exit_status) { | |
| 8464 return !ExitedWithCode(0)(exit_status); | |
| 8465 } | |
| 8466 | |
| 8467 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA | |
| 8468 // Generates a textual failure message when a death test finds more than | |
| 8469 // one thread running, or cannot determine the number of threads, prior | |
| 8470 // to executing the given statement. It is the responsibility of the | |
| 8471 // caller not to pass a thread_count of 1. | |
| 8472 static std::string DeathTestThreadWarning(size_t thread_count) { | |
| 8473 Message msg; | |
| 8474 msg << "Death tests use fork(), which is unsafe particularly" | |
| 8475 << " in a threaded context. For this test, " << GTEST_NAME_ << " "; | |
| 8476 if (thread_count == 0) { | |
| 8477 msg << "couldn't detect the number of threads."; | |
| 8478 } else { | |
| 8479 msg << "detected " << thread_count << " threads."; | |
| 8480 } | |
| 8481 msg << " See " | |
| 8482 "https://github.com/google/googletest/blob/master/docs/" | |
| 8483 "advanced.md#death-tests-and-threads" | |
| 8484 << " for more explanation and suggested solutions, especially if" | |
| 8485 << " this is the last message you see before your test times out."; | |
| 8486 return msg.GetString(); | |
| 8487 } | |
| 8488 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA | |
| 8489 | |
| 8490 // Flag characters for reporting a death test that did not die. | |
| 8491 static const char kDeathTestLived = 'L'; | |
| 8492 static const char kDeathTestReturned = 'R'; | |
| 8493 static const char kDeathTestThrew = 'T'; | |
| 8494 static const char kDeathTestInternalError = 'I'; | |
| 8495 | |
| 8496 #if GTEST_OS_FUCHSIA | |
| 8497 | |
| 8498 // File descriptor used for the pipe in the child process. | |
| 8499 static const int kFuchsiaReadPipeFd = 3; | |
| 8500 | |
| 8501 #endif | |
| 8502 | |
| 8503 // An enumeration describing all of the possible ways that a death test can | |
| 8504 // conclude. DIED means that the process died while executing the test | |
| 8505 // code; LIVED means that process lived beyond the end of the test code; | |
| 8506 // RETURNED means that the test statement attempted to execute a return | |
| 8507 // statement, which is not allowed; THREW means that the test statement | |
| 8508 // returned control by throwing an exception. IN_PROGRESS means the test | |
| 8509 // has not yet concluded. | |
| 8510 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; | |
| 8511 | |
| 8512 // Routine for aborting the program which is safe to call from an | |
| 8513 // exec-style death test child process, in which case the error | |
| 8514 // message is propagated back to the parent process. Otherwise, the | |
| 8515 // message is simply printed to stderr. In either case, the program | |
| 8516 // then exits with status 1. | |
| 8517 static void DeathTestAbort(const std::string& message) { | |
| 8518 // On a POSIX system, this function may be called from a threadsafe-style | |
| 8519 // death test child process, which operates on a very small stack. Use | |
| 8520 // the heap for any additional non-minuscule memory requirements. | |
| 8521 const InternalRunDeathTestFlag* const flag = | |
| 8522 GetUnitTestImpl()->internal_run_death_test_flag(); | |
| 8523 if (flag != nullptr) { | |
| 8524 FILE* parent = posix::FDOpen(flag->write_fd(), "w"); | |
| 8525 fputc(kDeathTestInternalError, parent); | |
| 8526 fprintf(parent, "%s", message.c_str()); | |
| 8527 fflush(parent); | |
| 8528 _exit(1); | |
| 8529 } else { | |
| 8530 fprintf(stderr, "%s", message.c_str()); | |
| 8531 fflush(stderr); | |
| 8532 posix::Abort(); | |
| 8533 } | |
| 8534 } | |
| 8535 | |
| 8536 // A replacement for CHECK that calls DeathTestAbort if the assertion | |
| 8537 // fails. | |
| 8538 # define GTEST_DEATH_TEST_CHECK_(expression) \ | |
| 8539 do { \ | |
| 8540 if (!::testing::internal::IsTrue(expression)) { \ | |
| 8541 DeathTestAbort( \ | |
| 8542 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ | |
| 8543 + ::testing::internal::StreamableToString(__LINE__) + ": " \ | |
| 8544 + #expression); \ | |
| 8545 } \ | |
| 8546 } while (::testing::internal::AlwaysFalse()) | |
| 8547 | |
| 8548 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for | |
| 8549 // evaluating any system call that fulfills two conditions: it must return | |
| 8550 // -1 on failure, and set errno to EINTR when it is interrupted and | |
| 8551 // should be tried again. The macro expands to a loop that repeatedly | |
| 8552 // evaluates the expression as long as it evaluates to -1 and sets | |
| 8553 // errno to EINTR. If the expression evaluates to -1 but errno is | |
| 8554 // something other than EINTR, DeathTestAbort is called. | |
| 8555 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ | |
| 8556 do { \ | |
| 8557 int gtest_retval; \ | |
| 8558 do { \ | |
| 8559 gtest_retval = (expression); \ | |
| 8560 } while (gtest_retval == -1 && errno == EINTR); \ | |
| 8561 if (gtest_retval == -1) { \ | |
| 8562 DeathTestAbort( \ | |
| 8563 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ | |
| 8564 + ::testing::internal::StreamableToString(__LINE__) + ": " \ | |
| 8565 + #expression + " != -1"); \ | |
| 8566 } \ | |
| 8567 } while (::testing::internal::AlwaysFalse()) | |
| 8568 | |
| 8569 // Returns the message describing the last system error in errno. | |
| 8570 std::string GetLastErrnoDescription() { | |
| 8571 return errno == 0 ? "" : posix::StrError(errno); | |
| 8572 } | |
| 8573 | |
| 8574 // This is called from a death test parent process to read a failure | |
| 8575 // message from the death test child process and log it with the FATAL | |
| 8576 // severity. On Windows, the message is read from a pipe handle. On other | |
| 8577 // platforms, it is read from a file descriptor. | |
| 8578 static void FailFromInternalError(int fd) { | |
| 8579 Message error; | |
| 8580 char buffer[256]; | |
| 8581 int num_read; | |
| 8582 | |
| 8583 do { | |
| 8584 while ((num_read = posix::Read(fd, buffer, 255)) > 0) { | |
| 8585 buffer[num_read] = '\0'; | |
| 8586 error << buffer; | |
| 8587 } | |
| 8588 } while (num_read == -1 && errno == EINTR); | |
| 8589 | |
| 8590 if (num_read == 0) { | |
| 8591 GTEST_LOG_(FATAL) << error.GetString(); | |
| 8592 } else { | |
| 8593 const int last_error = errno; | |
| 8594 GTEST_LOG_(FATAL) << "Error while reading death test internal: " | |
| 8595 << GetLastErrnoDescription() << " [" << last_error << "]"; | |
| 8596 } | |
| 8597 } | |
| 8598 | |
| 8599 // Death test constructor. Increments the running death test count | |
| 8600 // for the current test. | |
| 8601 DeathTest::DeathTest() { | |
| 8602 TestInfo* const info = GetUnitTestImpl()->current_test_info(); | |
| 8603 if (info == nullptr) { | |
| 8604 DeathTestAbort("Cannot run a death test outside of a TEST or " | |
| 8605 "TEST_F construct"); | |
| 8606 } | |
| 8607 } | |
| 8608 | |
| 8609 // Creates and returns a death test by dispatching to the current | |
| 8610 // death test factory. | |
| 8611 bool DeathTest::Create(const char* statement, | |
| 8612 Matcher<const std::string&> matcher, const char* file, | |
| 8613 int line, DeathTest** test) { | |
| 8614 return GetUnitTestImpl()->death_test_factory()->Create( | |
| 8615 statement, std::move(matcher), file, line, test); | |
| 8616 } | |
| 8617 | |
| 8618 const char* DeathTest::LastMessage() { | |
| 8619 return last_death_test_message_.c_str(); | |
| 8620 } | |
| 8621 | |
| 8622 void DeathTest::set_last_death_test_message(const std::string& message) { | |
| 8623 last_death_test_message_ = message; | |
| 8624 } | |
| 8625 | |
| 8626 std::string DeathTest::last_death_test_message_; | |
| 8627 | |
| 8628 // Provides cross platform implementation for some death functionality. | |
| 8629 class DeathTestImpl : public DeathTest { | |
| 8630 protected: | |
| 8631 DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher) | |
| 8632 : statement_(a_statement), | |
| 8633 matcher_(std::move(matcher)), | |
| 8634 spawned_(false), | |
| 8635 status_(-1), | |
| 8636 outcome_(IN_PROGRESS), | |
| 8637 read_fd_(-1), | |
| 8638 write_fd_(-1) {} | |
| 8639 | |
| 8640 // read_fd_ is expected to be closed and cleared by a derived class. | |
| 8641 ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } | |
| 8642 | |
| 8643 void Abort(AbortReason reason) override; | |
| 8644 bool Passed(bool status_ok) override; | |
| 8645 | |
| 8646 const char* statement() const { return statement_; } | |
| 8647 bool spawned() const { return spawned_; } | |
| 8648 void set_spawned(bool is_spawned) { spawned_ = is_spawned; } | |
| 8649 int status() const { return status_; } | |
| 8650 void set_status(int a_status) { status_ = a_status; } | |
| 8651 DeathTestOutcome outcome() const { return outcome_; } | |
| 8652 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } | |
| 8653 int read_fd() const { return read_fd_; } | |
| 8654 void set_read_fd(int fd) { read_fd_ = fd; } | |
| 8655 int write_fd() const { return write_fd_; } | |
| 8656 void set_write_fd(int fd) { write_fd_ = fd; } | |
| 8657 | |
| 8658 // Called in the parent process only. Reads the result code of the death | |
| 8659 // test child process via a pipe, interprets it to set the outcome_ | |
| 8660 // member, and closes read_fd_. Outputs diagnostics and terminates in | |
| 8661 // case of unexpected codes. | |
| 8662 void ReadAndInterpretStatusByte(); | |
| 8663 | |
| 8664 // Returns stderr output from the child process. | |
| 8665 virtual std::string GetErrorLogs(); | |
| 8666 | |
| 8667 private: | |
| 8668 // The textual content of the code this object is testing. This class | |
| 8669 // doesn't own this string and should not attempt to delete it. | |
| 8670 const char* const statement_; | |
| 8671 // A matcher that's expected to match the stderr output by the child process. | |
| 8672 Matcher<const std::string&> matcher_; | |
| 8673 // True if the death test child process has been successfully spawned. | |
| 8674 bool spawned_; | |
| 8675 // The exit status of the child process. | |
| 8676 int status_; | |
| 8677 // How the death test concluded. | |
| 8678 DeathTestOutcome outcome_; | |
| 8679 // Descriptor to the read end of the pipe to the child process. It is | |
| 8680 // always -1 in the child process. The child keeps its write end of the | |
| 8681 // pipe in write_fd_. | |
| 8682 int read_fd_; | |
| 8683 // Descriptor to the child's write end of the pipe to the parent process. | |
| 8684 // It is always -1 in the parent process. The parent keeps its end of the | |
| 8685 // pipe in read_fd_. | |
| 8686 int write_fd_; | |
| 8687 }; | |
| 8688 | |
| 8689 // Called in the parent process only. Reads the result code of the death | |
| 8690 // test child process via a pipe, interprets it to set the outcome_ | |
| 8691 // member, and closes read_fd_. Outputs diagnostics and terminates in | |
| 8692 // case of unexpected codes. | |
| 8693 void DeathTestImpl::ReadAndInterpretStatusByte() { | |
| 8694 char flag; | |
| 8695 int bytes_read; | |
| 8696 | |
| 8697 // The read() here blocks until data is available (signifying the | |
| 8698 // failure of the death test) or until the pipe is closed (signifying | |
| 8699 // its success), so it's okay to call this in the parent before | |
| 8700 // the child process has exited. | |
| 8701 do { | |
| 8702 bytes_read = posix::Read(read_fd(), &flag, 1); | |
| 8703 } while (bytes_read == -1 && errno == EINTR); | |
| 8704 | |
| 8705 if (bytes_read == 0) { | |
| 8706 set_outcome(DIED); | |
| 8707 } else if (bytes_read == 1) { | |
| 8708 switch (flag) { | |
| 8709 case kDeathTestReturned: | |
| 8710 set_outcome(RETURNED); | |
| 8711 break; | |
| 8712 case kDeathTestThrew: | |
| 8713 set_outcome(THREW); | |
| 8714 break; | |
| 8715 case kDeathTestLived: | |
| 8716 set_outcome(LIVED); | |
| 8717 break; | |
| 8718 case kDeathTestInternalError: | |
| 8719 FailFromInternalError(read_fd()); // Does not return. | |
| 8720 break; | |
| 8721 default: | |
| 8722 GTEST_LOG_(FATAL) << "Death test child process reported " | |
| 8723 << "unexpected status byte (" | |
| 8724 << static_cast<unsigned int>(flag) << ")"; | |
| 8725 } | |
| 8726 } else { | |
| 8727 GTEST_LOG_(FATAL) << "Read from death test child process failed: " | |
| 8728 << GetLastErrnoDescription(); | |
| 8729 } | |
| 8730 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); | |
| 8731 set_read_fd(-1); | |
| 8732 } | |
| 8733 | |
| 8734 std::string DeathTestImpl::GetErrorLogs() { | |
| 8735 return GetCapturedStderr(); | |
| 8736 } | |
| 8737 | |
| 8738 // Signals that the death test code which should have exited, didn't. | |
| 8739 // Should be called only in a death test child process. | |
| 8740 // Writes a status byte to the child's status file descriptor, then | |
| 8741 // calls _exit(1). | |
| 8742 void DeathTestImpl::Abort(AbortReason reason) { | |
| 8743 // The parent process considers the death test to be a failure if | |
| 8744 // it finds any data in our pipe. So, here we write a single flag byte | |
| 8745 // to the pipe, then exit. | |
| 8746 const char status_ch = | |
| 8747 reason == TEST_DID_NOT_DIE ? kDeathTestLived : | |
| 8748 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; | |
| 8749 | |
| 8750 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); | |
| 8751 // We are leaking the descriptor here because on some platforms (i.e., | |
| 8752 // when built as Windows DLL), destructors of global objects will still | |
| 8753 // run after calling _exit(). On such systems, write_fd_ will be | |
| 8754 // indirectly closed from the destructor of UnitTestImpl, causing double | |
| 8755 // close if it is also closed here. On debug configurations, double close | |
| 8756 // may assert. As there are no in-process buffers to flush here, we are | |
| 8757 // relying on the OS to close the descriptor after the process terminates | |
| 8758 // when the destructors are not run. | |
| 8759 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) | |
| 8760 } | |
| 8761 | |
| 8762 // Returns an indented copy of stderr output for a death test. | |
| 8763 // This makes distinguishing death test output lines from regular log lines | |
| 8764 // much easier. | |
| 8765 static ::std::string FormatDeathTestOutput(const ::std::string& output) { | |
| 8766 ::std::string ret; | |
| 8767 for (size_t at = 0; ; ) { | |
| 8768 const size_t line_end = output.find('\n', at); | |
| 8769 ret += "[ DEATH ] "; | |
| 8770 if (line_end == ::std::string::npos) { | |
| 8771 ret += output.substr(at); | |
| 8772 break; | |
| 8773 } | |
| 8774 ret += output.substr(at, line_end + 1 - at); | |
| 8775 at = line_end + 1; | |
| 8776 } | |
| 8777 return ret; | |
| 8778 } | |
| 8779 | |
| 8780 // Assesses the success or failure of a death test, using both private | |
| 8781 // members which have previously been set, and one argument: | |
| 8782 // | |
| 8783 // Private data members: | |
| 8784 // outcome: An enumeration describing how the death test | |
| 8785 // concluded: DIED, LIVED, THREW, or RETURNED. The death test | |
| 8786 // fails in the latter three cases. | |
| 8787 // status: The exit status of the child process. On *nix, it is in the | |
| 8788 // in the format specified by wait(2). On Windows, this is the | |
| 8789 // value supplied to the ExitProcess() API or a numeric code | |
| 8790 // of the exception that terminated the program. | |
| 8791 // matcher_: A matcher that's expected to match the stderr output by the child | |
| 8792 // process. | |
| 8793 // | |
| 8794 // Argument: | |
| 8795 // status_ok: true if exit_status is acceptable in the context of | |
| 8796 // this particular death test, which fails if it is false | |
| 8797 // | |
| 8798 // Returns true if and only if all of the above conditions are met. Otherwise, | |
| 8799 // the first failing condition, in the order given above, is the one that is | |
| 8800 // reported. Also sets the last death test message string. | |
| 8801 bool DeathTestImpl::Passed(bool status_ok) { | |
| 8802 if (!spawned()) | |
| 8803 return false; | |
| 8804 | |
| 8805 const std::string error_message = GetErrorLogs(); | |
| 8806 | |
| 8807 bool success = false; | |
| 8808 Message buffer; | |
| 8809 | |
| 8810 buffer << "Death test: " << statement() << "\n"; | |
| 8811 switch (outcome()) { | |
| 8812 case LIVED: | |
| 8813 buffer << " Result: failed to die.\n" | |
| 8814 << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
| 8815 break; | |
| 8816 case THREW: | |
| 8817 buffer << " Result: threw an exception.\n" | |
| 8818 << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
| 8819 break; | |
| 8820 case RETURNED: | |
| 8821 buffer << " Result: illegal return in test statement.\n" | |
| 8822 << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
| 8823 break; | |
| 8824 case DIED: | |
| 8825 if (status_ok) { | |
| 8826 if (matcher_.Matches(error_message)) { | |
| 8827 success = true; | |
| 8828 } else { | |
| 8829 std::ostringstream stream; | |
| 8830 matcher_.DescribeTo(&stream); | |
| 8831 buffer << " Result: died but not with expected error.\n" | |
| 8832 << " Expected: " << stream.str() << "\n" | |
| 8833 << "Actual msg:\n" | |
| 8834 << FormatDeathTestOutput(error_message); | |
| 8835 } | |
| 8836 } else { | |
| 8837 buffer << " Result: died but not with expected exit code:\n" | |
| 8838 << " " << ExitSummary(status()) << "\n" | |
| 8839 << "Actual msg:\n" << FormatDeathTestOutput(error_message); | |
| 8840 } | |
| 8841 break; | |
| 8842 case IN_PROGRESS: | |
| 8843 default: | |
| 8844 GTEST_LOG_(FATAL) | |
| 8845 << "DeathTest::Passed somehow called before conclusion of test"; | |
| 8846 } | |
| 8847 | |
| 8848 DeathTest::set_last_death_test_message(buffer.GetString()); | |
| 8849 return success; | |
| 8850 } | |
| 8851 | |
| 8852 # if GTEST_OS_WINDOWS | |
| 8853 // WindowsDeathTest implements death tests on Windows. Due to the | |
| 8854 // specifics of starting new processes on Windows, death tests there are | |
| 8855 // always threadsafe, and Google Test considers the | |
| 8856 // --gtest_death_test_style=fast setting to be equivalent to | |
| 8857 // --gtest_death_test_style=threadsafe there. | |
| 8858 // | |
| 8859 // A few implementation notes: Like the Linux version, the Windows | |
| 8860 // implementation uses pipes for child-to-parent communication. But due to | |
| 8861 // the specifics of pipes on Windows, some extra steps are required: | |
| 8862 // | |
| 8863 // 1. The parent creates a communication pipe and stores handles to both | |
| 8864 // ends of it. | |
| 8865 // 2. The parent starts the child and provides it with the information | |
| 8866 // necessary to acquire the handle to the write end of the pipe. | |
| 8867 // 3. The child acquires the write end of the pipe and signals the parent | |
| 8868 // using a Windows event. | |
| 8869 // 4. Now the parent can release the write end of the pipe on its side. If | |
| 8870 // this is done before step 3, the object's reference count goes down to | |
| 8871 // 0 and it is destroyed, preventing the child from acquiring it. The | |
| 8872 // parent now has to release it, or read operations on the read end of | |
| 8873 // the pipe will not return when the child terminates. | |
| 8874 // 5. The parent reads child's output through the pipe (outcome code and | |
| 8875 // any possible error messages) from the pipe, and its stderr and then | |
| 8876 // determines whether to fail the test. | |
| 8877 // | |
| 8878 // Note: to distinguish Win32 API calls from the local method and function | |
| 8879 // calls, the former are explicitly resolved in the global namespace. | |
| 8880 // | |
| 8881 class WindowsDeathTest : public DeathTestImpl { | |
| 8882 public: | |
| 8883 WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher, | |
| 8884 const char* file, int line) | |
| 8885 : DeathTestImpl(a_statement, std::move(matcher)), | |
| 8886 file_(file), | |
| 8887 line_(line) {} | |
| 8888 | |
| 8889 // All of these virtual functions are inherited from DeathTest. | |
| 8890 virtual int Wait(); | |
| 8891 virtual TestRole AssumeRole(); | |
| 8892 | |
| 8893 private: | |
| 8894 // The name of the file in which the death test is located. | |
| 8895 const char* const file_; | |
| 8896 // The line number on which the death test is located. | |
| 8897 const int line_; | |
| 8898 // Handle to the write end of the pipe to the child process. | |
| 8899 AutoHandle write_handle_; | |
| 8900 // Child process handle. | |
| 8901 AutoHandle child_handle_; | |
| 8902 // Event the child process uses to signal the parent that it has | |
| 8903 // acquired the handle to the write end of the pipe. After seeing this | |
| 8904 // event the parent can release its own handles to make sure its | |
| 8905 // ReadFile() calls return when the child terminates. | |
| 8906 AutoHandle event_handle_; | |
| 8907 }; | |
| 8908 | |
| 8909 // Waits for the child in a death test to exit, returning its exit | |
| 8910 // status, or 0 if no child process exists. As a side effect, sets the | |
| 8911 // outcome data member. | |
| 8912 int WindowsDeathTest::Wait() { | |
| 8913 if (!spawned()) | |
| 8914 return 0; | |
| 8915 | |
| 8916 // Wait until the child either signals that it has acquired the write end | |
| 8917 // of the pipe or it dies. | |
| 8918 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; | |
| 8919 switch (::WaitForMultipleObjects(2, | |
| 8920 wait_handles, | |
| 8921 FALSE, // Waits for any of the handles. | |
| 8922 INFINITE)) { | |
| 8923 case WAIT_OBJECT_0: | |
| 8924 case WAIT_OBJECT_0 + 1: | |
| 8925 break; | |
| 8926 default: | |
| 8927 GTEST_DEATH_TEST_CHECK_(false); // Should not get here. | |
| 8928 } | |
| 8929 | |
| 8930 // The child has acquired the write end of the pipe or exited. | |
| 8931 // We release the handle on our side and continue. | |
| 8932 write_handle_.Reset(); | |
| 8933 event_handle_.Reset(); | |
| 8934 | |
| 8935 ReadAndInterpretStatusByte(); | |
| 8936 | |
| 8937 // Waits for the child process to exit if it haven't already. This | |
| 8938 // returns immediately if the child has already exited, regardless of | |
| 8939 // whether previous calls to WaitForMultipleObjects synchronized on this | |
| 8940 // handle or not. | |
| 8941 GTEST_DEATH_TEST_CHECK_( | |
| 8942 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), | |
| 8943 INFINITE)); | |
| 8944 DWORD status_code; | |
| 8945 GTEST_DEATH_TEST_CHECK_( | |
| 8946 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); | |
| 8947 child_handle_.Reset(); | |
| 8948 set_status(static_cast<int>(status_code)); | |
| 8949 return status(); | |
| 8950 } | |
| 8951 | |
| 8952 // The AssumeRole process for a Windows death test. It creates a child | |
| 8953 // process with the same executable as the current process to run the | |
| 8954 // death test. The child process is given the --gtest_filter and | |
| 8955 // --gtest_internal_run_death_test flags such that it knows to run the | |
| 8956 // current death test only. | |
| 8957 DeathTest::TestRole WindowsDeathTest::AssumeRole() { | |
| 8958 const UnitTestImpl* const impl = GetUnitTestImpl(); | |
| 8959 const InternalRunDeathTestFlag* const flag = | |
| 8960 impl->internal_run_death_test_flag(); | |
| 8961 const TestInfo* const info = impl->current_test_info(); | |
| 8962 const int death_test_index = info->result()->death_test_count(); | |
| 8963 | |
| 8964 if (flag != nullptr) { | |
| 8965 // ParseInternalRunDeathTestFlag() has performed all the necessary | |
| 8966 // processing. | |
| 8967 set_write_fd(flag->write_fd()); | |
| 8968 return EXECUTE_TEST; | |
| 8969 } | |
| 8970 | |
| 8971 // WindowsDeathTest uses an anonymous pipe to communicate results of | |
| 8972 // a death test. | |
| 8973 SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), | |
| 8974 nullptr, TRUE}; | |
| 8975 HANDLE read_handle, write_handle; | |
| 8976 GTEST_DEATH_TEST_CHECK_( | |
| 8977 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, | |
| 8978 0) // Default buffer size. | |
| 8979 != FALSE); | |
| 8980 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), | |
| 8981 O_RDONLY)); | |
| 8982 write_handle_.Reset(write_handle); | |
| 8983 event_handle_.Reset(::CreateEvent( | |
| 8984 &handles_are_inheritable, | |
| 8985 TRUE, // The event will automatically reset to non-signaled state. | |
| 8986 FALSE, // The initial state is non-signalled. | |
| 8987 nullptr)); // The even is unnamed. | |
| 8988 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr); | |
| 8989 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + | |
| 8990 kFilterFlag + "=" + info->test_suite_name() + | |
| 8991 "." + info->name(); | |
| 8992 const std::string internal_flag = | |
| 8993 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + | |
| 8994 "=" + file_ + "|" + StreamableToString(line_) + "|" + | |
| 8995 StreamableToString(death_test_index) + "|" + | |
| 8996 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + | |
| 8997 // size_t has the same width as pointers on both 32-bit and 64-bit | |
| 8998 // Windows platforms. | |
| 8999 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. | |
| 9000 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + | |
| 9001 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); | |
| 9002 | |
| 9003 char executable_path[_MAX_PATH + 1]; // NOLINT | |
| 9004 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr, | |
| 9005 executable_path, | |
| 9006 _MAX_PATH)); | |
| 9007 | |
| 9008 std::string command_line = | |
| 9009 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + | |
| 9010 internal_flag + "\""; | |
| 9011 | |
| 9012 DeathTest::set_last_death_test_message(""); | |
| 9013 | |
| 9014 CaptureStderr(); | |
| 9015 // Flush the log buffers since the log streams are shared with the child. | |
| 9016 FlushInfoLog(); | |
| 9017 | |
| 9018 // The child process will share the standard handles with the parent. | |
| 9019 STARTUPINFOA startup_info; | |
| 9020 memset(&startup_info, 0, sizeof(STARTUPINFO)); | |
| 9021 startup_info.dwFlags = STARTF_USESTDHANDLES; | |
| 9022 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); | |
| 9023 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); | |
| 9024 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); | |
| 9025 | |
| 9026 PROCESS_INFORMATION process_info; | |
| 9027 GTEST_DEATH_TEST_CHECK_( | |
| 9028 ::CreateProcessA( | |
| 9029 executable_path, const_cast<char*>(command_line.c_str()), | |
| 9030 nullptr, // Retuned process handle is not inheritable. | |
| 9031 nullptr, // Retuned thread handle is not inheritable. | |
| 9032 TRUE, // Child inherits all inheritable handles (for write_handle_). | |
| 9033 0x0, // Default creation flags. | |
| 9034 nullptr, // Inherit the parent's environment. | |
| 9035 UnitTest::GetInstance()->original_working_dir(), &startup_info, | |
| 9036 &process_info) != FALSE); | |
| 9037 child_handle_.Reset(process_info.hProcess); | |
| 9038 ::CloseHandle(process_info.hThread); | |
| 9039 set_spawned(true); | |
| 9040 return OVERSEE_TEST; | |
| 9041 } | |
| 9042 | |
| 9043 # elif GTEST_OS_FUCHSIA | |
| 9044 | |
| 9045 class FuchsiaDeathTest : public DeathTestImpl { | |
| 9046 public: | |
| 9047 FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher, | |
| 9048 const char* file, int line) | |
| 9049 : DeathTestImpl(a_statement, std::move(matcher)), | |
| 9050 file_(file), | |
| 9051 line_(line) {} | |
| 9052 | |
| 9053 // All of these virtual functions are inherited from DeathTest. | |
| 9054 int Wait() override; | |
| 9055 TestRole AssumeRole() override; | |
| 9056 std::string GetErrorLogs() override; | |
| 9057 | |
| 9058 private: | |
| 9059 // The name of the file in which the death test is located. | |
| 9060 const char* const file_; | |
| 9061 // The line number on which the death test is located. | |
| 9062 const int line_; | |
| 9063 // The stderr data captured by the child process. | |
| 9064 std::string captured_stderr_; | |
| 9065 | |
| 9066 zx::process child_process_; | |
| 9067 zx::channel exception_channel_; | |
| 9068 zx::socket stderr_socket_; | |
| 9069 }; | |
| 9070 | |
| 9071 // Utility class for accumulating command-line arguments. | |
| 9072 class Arguments { | |
| 9073 public: | |
| 9074 Arguments() { args_.push_back(nullptr); } | |
| 9075 | |
| 9076 ~Arguments() { | |
| 9077 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); | |
| 9078 ++i) { | |
| 9079 free(*i); | |
| 9080 } | |
| 9081 } | |
| 9082 void AddArgument(const char* argument) { | |
| 9083 args_.insert(args_.end() - 1, posix::StrDup(argument)); | |
| 9084 } | |
| 9085 | |
| 9086 template <typename Str> | |
| 9087 void AddArguments(const ::std::vector<Str>& arguments) { | |
| 9088 for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); | |
| 9089 i != arguments.end(); | |
| 9090 ++i) { | |
| 9091 args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); | |
| 9092 } | |
| 9093 } | |
| 9094 char* const* Argv() { | |
| 9095 return &args_[0]; | |
| 9096 } | |
| 9097 | |
| 9098 int size() { | |
| 9099 return static_cast<int>(args_.size()) - 1; | |
| 9100 } | |
| 9101 | |
| 9102 private: | |
| 9103 std::vector<char*> args_; | |
| 9104 }; | |
| 9105 | |
| 9106 // Waits for the child in a death test to exit, returning its exit | |
| 9107 // status, or 0 if no child process exists. As a side effect, sets the | |
| 9108 // outcome data member. | |
| 9109 int FuchsiaDeathTest::Wait() { | |
| 9110 const int kProcessKey = 0; | |
| 9111 const int kSocketKey = 1; | |
| 9112 const int kExceptionKey = 2; | |
| 9113 | |
| 9114 if (!spawned()) | |
| 9115 return 0; | |
| 9116 | |
| 9117 // Create a port to wait for socket/task/exception events. | |
| 9118 zx_status_t status_zx; | |
| 9119 zx::port port; | |
| 9120 status_zx = zx::port::create(0, &port); | |
| 9121 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9122 | |
| 9123 // Register to wait for the child process to terminate. | |
| 9124 status_zx = child_process_.wait_async( | |
| 9125 port, kProcessKey, ZX_PROCESS_TERMINATED, 0); | |
| 9126 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9127 | |
| 9128 // Register to wait for the socket to be readable or closed. | |
| 9129 status_zx = stderr_socket_.wait_async( | |
| 9130 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0); | |
| 9131 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9132 | |
| 9133 // Register to wait for an exception. | |
| 9134 status_zx = exception_channel_.wait_async( | |
| 9135 port, kExceptionKey, ZX_CHANNEL_READABLE, 0); | |
| 9136 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9137 | |
| 9138 bool process_terminated = false; | |
| 9139 bool socket_closed = false; | |
| 9140 do { | |
| 9141 zx_port_packet_t packet = {}; | |
| 9142 status_zx = port.wait(zx::time::infinite(), &packet); | |
| 9143 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9144 | |
| 9145 if (packet.key == kExceptionKey) { | |
| 9146 // Process encountered an exception. Kill it directly rather than | |
| 9147 // letting other handlers process the event. We will get a kProcessKey | |
| 9148 // event when the process actually terminates. | |
| 9149 status_zx = child_process_.kill(); | |
| 9150 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9151 } else if (packet.key == kProcessKey) { | |
| 9152 // Process terminated. | |
| 9153 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); | |
| 9154 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED); | |
| 9155 process_terminated = true; | |
| 9156 } else if (packet.key == kSocketKey) { | |
| 9157 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); | |
| 9158 if (packet.signal.observed & ZX_SOCKET_READABLE) { | |
| 9159 // Read data from the socket. | |
| 9160 constexpr size_t kBufferSize = 1024; | |
| 9161 do { | |
| 9162 size_t old_length = captured_stderr_.length(); | |
| 9163 size_t bytes_read = 0; | |
| 9164 captured_stderr_.resize(old_length + kBufferSize); | |
| 9165 status_zx = stderr_socket_.read( | |
| 9166 0, &captured_stderr_.front() + old_length, kBufferSize, | |
| 9167 &bytes_read); | |
| 9168 captured_stderr_.resize(old_length + bytes_read); | |
| 9169 } while (status_zx == ZX_OK); | |
| 9170 if (status_zx == ZX_ERR_PEER_CLOSED) { | |
| 9171 socket_closed = true; | |
| 9172 } else { | |
| 9173 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT); | |
| 9174 status_zx = stderr_socket_.wait_async( | |
| 9175 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0); | |
| 9176 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9177 } | |
| 9178 } else { | |
| 9179 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED); | |
| 9180 socket_closed = true; | |
| 9181 } | |
| 9182 } | |
| 9183 } while (!process_terminated && !socket_closed); | |
| 9184 | |
| 9185 ReadAndInterpretStatusByte(); | |
| 9186 | |
| 9187 zx_info_process_v2_t buffer; | |
| 9188 status_zx = child_process_.get_info( | |
| 9189 ZX_INFO_PROCESS_V2, &buffer, sizeof(buffer), nullptr, nullptr); | |
| 9190 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); | |
| 9191 | |
| 9192 GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED); | |
| 9193 set_status(static_cast<int>(buffer.return_code)); | |
| 9194 return status(); | |
| 9195 } | |
| 9196 | |
| 9197 // The AssumeRole process for a Fuchsia death test. It creates a child | |
| 9198 // process with the same executable as the current process to run the | |
| 9199 // death test. The child process is given the --gtest_filter and | |
| 9200 // --gtest_internal_run_death_test flags such that it knows to run the | |
| 9201 // current death test only. | |
| 9202 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { | |
| 9203 const UnitTestImpl* const impl = GetUnitTestImpl(); | |
| 9204 const InternalRunDeathTestFlag* const flag = | |
| 9205 impl->internal_run_death_test_flag(); | |
| 9206 const TestInfo* const info = impl->current_test_info(); | |
| 9207 const int death_test_index = info->result()->death_test_count(); | |
| 9208 | |
| 9209 if (flag != nullptr) { | |
| 9210 // ParseInternalRunDeathTestFlag() has performed all the necessary | |
| 9211 // processing. | |
| 9212 set_write_fd(kFuchsiaReadPipeFd); | |
| 9213 return EXECUTE_TEST; | |
| 9214 } | |
| 9215 | |
| 9216 // Flush the log buffers since the log streams are shared with the child. | |
| 9217 FlushInfoLog(); | |
| 9218 | |
| 9219 // Build the child process command line. | |
| 9220 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + | |
| 9221 kFilterFlag + "=" + info->test_suite_name() + | |
| 9222 "." + info->name(); | |
| 9223 const std::string internal_flag = | |
| 9224 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" | |
| 9225 + file_ + "|" | |
| 9226 + StreamableToString(line_) + "|" | |
| 9227 + StreamableToString(death_test_index); | |
| 9228 Arguments args; | |
| 9229 args.AddArguments(GetInjectableArgvs()); | |
| 9230 args.AddArgument(filter_flag.c_str()); | |
| 9231 args.AddArgument(internal_flag.c_str()); | |
| 9232 | |
| 9233 // Build the pipe for communication with the child. | |
| 9234 zx_status_t status; | |
| 9235 zx_handle_t child_pipe_handle; | |
| 9236 int child_pipe_fd; | |
| 9237 status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle); | |
| 9238 GTEST_DEATH_TEST_CHECK_(status == ZX_OK); | |
| 9239 set_read_fd(child_pipe_fd); | |
| 9240 | |
| 9241 // Set the pipe handle for the child. | |
| 9242 fdio_spawn_action_t spawn_actions[2] = {}; | |
| 9243 fdio_spawn_action_t* add_handle_action = &spawn_actions[0]; | |
| 9244 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE; | |
| 9245 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd); | |
| 9246 add_handle_action->h.handle = child_pipe_handle; | |
| 9247 | |
| 9248 // Create a socket pair will be used to receive the child process' stderr. | |
| 9249 zx::socket stderr_producer_socket; | |
| 9250 status = | |
| 9251 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); | |
| 9252 GTEST_DEATH_TEST_CHECK_(status >= 0); | |
| 9253 int stderr_producer_fd = -1; | |
| 9254 status = | |
| 9255 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd); | |
| 9256 GTEST_DEATH_TEST_CHECK_(status >= 0); | |
| 9257 | |
| 9258 // Make the stderr socket nonblocking. | |
| 9259 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0); | |
| 9260 | |
| 9261 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1]; | |
| 9262 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD; | |
| 9263 add_stderr_action->fd.local_fd = stderr_producer_fd; | |
| 9264 add_stderr_action->fd.target_fd = STDERR_FILENO; | |
| 9265 | |
| 9266 // Create a child job. | |
| 9267 zx_handle_t child_job = ZX_HANDLE_INVALID; | |
| 9268 status = zx_job_create(zx_job_default(), 0, & child_job); | |
| 9269 GTEST_DEATH_TEST_CHECK_(status == ZX_OK); | |
| 9270 zx_policy_basic_t policy; | |
| 9271 policy.condition = ZX_POL_NEW_ANY; | |
| 9272 policy.policy = ZX_POL_ACTION_ALLOW; | |
| 9273 status = zx_job_set_policy( | |
| 9274 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); | |
| 9275 GTEST_DEATH_TEST_CHECK_(status == ZX_OK); | |
| 9276 | |
| 9277 // Create an exception channel attached to the |child_job|, to allow | |
| 9278 // us to suppress the system default exception handler from firing. | |
| 9279 status = | |
| 9280 zx_task_create_exception_channel( | |
| 9281 child_job, 0, exception_channel_.reset_and_get_address()); | |
| 9282 GTEST_DEATH_TEST_CHECK_(status == ZX_OK); | |
| 9283 | |
| 9284 // Spawn the child process. | |
| 9285 status = fdio_spawn_etc( | |
| 9286 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, | |
| 9287 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); | |
| 9288 GTEST_DEATH_TEST_CHECK_(status == ZX_OK); | |
| 9289 | |
| 9290 set_spawned(true); | |
| 9291 return OVERSEE_TEST; | |
| 9292 } | |
| 9293 | |
| 9294 std::string FuchsiaDeathTest::GetErrorLogs() { | |
| 9295 return captured_stderr_; | |
| 9296 } | |
| 9297 | |
| 9298 #else // We are neither on Windows, nor on Fuchsia. | |
| 9299 | |
| 9300 // ForkingDeathTest provides implementations for most of the abstract | |
| 9301 // methods of the DeathTest interface. Only the AssumeRole method is | |
| 9302 // left undefined. | |
| 9303 class ForkingDeathTest : public DeathTestImpl { | |
| 9304 public: | |
| 9305 ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher); | |
| 9306 | |
| 9307 // All of these virtual functions are inherited from DeathTest. | |
| 9308 int Wait() override; | |
| 9309 | |
| 9310 protected: | |
| 9311 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } | |
| 9312 | |
| 9313 private: | |
| 9314 // PID of child process during death test; 0 in the child process itself. | |
| 9315 pid_t child_pid_; | |
| 9316 }; | |
| 9317 | |
| 9318 // Constructs a ForkingDeathTest. | |
| 9319 ForkingDeathTest::ForkingDeathTest(const char* a_statement, | |
| 9320 Matcher<const std::string&> matcher) | |
| 9321 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {} | |
| 9322 | |
| 9323 // Waits for the child in a death test to exit, returning its exit | |
| 9324 // status, or 0 if no child process exists. As a side effect, sets the | |
| 9325 // outcome data member. | |
| 9326 int ForkingDeathTest::Wait() { | |
| 9327 if (!spawned()) | |
| 9328 return 0; | |
| 9329 | |
| 9330 ReadAndInterpretStatusByte(); | |
| 9331 | |
| 9332 int status_value; | |
| 9333 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); | |
| 9334 set_status(status_value); | |
| 9335 return status_value; | |
| 9336 } | |
| 9337 | |
| 9338 // A concrete death test class that forks, then immediately runs the test | |
| 9339 // in the child process. | |
| 9340 class NoExecDeathTest : public ForkingDeathTest { | |
| 9341 public: | |
| 9342 NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher) | |
| 9343 : ForkingDeathTest(a_statement, std::move(matcher)) {} | |
| 9344 TestRole AssumeRole() override; | |
| 9345 }; | |
| 9346 | |
| 9347 // The AssumeRole process for a fork-and-run death test. It implements a | |
| 9348 // straightforward fork, with a simple pipe to transmit the status byte. | |
| 9349 DeathTest::TestRole NoExecDeathTest::AssumeRole() { | |
| 9350 const size_t thread_count = GetThreadCount(); | |
| 9351 if (thread_count != 1) { | |
| 9352 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); | |
| 9353 } | |
| 9354 | |
| 9355 int pipe_fd[2]; | |
| 9356 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); | |
| 9357 | |
| 9358 DeathTest::set_last_death_test_message(""); | |
| 9359 CaptureStderr(); | |
| 9360 // When we fork the process below, the log file buffers are copied, but the | |
| 9361 // file descriptors are shared. We flush all log files here so that closing | |
| 9362 // the file descriptors in the child process doesn't throw off the | |
| 9363 // synchronization between descriptors and buffers in the parent process. | |
| 9364 // This is as close to the fork as possible to avoid a race condition in case | |
| 9365 // there are multiple threads running before the death test, and another | |
| 9366 // thread writes to the log file. | |
| 9367 FlushInfoLog(); | |
| 9368 | |
| 9369 const pid_t child_pid = fork(); | |
| 9370 GTEST_DEATH_TEST_CHECK_(child_pid != -1); | |
| 9371 set_child_pid(child_pid); | |
| 9372 if (child_pid == 0) { | |
| 9373 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); | |
| 9374 set_write_fd(pipe_fd[1]); | |
| 9375 // Redirects all logging to stderr in the child process to prevent | |
| 9376 // concurrent writes to the log files. We capture stderr in the parent | |
| 9377 // process and append the child process' output to a log. | |
| 9378 LogToStderr(); | |
| 9379 // Event forwarding to the listeners of event listener API mush be shut | |
| 9380 // down in death test subprocesses. | |
| 9381 GetUnitTestImpl()->listeners()->SuppressEventForwarding(); | |
| 9382 g_in_fast_death_test_child = true; | |
| 9383 return EXECUTE_TEST; | |
| 9384 } else { | |
| 9385 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); | |
| 9386 set_read_fd(pipe_fd[0]); | |
| 9387 set_spawned(true); | |
| 9388 return OVERSEE_TEST; | |
| 9389 } | |
| 9390 } | |
| 9391 | |
| 9392 // A concrete death test class that forks and re-executes the main | |
| 9393 // program from the beginning, with command-line flags set that cause | |
| 9394 // only this specific death test to be run. | |
| 9395 class ExecDeathTest : public ForkingDeathTest { | |
| 9396 public: | |
| 9397 ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher, | |
| 9398 const char* file, int line) | |
| 9399 : ForkingDeathTest(a_statement, std::move(matcher)), | |
| 9400 file_(file), | |
| 9401 line_(line) {} | |
| 9402 TestRole AssumeRole() override; | |
| 9403 | |
| 9404 private: | |
| 9405 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { | |
| 9406 ::std::vector<std::string> args = GetInjectableArgvs(); | |
| 9407 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) | |
| 9408 ::std::vector<std::string> extra_args = | |
| 9409 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); | |
| 9410 args.insert(args.end(), extra_args.begin(), extra_args.end()); | |
| 9411 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) | |
| 9412 return args; | |
| 9413 } | |
| 9414 // The name of the file in which the death test is located. | |
| 9415 const char* const file_; | |
| 9416 // The line number on which the death test is located. | |
| 9417 const int line_; | |
| 9418 }; | |
| 9419 | |
| 9420 // Utility class for accumulating command-line arguments. | |
| 9421 class Arguments { | |
| 9422 public: | |
| 9423 Arguments() { args_.push_back(nullptr); } | |
| 9424 | |
| 9425 ~Arguments() { | |
| 9426 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); | |
| 9427 ++i) { | |
| 9428 free(*i); | |
| 9429 } | |
| 9430 } | |
| 9431 void AddArgument(const char* argument) { | |
| 9432 args_.insert(args_.end() - 1, posix::StrDup(argument)); | |
| 9433 } | |
| 9434 | |
| 9435 template <typename Str> | |
| 9436 void AddArguments(const ::std::vector<Str>& arguments) { | |
| 9437 for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); | |
| 9438 i != arguments.end(); | |
| 9439 ++i) { | |
| 9440 args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); | |
| 9441 } | |
| 9442 } | |
| 9443 char* const* Argv() { | |
| 9444 return &args_[0]; | |
| 9445 } | |
| 9446 | |
| 9447 private: | |
| 9448 std::vector<char*> args_; | |
| 9449 }; | |
| 9450 | |
| 9451 // A struct that encompasses the arguments to the child process of a | |
| 9452 // threadsafe-style death test process. | |
| 9453 struct ExecDeathTestArgs { | |
| 9454 char* const* argv; // Command-line arguments for the child's call to exec | |
| 9455 int close_fd; // File descriptor to close; the read end of a pipe | |
| 9456 }; | |
| 9457 | |
| 9458 # if GTEST_OS_QNX | |
| 9459 extern "C" char** environ; | |
| 9460 # else // GTEST_OS_QNX | |
| 9461 // The main function for a threadsafe-style death test child process. | |
| 9462 // This function is called in a clone()-ed process and thus must avoid | |
| 9463 // any potentially unsafe operations like malloc or libc functions. | |
| 9464 static int ExecDeathTestChildMain(void* child_arg) { | |
| 9465 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); | |
| 9466 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); | |
| 9467 | |
| 9468 // We need to execute the test program in the same environment where | |
| 9469 // it was originally invoked. Therefore we change to the original | |
| 9470 // working directory first. | |
| 9471 const char* const original_dir = | |
| 9472 UnitTest::GetInstance()->original_working_dir(); | |
| 9473 // We can safely call chdir() as it's a direct system call. | |
| 9474 if (chdir(original_dir) != 0) { | |
| 9475 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + | |
| 9476 GetLastErrnoDescription()); | |
| 9477 return EXIT_FAILURE; | |
| 9478 } | |
| 9479 | |
| 9480 // We can safely call execv() as it's almost a direct system call. We | |
| 9481 // cannot use execvp() as it's a libc function and thus potentially | |
| 9482 // unsafe. Since execv() doesn't search the PATH, the user must | |
| 9483 // invoke the test program via a valid path that contains at least | |
| 9484 // one path separator. | |
| 9485 execv(args->argv[0], args->argv); | |
| 9486 DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " + | |
| 9487 original_dir + " failed: " + | |
| 9488 GetLastErrnoDescription()); | |
| 9489 return EXIT_FAILURE; | |
| 9490 } | |
| 9491 # endif // GTEST_OS_QNX | |
| 9492 | |
| 9493 # if GTEST_HAS_CLONE | |
| 9494 // Two utility routines that together determine the direction the stack | |
| 9495 // grows. | |
| 9496 // This could be accomplished more elegantly by a single recursive | |
| 9497 // function, but we want to guard against the unlikely possibility of | |
| 9498 // a smart compiler optimizing the recursion away. | |
| 9499 // | |
| 9500 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining | |
| 9501 // StackLowerThanAddress into StackGrowsDown, which then doesn't give | |
| 9502 // correct answer. | |
| 9503 static void StackLowerThanAddress(const void* ptr, | |
| 9504 bool* result) GTEST_NO_INLINE_; | |
| 9505 // Make sure sanitizers do not tamper with the stack here. | |
| 9506 // Ideally, we want to use `__builtin_frame_address` instead of a local variable | |
| 9507 // address with sanitizer disabled, but it does not work when the | |
| 9508 // compiler optimizes the stack frame out, which happens on PowerPC targets. | |
| 9509 // HWAddressSanitizer add a random tag to the MSB of the local variable address, | |
| 9510 // making comparison result unpredictable. | |
| 9511 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ | |
| 9512 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ | |
| 9513 static void StackLowerThanAddress(const void* ptr, bool* result) { | |
| 9514 int dummy = 0; | |
| 9515 *result = std::less<const void*>()(&dummy, ptr); | |
| 9516 } | |
| 9517 | |
| 9518 // Make sure AddressSanitizer does not tamper with the stack here. | |
| 9519 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ | |
| 9520 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ | |
| 9521 static bool StackGrowsDown() { | |
| 9522 int dummy = 0; | |
| 9523 bool result; | |
| 9524 StackLowerThanAddress(&dummy, &result); | |
| 9525 return result; | |
| 9526 } | |
| 9527 # endif // GTEST_HAS_CLONE | |
| 9528 | |
| 9529 // Spawns a child process with the same executable as the current process in | |
| 9530 // a thread-safe manner and instructs it to run the death test. The | |
| 9531 // implementation uses fork(2) + exec. On systems where clone(2) is | |
| 9532 // available, it is used instead, being slightly more thread-safe. On QNX, | |
| 9533 // fork supports only single-threaded environments, so this function uses | |
| 9534 // spawn(2) there instead. The function dies with an error message if | |
| 9535 // anything goes wrong. | |
| 9536 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { | |
| 9537 ExecDeathTestArgs args = { argv, close_fd }; | |
| 9538 pid_t child_pid = -1; | |
| 9539 | |
| 9540 # if GTEST_OS_QNX | |
| 9541 // Obtains the current directory and sets it to be closed in the child | |
| 9542 // process. | |
| 9543 const int cwd_fd = open(".", O_RDONLY); | |
| 9544 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); | |
| 9545 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); | |
| 9546 // We need to execute the test program in the same environment where | |
| 9547 // it was originally invoked. Therefore we change to the original | |
| 9548 // working directory first. | |
| 9549 const char* const original_dir = | |
| 9550 UnitTest::GetInstance()->original_working_dir(); | |
| 9551 // We can safely call chdir() as it's a direct system call. | |
| 9552 if (chdir(original_dir) != 0) { | |
| 9553 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + | |
| 9554 GetLastErrnoDescription()); | |
| 9555 return EXIT_FAILURE; | |
| 9556 } | |
| 9557 | |
| 9558 int fd_flags; | |
| 9559 // Set close_fd to be closed after spawn. | |
| 9560 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); | |
| 9561 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, | |
| 9562 fd_flags | FD_CLOEXEC)); | |
| 9563 struct inheritance inherit = {0}; | |
| 9564 // spawn is a system call. | |
| 9565 child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ); | |
| 9566 // Restores the current working directory. | |
| 9567 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); | |
| 9568 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); | |
| 9569 | |
| 9570 # else // GTEST_OS_QNX | |
| 9571 # if GTEST_OS_LINUX | |
| 9572 // When a SIGPROF signal is received while fork() or clone() are executing, | |
| 9573 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable | |
| 9574 // it after the call to fork()/clone() is complete. | |
| 9575 struct sigaction saved_sigprof_action; | |
| 9576 struct sigaction ignore_sigprof_action; | |
| 9577 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); | |
| 9578 sigemptyset(&ignore_sigprof_action.sa_mask); | |
| 9579 ignore_sigprof_action.sa_handler = SIG_IGN; | |
| 9580 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( | |
| 9581 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); | |
| 9582 # endif // GTEST_OS_LINUX | |
| 9583 | |
| 9584 # if GTEST_HAS_CLONE | |
| 9585 const bool use_fork = GTEST_FLAG(death_test_use_fork); | |
| 9586 | |
| 9587 if (!use_fork) { | |
| 9588 static const bool stack_grows_down = StackGrowsDown(); | |
| 9589 const auto stack_size = static_cast<size_t>(getpagesize() * 2); | |
| 9590 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. | |
| 9591 void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE, | |
| 9592 MAP_ANON | MAP_PRIVATE, -1, 0); | |
| 9593 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); | |
| 9594 | |
| 9595 // Maximum stack alignment in bytes: For a downward-growing stack, this | |
| 9596 // amount is subtracted from size of the stack space to get an address | |
| 9597 // that is within the stack space and is aligned on all systems we care | |
| 9598 // about. As far as I know there is no ABI with stack alignment greater | |
| 9599 // than 64. We assume stack and stack_size already have alignment of | |
| 9600 // kMaxStackAlignment. | |
| 9601 const size_t kMaxStackAlignment = 64; | |
| 9602 void* const stack_top = | |
| 9603 static_cast<char*>(stack) + | |
| 9604 (stack_grows_down ? stack_size - kMaxStackAlignment : 0); | |
| 9605 GTEST_DEATH_TEST_CHECK_( | |
| 9606 static_cast<size_t>(stack_size) > kMaxStackAlignment && | |
| 9607 reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0); | |
| 9608 | |
| 9609 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); | |
| 9610 | |
| 9611 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); | |
| 9612 } | |
| 9613 # else | |
| 9614 const bool use_fork = true; | |
| 9615 # endif // GTEST_HAS_CLONE | |
| 9616 | |
| 9617 if (use_fork && (child_pid = fork()) == 0) { | |
| 9618 ExecDeathTestChildMain(&args); | |
| 9619 _exit(0); | |
| 9620 } | |
| 9621 # endif // GTEST_OS_QNX | |
| 9622 # if GTEST_OS_LINUX | |
| 9623 GTEST_DEATH_TEST_CHECK_SYSCALL_( | |
| 9624 sigaction(SIGPROF, &saved_sigprof_action, nullptr)); | |
| 9625 # endif // GTEST_OS_LINUX | |
| 9626 | |
| 9627 GTEST_DEATH_TEST_CHECK_(child_pid != -1); | |
| 9628 return child_pid; | |
| 9629 } | |
| 9630 | |
| 9631 // The AssumeRole process for a fork-and-exec death test. It re-executes the | |
| 9632 // main program from the beginning, setting the --gtest_filter | |
| 9633 // and --gtest_internal_run_death_test flags to cause only the current | |
| 9634 // death test to be re-run. | |
| 9635 DeathTest::TestRole ExecDeathTest::AssumeRole() { | |
| 9636 const UnitTestImpl* const impl = GetUnitTestImpl(); | |
| 9637 const InternalRunDeathTestFlag* const flag = | |
| 9638 impl->internal_run_death_test_flag(); | |
| 9639 const TestInfo* const info = impl->current_test_info(); | |
| 9640 const int death_test_index = info->result()->death_test_count(); | |
| 9641 | |
| 9642 if (flag != nullptr) { | |
| 9643 set_write_fd(flag->write_fd()); | |
| 9644 return EXECUTE_TEST; | |
| 9645 } | |
| 9646 | |
| 9647 int pipe_fd[2]; | |
| 9648 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); | |
| 9649 // Clear the close-on-exec flag on the write end of the pipe, lest | |
| 9650 // it be closed when the child process does an exec: | |
| 9651 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); | |
| 9652 | |
| 9653 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + | |
| 9654 kFilterFlag + "=" + info->test_suite_name() + | |
| 9655 "." + info->name(); | |
| 9656 const std::string internal_flag = | |
| 9657 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" | |
| 9658 + file_ + "|" + StreamableToString(line_) + "|" | |
| 9659 + StreamableToString(death_test_index) + "|" | |
| 9660 + StreamableToString(pipe_fd[1]); | |
| 9661 Arguments args; | |
| 9662 args.AddArguments(GetArgvsForDeathTestChildProcess()); | |
| 9663 args.AddArgument(filter_flag.c_str()); | |
| 9664 args.AddArgument(internal_flag.c_str()); | |
| 9665 | |
| 9666 DeathTest::set_last_death_test_message(""); | |
| 9667 | |
| 9668 CaptureStderr(); | |
| 9669 // See the comment in NoExecDeathTest::AssumeRole for why the next line | |
| 9670 // is necessary. | |
| 9671 FlushInfoLog(); | |
| 9672 | |
| 9673 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); | |
| 9674 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); | |
| 9675 set_child_pid(child_pid); | |
| 9676 set_read_fd(pipe_fd[0]); | |
| 9677 set_spawned(true); | |
| 9678 return OVERSEE_TEST; | |
| 9679 } | |
| 9680 | |
| 9681 # endif // !GTEST_OS_WINDOWS | |
| 9682 | |
| 9683 // Creates a concrete DeathTest-derived class that depends on the | |
| 9684 // --gtest_death_test_style flag, and sets the pointer pointed to | |
| 9685 // by the "test" argument to its address. If the test should be | |
| 9686 // skipped, sets that pointer to NULL. Returns true, unless the | |
| 9687 // flag is set to an invalid value. | |
| 9688 bool DefaultDeathTestFactory::Create(const char* statement, | |
| 9689 Matcher<const std::string&> matcher, | |
| 9690 const char* file, int line, | |
| 9691 DeathTest** test) { | |
| 9692 UnitTestImpl* const impl = GetUnitTestImpl(); | |
| 9693 const InternalRunDeathTestFlag* const flag = | |
| 9694 impl->internal_run_death_test_flag(); | |
| 9695 const int death_test_index = impl->current_test_info() | |
| 9696 ->increment_death_test_count(); | |
| 9697 | |
| 9698 if (flag != nullptr) { | |
| 9699 if (death_test_index > flag->index()) { | |
| 9700 DeathTest::set_last_death_test_message( | |
| 9701 "Death test count (" + StreamableToString(death_test_index) | |
| 9702 + ") somehow exceeded expected maximum (" | |
| 9703 + StreamableToString(flag->index()) + ")"); | |
| 9704 return false; | |
| 9705 } | |
| 9706 | |
| 9707 if (!(flag->file() == file && flag->line() == line && | |
| 9708 flag->index() == death_test_index)) { | |
| 9709 *test = nullptr; | |
| 9710 return true; | |
| 9711 } | |
| 9712 } | |
| 9713 | |
| 9714 # if GTEST_OS_WINDOWS | |
| 9715 | |
| 9716 if (GTEST_FLAG(death_test_style) == "threadsafe" || | |
| 9717 GTEST_FLAG(death_test_style) == "fast") { | |
| 9718 *test = new WindowsDeathTest(statement, std::move(matcher), file, line); | |
| 9719 } | |
| 9720 | |
| 9721 # elif GTEST_OS_FUCHSIA | |
| 9722 | |
| 9723 if (GTEST_FLAG(death_test_style) == "threadsafe" || | |
| 9724 GTEST_FLAG(death_test_style) == "fast") { | |
| 9725 *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); | |
| 9726 } | |
| 9727 | |
| 9728 # else | |
| 9729 | |
| 9730 if (GTEST_FLAG(death_test_style) == "threadsafe") { | |
| 9731 *test = new ExecDeathTest(statement, std::move(matcher), file, line); | |
| 9732 } else if (GTEST_FLAG(death_test_style) == "fast") { | |
| 9733 *test = new NoExecDeathTest(statement, std::move(matcher)); | |
| 9734 } | |
| 9735 | |
| 9736 # endif // GTEST_OS_WINDOWS | |
| 9737 | |
| 9738 else { // NOLINT - this is more readable than unbalanced brackets inside #if. | |
| 9739 DeathTest::set_last_death_test_message( | |
| 9740 "Unknown death test style \"" + GTEST_FLAG(death_test_style) | |
| 9741 + "\" encountered"); | |
| 9742 return false; | |
| 9743 } | |
| 9744 | |
| 9745 return true; | |
| 9746 } | |
| 9747 | |
| 9748 # if GTEST_OS_WINDOWS | |
| 9749 // Recreates the pipe and event handles from the provided parameters, | |
| 9750 // signals the event, and returns a file descriptor wrapped around the pipe | |
| 9751 // handle. This function is called in the child process only. | |
| 9752 static int GetStatusFileDescriptor(unsigned int parent_process_id, | |
| 9753 size_t write_handle_as_size_t, | |
| 9754 size_t event_handle_as_size_t) { | |
| 9755 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, | |
| 9756 FALSE, // Non-inheritable. | |
| 9757 parent_process_id)); | |
| 9758 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { | |
| 9759 DeathTestAbort("Unable to open parent process " + | |
| 9760 StreamableToString(parent_process_id)); | |
| 9761 } | |
| 9762 | |
| 9763 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); | |
| 9764 | |
| 9765 const HANDLE write_handle = | |
| 9766 reinterpret_cast<HANDLE>(write_handle_as_size_t); | |
| 9767 HANDLE dup_write_handle; | |
| 9768 | |
| 9769 // The newly initialized handle is accessible only in the parent | |
| 9770 // process. To obtain one accessible within the child, we need to use | |
| 9771 // DuplicateHandle. | |
| 9772 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, | |
| 9773 ::GetCurrentProcess(), &dup_write_handle, | |
| 9774 0x0, // Requested privileges ignored since | |
| 9775 // DUPLICATE_SAME_ACCESS is used. | |
| 9776 FALSE, // Request non-inheritable handler. | |
| 9777 DUPLICATE_SAME_ACCESS)) { | |
| 9778 DeathTestAbort("Unable to duplicate the pipe handle " + | |
| 9779 StreamableToString(write_handle_as_size_t) + | |
| 9780 " from the parent process " + | |
| 9781 StreamableToString(parent_process_id)); | |
| 9782 } | |
| 9783 | |
| 9784 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); | |
| 9785 HANDLE dup_event_handle; | |
| 9786 | |
| 9787 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, | |
| 9788 ::GetCurrentProcess(), &dup_event_handle, | |
| 9789 0x0, | |
| 9790 FALSE, | |
| 9791 DUPLICATE_SAME_ACCESS)) { | |
| 9792 DeathTestAbort("Unable to duplicate the event handle " + | |
| 9793 StreamableToString(event_handle_as_size_t) + | |
| 9794 " from the parent process " + | |
| 9795 StreamableToString(parent_process_id)); | |
| 9796 } | |
| 9797 | |
| 9798 const int write_fd = | |
| 9799 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); | |
| 9800 if (write_fd == -1) { | |
| 9801 DeathTestAbort("Unable to convert pipe handle " + | |
| 9802 StreamableToString(write_handle_as_size_t) + | |
| 9803 " to a file descriptor"); | |
| 9804 } | |
| 9805 | |
| 9806 // Signals the parent that the write end of the pipe has been acquired | |
| 9807 // so the parent can release its own write end. | |
| 9808 ::SetEvent(dup_event_handle); | |
| 9809 | |
| 9810 return write_fd; | |
| 9811 } | |
| 9812 # endif // GTEST_OS_WINDOWS | |
| 9813 | |
| 9814 // Returns a newly created InternalRunDeathTestFlag object with fields | |
| 9815 // initialized from the GTEST_FLAG(internal_run_death_test) flag if | |
| 9816 // the flag is specified; otherwise returns NULL. | |
| 9817 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { | |
| 9818 if (GTEST_FLAG(internal_run_death_test) == "") return nullptr; | |
| 9819 | |
| 9820 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we | |
| 9821 // can use it here. | |
| 9822 int line = -1; | |
| 9823 int index = -1; | |
| 9824 ::std::vector< ::std::string> fields; | |
| 9825 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); | |
| 9826 int write_fd = -1; | |
| 9827 | |
| 9828 # if GTEST_OS_WINDOWS | |
| 9829 | |
| 9830 unsigned int parent_process_id = 0; | |
| 9831 size_t write_handle_as_size_t = 0; | |
| 9832 size_t event_handle_as_size_t = 0; | |
| 9833 | |
| 9834 if (fields.size() != 6 | |
| 9835 || !ParseNaturalNumber(fields[1], &line) | |
| 9836 || !ParseNaturalNumber(fields[2], &index) | |
| 9837 || !ParseNaturalNumber(fields[3], &parent_process_id) | |
| 9838 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) | |
| 9839 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { | |
| 9840 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + | |
| 9841 GTEST_FLAG(internal_run_death_test)); | |
| 9842 } | |
| 9843 write_fd = GetStatusFileDescriptor(parent_process_id, | |
| 9844 write_handle_as_size_t, | |
| 9845 event_handle_as_size_t); | |
| 9846 | |
| 9847 # elif GTEST_OS_FUCHSIA | |
| 9848 | |
| 9849 if (fields.size() != 3 | |
| 9850 || !ParseNaturalNumber(fields[1], &line) | |
| 9851 || !ParseNaturalNumber(fields[2], &index)) { | |
| 9852 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " | |
| 9853 + GTEST_FLAG(internal_run_death_test)); | |
| 9854 } | |
| 9855 | |
| 9856 # else | |
| 9857 | |
| 9858 if (fields.size() != 4 | |
| 9859 || !ParseNaturalNumber(fields[1], &line) | |
| 9860 || !ParseNaturalNumber(fields[2], &index) | |
| 9861 || !ParseNaturalNumber(fields[3], &write_fd)) { | |
| 9862 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " | |
| 9863 + GTEST_FLAG(internal_run_death_test)); | |
| 9864 } | |
| 9865 | |
| 9866 # endif // GTEST_OS_WINDOWS | |
| 9867 | |
| 9868 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); | |
| 9869 } | |
| 9870 | |
| 9871 } // namespace internal | |
| 9872 | |
| 9873 #endif // GTEST_HAS_DEATH_TEST | |
| 9874 | |
| 9875 } // namespace testing | |
| 9876 // Copyright 2008, Google Inc. | |
| 9877 // All rights reserved. | |
| 9878 // | |
| 9879 // Redistribution and use in source and binary forms, with or without | |
| 9880 // modification, are permitted provided that the following conditions are | |
| 9881 // met: | |
| 9882 // | |
| 9883 // * Redistributions of source code must retain the above copyright | |
| 9884 // notice, this list of conditions and the following disclaimer. | |
| 9885 // * Redistributions in binary form must reproduce the above | |
| 9886 // copyright notice, this list of conditions and the following disclaimer | |
| 9887 // in the documentation and/or other materials provided with the | |
| 9888 // distribution. | |
| 9889 // * Neither the name of Google Inc. nor the names of its | |
| 9890 // contributors may be used to endorse or promote products derived from | |
| 9891 // this software without specific prior written permission. | |
| 9892 // | |
| 9893 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 9894 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 9895 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 9896 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 9897 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 9898 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 9899 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 9900 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 9901 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 9902 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 9903 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 9904 | |
| 9905 | |
| 9906 #include <stdlib.h> | |
| 9907 | |
| 9908 #if GTEST_OS_WINDOWS_MOBILE | |
| 9909 # include <windows.h> | |
| 9910 #elif GTEST_OS_WINDOWS | |
| 9911 # include <direct.h> | |
| 9912 # include <io.h> | |
| 9913 #else | |
| 9914 # include <limits.h> | |
| 9915 # include <climits> // Some Linux distributions define PATH_MAX here. | |
| 9916 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 9917 | |
| 9918 | |
| 9919 #if GTEST_OS_WINDOWS | |
| 9920 # define GTEST_PATH_MAX_ _MAX_PATH | |
| 9921 #elif defined(PATH_MAX) | |
| 9922 # define GTEST_PATH_MAX_ PATH_MAX | |
| 9923 #elif defined(_XOPEN_PATH_MAX) | |
| 9924 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX | |
| 9925 #else | |
| 9926 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX | |
| 9927 #endif // GTEST_OS_WINDOWS | |
| 9928 | |
| 9929 namespace testing { | |
| 9930 namespace internal { | |
| 9931 | |
| 9932 #if GTEST_OS_WINDOWS | |
| 9933 // On Windows, '\\' is the standard path separator, but many tools and the | |
| 9934 // Windows API also accept '/' as an alternate path separator. Unless otherwise | |
| 9935 // noted, a file path can contain either kind of path separators, or a mixture | |
| 9936 // of them. | |
| 9937 const char kPathSeparator = '\\'; | |
| 9938 const char kAlternatePathSeparator = '/'; | |
| 9939 const char kAlternatePathSeparatorString[] = "/"; | |
| 9940 # if GTEST_OS_WINDOWS_MOBILE | |
| 9941 // Windows CE doesn't have a current directory. You should not use | |
| 9942 // the current directory in tests on Windows CE, but this at least | |
| 9943 // provides a reasonable fallback. | |
| 9944 const char kCurrentDirectoryString[] = "\\"; | |
| 9945 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES | |
| 9946 const DWORD kInvalidFileAttributes = 0xffffffff; | |
| 9947 # else | |
| 9948 const char kCurrentDirectoryString[] = ".\\"; | |
| 9949 # endif // GTEST_OS_WINDOWS_MOBILE | |
| 9950 #else | |
| 9951 const char kPathSeparator = '/'; | |
| 9952 const char kCurrentDirectoryString[] = "./"; | |
| 9953 #endif // GTEST_OS_WINDOWS | |
| 9954 | |
| 9955 // Returns whether the given character is a valid path separator. | |
| 9956 static bool IsPathSeparator(char c) { | |
| 9957 #if GTEST_HAS_ALT_PATH_SEP_ | |
| 9958 return (c == kPathSeparator) || (c == kAlternatePathSeparator); | |
| 9959 #else | |
| 9960 return c == kPathSeparator; | |
| 9961 #endif | |
| 9962 } | |
| 9963 | |
| 9964 // Returns the current working directory, or "" if unsuccessful. | |
| 9965 FilePath FilePath::GetCurrentDir() { | |
| 9966 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ | |
| 9967 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \ | |
| 9968 GTEST_OS_XTENSA | |
| 9969 // These platforms do not have a current directory, so we just return | |
| 9970 // something reasonable. | |
| 9971 return FilePath(kCurrentDirectoryString); | |
| 9972 #elif GTEST_OS_WINDOWS | |
| 9973 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; | |
| 9974 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); | |
| 9975 #else | |
| 9976 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; | |
| 9977 char* result = getcwd(cwd, sizeof(cwd)); | |
| 9978 # if GTEST_OS_NACL | |
| 9979 // getcwd will likely fail in NaCl due to the sandbox, so return something | |
| 9980 // reasonable. The user may have provided a shim implementation for getcwd, | |
| 9981 // however, so fallback only when failure is detected. | |
| 9982 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); | |
| 9983 # endif // GTEST_OS_NACL | |
| 9984 return FilePath(result == nullptr ? "" : cwd); | |
| 9985 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 9986 } | |
| 9987 | |
| 9988 // Returns a copy of the FilePath with the case-insensitive extension removed. | |
| 9989 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns | |
| 9990 // FilePath("dir/file"). If a case-insensitive extension is not | |
| 9991 // found, returns a copy of the original FilePath. | |
| 9992 FilePath FilePath::RemoveExtension(const char* extension) const { | |
| 9993 const std::string dot_extension = std::string(".") + extension; | |
| 9994 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { | |
| 9995 return FilePath(pathname_.substr( | |
| 9996 0, pathname_.length() - dot_extension.length())); | |
| 9997 } | |
| 9998 return *this; | |
| 9999 } | |
| 10000 | |
| 10001 // Returns a pointer to the last occurrence of a valid path separator in | |
| 10002 // the FilePath. On Windows, for example, both '/' and '\' are valid path | |
| 10003 // separators. Returns NULL if no path separator was found. | |
| 10004 const char* FilePath::FindLastPathSeparator() const { | |
| 10005 const char* const last_sep = strrchr(c_str(), kPathSeparator); | |
| 10006 #if GTEST_HAS_ALT_PATH_SEP_ | |
| 10007 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); | |
| 10008 // Comparing two pointers of which only one is NULL is undefined. | |
| 10009 if (last_alt_sep != nullptr && | |
| 10010 (last_sep == nullptr || last_alt_sep > last_sep)) { | |
| 10011 return last_alt_sep; | |
| 10012 } | |
| 10013 #endif | |
| 10014 return last_sep; | |
| 10015 } | |
| 10016 | |
| 10017 // Returns a copy of the FilePath with the directory part removed. | |
| 10018 // Example: FilePath("path/to/file").RemoveDirectoryName() returns | |
| 10019 // FilePath("file"). If there is no directory part ("just_a_file"), it returns | |
| 10020 // the FilePath unmodified. If there is no file part ("just_a_dir/") it | |
| 10021 // returns an empty FilePath (""). | |
| 10022 // On Windows platform, '\' is the path separator, otherwise it is '/'. | |
| 10023 FilePath FilePath::RemoveDirectoryName() const { | |
| 10024 const char* const last_sep = FindLastPathSeparator(); | |
| 10025 return last_sep ? FilePath(last_sep + 1) : *this; | |
| 10026 } | |
| 10027 | |
| 10028 // RemoveFileName returns the directory path with the filename removed. | |
| 10029 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". | |
| 10030 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns | |
| 10031 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does | |
| 10032 // not have a file, like "just/a/dir/", it returns the FilePath unmodified. | |
| 10033 // On Windows platform, '\' is the path separator, otherwise it is '/'. | |
| 10034 FilePath FilePath::RemoveFileName() const { | |
| 10035 const char* const last_sep = FindLastPathSeparator(); | |
| 10036 std::string dir; | |
| 10037 if (last_sep) { | |
| 10038 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str())); | |
| 10039 } else { | |
| 10040 dir = kCurrentDirectoryString; | |
| 10041 } | |
| 10042 return FilePath(dir); | |
| 10043 } | |
| 10044 | |
| 10045 // Helper functions for naming files in a directory for xml output. | |
| 10046 | |
| 10047 // Given directory = "dir", base_name = "test", number = 0, | |
| 10048 // extension = "xml", returns "dir/test.xml". If number is greater | |
| 10049 // than zero (e.g., 12), returns "dir/test_12.xml". | |
| 10050 // On Windows platform, uses \ as the separator rather than /. | |
| 10051 FilePath FilePath::MakeFileName(const FilePath& directory, | |
| 10052 const FilePath& base_name, | |
| 10053 int number, | |
| 10054 const char* extension) { | |
| 10055 std::string file; | |
| 10056 if (number == 0) { | |
| 10057 file = base_name.string() + "." + extension; | |
| 10058 } else { | |
| 10059 file = base_name.string() + "_" + StreamableToString(number) | |
| 10060 + "." + extension; | |
| 10061 } | |
| 10062 return ConcatPaths(directory, FilePath(file)); | |
| 10063 } | |
| 10064 | |
| 10065 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". | |
| 10066 // On Windows, uses \ as the separator rather than /. | |
| 10067 FilePath FilePath::ConcatPaths(const FilePath& directory, | |
| 10068 const FilePath& relative_path) { | |
| 10069 if (directory.IsEmpty()) | |
| 10070 return relative_path; | |
| 10071 const FilePath dir(directory.RemoveTrailingPathSeparator()); | |
| 10072 return FilePath(dir.string() + kPathSeparator + relative_path.string()); | |
| 10073 } | |
| 10074 | |
| 10075 // Returns true if pathname describes something findable in the file-system, | |
| 10076 // either a file, directory, or whatever. | |
| 10077 bool FilePath::FileOrDirectoryExists() const { | |
| 10078 #if GTEST_OS_WINDOWS_MOBILE | |
| 10079 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); | |
| 10080 const DWORD attributes = GetFileAttributes(unicode); | |
| 10081 delete [] unicode; | |
| 10082 return attributes != kInvalidFileAttributes; | |
| 10083 #else | |
| 10084 posix::StatStruct file_stat; | |
| 10085 return posix::Stat(pathname_.c_str(), &file_stat) == 0; | |
| 10086 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 10087 } | |
| 10088 | |
| 10089 // Returns true if pathname describes a directory in the file-system | |
| 10090 // that exists. | |
| 10091 bool FilePath::DirectoryExists() const { | |
| 10092 bool result = false; | |
| 10093 #if GTEST_OS_WINDOWS | |
| 10094 // Don't strip off trailing separator if path is a root directory on | |
| 10095 // Windows (like "C:\\"). | |
| 10096 const FilePath& path(IsRootDirectory() ? *this : | |
| 10097 RemoveTrailingPathSeparator()); | |
| 10098 #else | |
| 10099 const FilePath& path(*this); | |
| 10100 #endif | |
| 10101 | |
| 10102 #if GTEST_OS_WINDOWS_MOBILE | |
| 10103 LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); | |
| 10104 const DWORD attributes = GetFileAttributes(unicode); | |
| 10105 delete [] unicode; | |
| 10106 if ((attributes != kInvalidFileAttributes) && | |
| 10107 (attributes & FILE_ATTRIBUTE_DIRECTORY)) { | |
| 10108 result = true; | |
| 10109 } | |
| 10110 #else | |
| 10111 posix::StatStruct file_stat; | |
| 10112 result = posix::Stat(path.c_str(), &file_stat) == 0 && | |
| 10113 posix::IsDir(file_stat); | |
| 10114 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 10115 | |
| 10116 return result; | |
| 10117 } | |
| 10118 | |
| 10119 // Returns true if pathname describes a root directory. (Windows has one | |
| 10120 // root directory per disk drive.) | |
| 10121 bool FilePath::IsRootDirectory() const { | |
| 10122 #if GTEST_OS_WINDOWS | |
| 10123 return pathname_.length() == 3 && IsAbsolutePath(); | |
| 10124 #else | |
| 10125 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); | |
| 10126 #endif | |
| 10127 } | |
| 10128 | |
| 10129 // Returns true if pathname describes an absolute path. | |
| 10130 bool FilePath::IsAbsolutePath() const { | |
| 10131 const char* const name = pathname_.c_str(); | |
| 10132 #if GTEST_OS_WINDOWS | |
| 10133 return pathname_.length() >= 3 && | |
| 10134 ((name[0] >= 'a' && name[0] <= 'z') || | |
| 10135 (name[0] >= 'A' && name[0] <= 'Z')) && | |
| 10136 name[1] == ':' && | |
| 10137 IsPathSeparator(name[2]); | |
| 10138 #else | |
| 10139 return IsPathSeparator(name[0]); | |
| 10140 #endif | |
| 10141 } | |
| 10142 | |
| 10143 // Returns a pathname for a file that does not currently exist. The pathname | |
| 10144 // will be directory/base_name.extension or | |
| 10145 // directory/base_name_<number>.extension if directory/base_name.extension | |
| 10146 // already exists. The number will be incremented until a pathname is found | |
| 10147 // that does not already exist. | |
| 10148 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. | |
| 10149 // There could be a race condition if two or more processes are calling this | |
| 10150 // function at the same time -- they could both pick the same filename. | |
| 10151 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, | |
| 10152 const FilePath& base_name, | |
| 10153 const char* extension) { | |
| 10154 FilePath full_pathname; | |
| 10155 int number = 0; | |
| 10156 do { | |
| 10157 full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); | |
| 10158 } while (full_pathname.FileOrDirectoryExists()); | |
| 10159 return full_pathname; | |
| 10160 } | |
| 10161 | |
| 10162 // Returns true if FilePath ends with a path separator, which indicates that | |
| 10163 // it is intended to represent a directory. Returns false otherwise. | |
| 10164 // This does NOT check that a directory (or file) actually exists. | |
| 10165 bool FilePath::IsDirectory() const { | |
| 10166 return !pathname_.empty() && | |
| 10167 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); | |
| 10168 } | |
| 10169 | |
| 10170 // Create directories so that path exists. Returns true if successful or if | |
| 10171 // the directories already exist; returns false if unable to create directories | |
| 10172 // for any reason. | |
| 10173 bool FilePath::CreateDirectoriesRecursively() const { | |
| 10174 if (!this->IsDirectory()) { | |
| 10175 return false; | |
| 10176 } | |
| 10177 | |
| 10178 if (pathname_.length() == 0 || this->DirectoryExists()) { | |
| 10179 return true; | |
| 10180 } | |
| 10181 | |
| 10182 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); | |
| 10183 return parent.CreateDirectoriesRecursively() && this->CreateFolder(); | |
| 10184 } | |
| 10185 | |
| 10186 // Create the directory so that path exists. Returns true if successful or | |
| 10187 // if the directory already exists; returns false if unable to create the | |
| 10188 // directory for any reason, including if the parent directory does not | |
| 10189 // exist. Not named "CreateDirectory" because that's a macro on Windows. | |
| 10190 bool FilePath::CreateFolder() const { | |
| 10191 #if GTEST_OS_WINDOWS_MOBILE | |
| 10192 FilePath removed_sep(this->RemoveTrailingPathSeparator()); | |
| 10193 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); | |
| 10194 int result = CreateDirectory(unicode, nullptr) ? 0 : -1; | |
| 10195 delete [] unicode; | |
| 10196 #elif GTEST_OS_WINDOWS | |
| 10197 int result = _mkdir(pathname_.c_str()); | |
| 10198 #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA | |
| 10199 // do nothing | |
| 10200 int result = 0; | |
| 10201 #else | |
| 10202 int result = mkdir(pathname_.c_str(), 0777); | |
| 10203 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 10204 | |
| 10205 if (result == -1) { | |
| 10206 return this->DirectoryExists(); // An error is OK if the directory exists. | |
| 10207 } | |
| 10208 return true; // No error. | |
| 10209 } | |
| 10210 | |
| 10211 // If input name has a trailing separator character, remove it and return the | |
| 10212 // name, otherwise return the name string unmodified. | |
| 10213 // On Windows platform, uses \ as the separator, other platforms use /. | |
| 10214 FilePath FilePath::RemoveTrailingPathSeparator() const { | |
| 10215 return IsDirectory() | |
| 10216 ? FilePath(pathname_.substr(0, pathname_.length() - 1)) | |
| 10217 : *this; | |
| 10218 } | |
| 10219 | |
| 10220 // Removes any redundant separators that might be in the pathname. | |
| 10221 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other | |
| 10222 // redundancies that might be in a pathname involving "." or "..". | |
| 10223 void FilePath::Normalize() { | |
| 10224 auto out = pathname_.begin(); | |
| 10225 | |
| 10226 for (const char character : pathname_) { | |
| 10227 if (!IsPathSeparator(character)) { | |
| 10228 *(out++) = character; | |
| 10229 } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) { | |
| 10230 *(out++) = kPathSeparator; | |
| 10231 } else { | |
| 10232 continue; | |
| 10233 } | |
| 10234 } | |
| 10235 | |
| 10236 pathname_.erase(out, pathname_.end()); | |
| 10237 } | |
| 10238 | |
| 10239 } // namespace internal | |
| 10240 } // namespace testing | |
| 10241 // Copyright 2007, Google Inc. | |
| 10242 // All rights reserved. | |
| 10243 // | |
| 10244 // Redistribution and use in source and binary forms, with or without | |
| 10245 // modification, are permitted provided that the following conditions are | |
| 10246 // met: | |
| 10247 // | |
| 10248 // * Redistributions of source code must retain the above copyright | |
| 10249 // notice, this list of conditions and the following disclaimer. | |
| 10250 // * Redistributions in binary form must reproduce the above | |
| 10251 // copyright notice, this list of conditions and the following disclaimer | |
| 10252 // in the documentation and/or other materials provided with the | |
| 10253 // distribution. | |
| 10254 // * Neither the name of Google Inc. nor the names of its | |
| 10255 // contributors may be used to endorse or promote products derived from | |
| 10256 // this software without specific prior written permission. | |
| 10257 // | |
| 10258 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 10259 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 10260 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 10261 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 10262 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 10263 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 10264 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 10265 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 10266 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 10267 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 10268 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 10269 | |
| 10270 // The Google C++ Testing and Mocking Framework (Google Test) | |
| 10271 // | |
| 10272 // This file implements just enough of the matcher interface to allow | |
| 10273 // EXPECT_DEATH and friends to accept a matcher argument. | |
| 10274 | |
| 10275 | |
| 10276 #include <string> | |
| 10277 | |
| 10278 namespace testing { | |
| 10279 | |
| 10280 // Constructs a matcher that matches a const std::string& whose value is | |
| 10281 // equal to s. | |
| 10282 Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); } | |
| 10283 | |
| 10284 // Constructs a matcher that matches a const std::string& whose value is | |
| 10285 // equal to s. | |
| 10286 Matcher<const std::string&>::Matcher(const char* s) { | |
| 10287 *this = Eq(std::string(s)); | |
| 10288 } | |
| 10289 | |
| 10290 // Constructs a matcher that matches a std::string whose value is equal to | |
| 10291 // s. | |
| 10292 Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); } | |
| 10293 | |
| 10294 // Constructs a matcher that matches a std::string whose value is equal to | |
| 10295 // s. | |
| 10296 Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); } | |
| 10297 | |
| 10298 #if GTEST_INTERNAL_HAS_STRING_VIEW | |
| 10299 // Constructs a matcher that matches a const StringView& whose value is | |
| 10300 // equal to s. | |
| 10301 Matcher<const internal::StringView&>::Matcher(const std::string& s) { | |
| 10302 *this = Eq(s); | |
| 10303 } | |
| 10304 | |
| 10305 // Constructs a matcher that matches a const StringView& whose value is | |
| 10306 // equal to s. | |
| 10307 Matcher<const internal::StringView&>::Matcher(const char* s) { | |
| 10308 *this = Eq(std::string(s)); | |
| 10309 } | |
| 10310 | |
| 10311 // Constructs a matcher that matches a const StringView& whose value is | |
| 10312 // equal to s. | |
| 10313 Matcher<const internal::StringView&>::Matcher(internal::StringView s) { | |
| 10314 *this = Eq(std::string(s)); | |
| 10315 } | |
| 10316 | |
| 10317 // Constructs a matcher that matches a StringView whose value is equal to | |
| 10318 // s. | |
| 10319 Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); } | |
| 10320 | |
| 10321 // Constructs a matcher that matches a StringView whose value is equal to | |
| 10322 // s. | |
| 10323 Matcher<internal::StringView>::Matcher(const char* s) { | |
| 10324 *this = Eq(std::string(s)); | |
| 10325 } | |
| 10326 | |
| 10327 // Constructs a matcher that matches a StringView whose value is equal to | |
| 10328 // s. | |
| 10329 Matcher<internal::StringView>::Matcher(internal::StringView s) { | |
| 10330 *this = Eq(std::string(s)); | |
| 10331 } | |
| 10332 #endif // GTEST_INTERNAL_HAS_STRING_VIEW | |
| 10333 | |
| 10334 } // namespace testing | |
| 10335 // Copyright 2008, Google Inc. | |
| 10336 // All rights reserved. | |
| 10337 // | |
| 10338 // Redistribution and use in source and binary forms, with or without | |
| 10339 // modification, are permitted provided that the following conditions are | |
| 10340 // met: | |
| 10341 // | |
| 10342 // * Redistributions of source code must retain the above copyright | |
| 10343 // notice, this list of conditions and the following disclaimer. | |
| 10344 // * Redistributions in binary form must reproduce the above | |
| 10345 // copyright notice, this list of conditions and the following disclaimer | |
| 10346 // in the documentation and/or other materials provided with the | |
| 10347 // distribution. | |
| 10348 // * Neither the name of Google Inc. nor the names of its | |
| 10349 // contributors may be used to endorse or promote products derived from | |
| 10350 // this software without specific prior written permission. | |
| 10351 // | |
| 10352 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 10353 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 10354 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 10355 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 10356 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 10357 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 10358 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 10359 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 10360 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 10361 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 10362 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 10363 | |
| 10364 | |
| 10365 | |
| 10366 #include <limits.h> | |
| 10367 #include <stdio.h> | |
| 10368 #include <stdlib.h> | |
| 10369 #include <string.h> | |
| 10370 #include <cstdint> | |
| 10371 #include <fstream> | |
| 10372 #include <memory> | |
| 10373 | |
| 10374 #if GTEST_OS_WINDOWS | |
| 10375 # include <windows.h> | |
| 10376 # include <io.h> | |
| 10377 # include <sys/stat.h> | |
| 10378 # include <map> // Used in ThreadLocal. | |
| 10379 # ifdef _MSC_VER | |
| 10380 # include <crtdbg.h> | |
| 10381 # endif // _MSC_VER | |
| 10382 #else | |
| 10383 # include <unistd.h> | |
| 10384 #endif // GTEST_OS_WINDOWS | |
| 10385 | |
| 10386 #if GTEST_OS_MAC | |
| 10387 # include <mach/mach_init.h> | |
| 10388 # include <mach/task.h> | |
| 10389 # include <mach/vm_map.h> | |
| 10390 #endif // GTEST_OS_MAC | |
| 10391 | |
| 10392 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ | |
| 10393 GTEST_OS_NETBSD || GTEST_OS_OPENBSD | |
| 10394 # include <sys/sysctl.h> | |
| 10395 # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD | |
| 10396 # include <sys/user.h> | |
| 10397 # endif | |
| 10398 #endif | |
| 10399 | |
| 10400 #if GTEST_OS_QNX | |
| 10401 # include <devctl.h> | |
| 10402 # include <fcntl.h> | |
| 10403 # include <sys/procfs.h> | |
| 10404 #endif // GTEST_OS_QNX | |
| 10405 | |
| 10406 #if GTEST_OS_AIX | |
| 10407 # include <procinfo.h> | |
| 10408 # include <sys/types.h> | |
| 10409 #endif // GTEST_OS_AIX | |
| 10410 | |
| 10411 #if GTEST_OS_FUCHSIA | |
| 10412 # include <zircon/process.h> | |
| 10413 # include <zircon/syscalls.h> | |
| 10414 #endif // GTEST_OS_FUCHSIA | |
| 10415 | |
| 10416 | |
| 10417 namespace testing { | |
| 10418 namespace internal { | |
| 10419 | |
| 10420 #if defined(_MSC_VER) || defined(__BORLANDC__) | |
| 10421 // MSVC and C++Builder do not provide a definition of STDERR_FILENO. | |
| 10422 const int kStdOutFileno = 1; | |
| 10423 const int kStdErrFileno = 2; | |
| 10424 #else | |
| 10425 const int kStdOutFileno = STDOUT_FILENO; | |
| 10426 const int kStdErrFileno = STDERR_FILENO; | |
| 10427 #endif // _MSC_VER | |
| 10428 | |
| 10429 #if GTEST_OS_LINUX | |
| 10430 | |
| 10431 namespace { | |
| 10432 template <typename T> | |
| 10433 T ReadProcFileField(const std::string& filename, int field) { | |
| 10434 std::string dummy; | |
| 10435 std::ifstream file(filename.c_str()); | |
| 10436 while (field-- > 0) { | |
| 10437 file >> dummy; | |
| 10438 } | |
| 10439 T output = 0; | |
| 10440 file >> output; | |
| 10441 return output; | |
| 10442 } | |
| 10443 } // namespace | |
| 10444 | |
| 10445 // Returns the number of active threads, or 0 when there is an error. | |
| 10446 size_t GetThreadCount() { | |
| 10447 const std::string filename = | |
| 10448 (Message() << "/proc/" << getpid() << "/stat").GetString(); | |
| 10449 return ReadProcFileField<size_t>(filename, 19); | |
| 10450 } | |
| 10451 | |
| 10452 #elif GTEST_OS_MAC | |
| 10453 | |
| 10454 size_t GetThreadCount() { | |
| 10455 const task_t task = mach_task_self(); | |
| 10456 mach_msg_type_number_t thread_count; | |
| 10457 thread_act_array_t thread_list; | |
| 10458 const kern_return_t status = task_threads(task, &thread_list, &thread_count); | |
| 10459 if (status == KERN_SUCCESS) { | |
| 10460 // task_threads allocates resources in thread_list and we need to free them | |
| 10461 // to avoid leaks. | |
| 10462 vm_deallocate(task, | |
| 10463 reinterpret_cast<vm_address_t>(thread_list), | |
| 10464 sizeof(thread_t) * thread_count); | |
| 10465 return static_cast<size_t>(thread_count); | |
| 10466 } else { | |
| 10467 return 0; | |
| 10468 } | |
| 10469 } | |
| 10470 | |
| 10471 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ | |
| 10472 GTEST_OS_NETBSD | |
| 10473 | |
| 10474 #if GTEST_OS_NETBSD | |
| 10475 #undef KERN_PROC | |
| 10476 #define KERN_PROC KERN_PROC2 | |
| 10477 #define kinfo_proc kinfo_proc2 | |
| 10478 #endif | |
| 10479 | |
| 10480 #if GTEST_OS_DRAGONFLY | |
| 10481 #define KP_NLWP(kp) (kp.kp_nthreads) | |
| 10482 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD | |
| 10483 #define KP_NLWP(kp) (kp.ki_numthreads) | |
| 10484 #elif GTEST_OS_NETBSD | |
| 10485 #define KP_NLWP(kp) (kp.p_nlwps) | |
| 10486 #endif | |
| 10487 | |
| 10488 // Returns the number of threads running in the process, or 0 to indicate that | |
| 10489 // we cannot detect it. | |
| 10490 size_t GetThreadCount() { | |
| 10491 int mib[] = { | |
| 10492 CTL_KERN, | |
| 10493 KERN_PROC, | |
| 10494 KERN_PROC_PID, | |
| 10495 getpid(), | |
| 10496 #if GTEST_OS_NETBSD | |
| 10497 sizeof(struct kinfo_proc), | |
| 10498 1, | |
| 10499 #endif | |
| 10500 }; | |
| 10501 u_int miblen = sizeof(mib) / sizeof(mib[0]); | |
| 10502 struct kinfo_proc info; | |
| 10503 size_t size = sizeof(info); | |
| 10504 if (sysctl(mib, miblen, &info, &size, NULL, 0)) { | |
| 10505 return 0; | |
| 10506 } | |
| 10507 return static_cast<size_t>(KP_NLWP(info)); | |
| 10508 } | |
| 10509 #elif GTEST_OS_OPENBSD | |
| 10510 | |
| 10511 // Returns the number of threads running in the process, or 0 to indicate that | |
| 10512 // we cannot detect it. | |
| 10513 size_t GetThreadCount() { | |
| 10514 int mib[] = { | |
| 10515 CTL_KERN, | |
| 10516 KERN_PROC, | |
| 10517 KERN_PROC_PID | KERN_PROC_SHOW_THREADS, | |
| 10518 getpid(), | |
| 10519 sizeof(struct kinfo_proc), | |
| 10520 0, | |
| 10521 }; | |
| 10522 u_int miblen = sizeof(mib) / sizeof(mib[0]); | |
| 10523 | |
| 10524 // get number of structs | |
| 10525 size_t size; | |
| 10526 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) { | |
| 10527 return 0; | |
| 10528 } | |
| 10529 | |
| 10530 mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4])); | |
| 10531 | |
| 10532 // populate array of structs | |
| 10533 struct kinfo_proc info[mib[5]]; | |
| 10534 if (sysctl(mib, miblen, &info, &size, NULL, 0)) { | |
| 10535 return 0; | |
| 10536 } | |
| 10537 | |
| 10538 // exclude empty members | |
| 10539 size_t nthreads = 0; | |
| 10540 for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) { | |
| 10541 if (info[i].p_tid != -1) | |
| 10542 nthreads++; | |
| 10543 } | |
| 10544 return nthreads; | |
| 10545 } | |
| 10546 | |
| 10547 #elif GTEST_OS_QNX | |
| 10548 | |
| 10549 // Returns the number of threads running in the process, or 0 to indicate that | |
| 10550 // we cannot detect it. | |
| 10551 size_t GetThreadCount() { | |
| 10552 const int fd = open("/proc/self/as", O_RDONLY); | |
| 10553 if (fd < 0) { | |
| 10554 return 0; | |
| 10555 } | |
| 10556 procfs_info process_info; | |
| 10557 const int status = | |
| 10558 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr); | |
| 10559 close(fd); | |
| 10560 if (status == EOK) { | |
| 10561 return static_cast<size_t>(process_info.num_threads); | |
| 10562 } else { | |
| 10563 return 0; | |
| 10564 } | |
| 10565 } | |
| 10566 | |
| 10567 #elif GTEST_OS_AIX | |
| 10568 | |
| 10569 size_t GetThreadCount() { | |
| 10570 struct procentry64 entry; | |
| 10571 pid_t pid = getpid(); | |
| 10572 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1); | |
| 10573 if (status == 1) { | |
| 10574 return entry.pi_thcount; | |
| 10575 } else { | |
| 10576 return 0; | |
| 10577 } | |
| 10578 } | |
| 10579 | |
| 10580 #elif GTEST_OS_FUCHSIA | |
| 10581 | |
| 10582 size_t GetThreadCount() { | |
| 10583 int dummy_buffer; | |
| 10584 size_t avail; | |
| 10585 zx_status_t status = zx_object_get_info( | |
| 10586 zx_process_self(), | |
| 10587 ZX_INFO_PROCESS_THREADS, | |
| 10588 &dummy_buffer, | |
| 10589 0, | |
| 10590 nullptr, | |
| 10591 &avail); | |
| 10592 if (status == ZX_OK) { | |
| 10593 return avail; | |
| 10594 } else { | |
| 10595 return 0; | |
| 10596 } | |
| 10597 } | |
| 10598 | |
| 10599 #else | |
| 10600 | |
| 10601 size_t GetThreadCount() { | |
| 10602 // There's no portable way to detect the number of threads, so we just | |
| 10603 // return 0 to indicate that we cannot detect it. | |
| 10604 return 0; | |
| 10605 } | |
| 10606 | |
| 10607 #endif // GTEST_OS_LINUX | |
| 10608 | |
| 10609 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS | |
| 10610 | |
| 10611 void SleepMilliseconds(int n) { | |
| 10612 ::Sleep(static_cast<DWORD>(n)); | |
| 10613 } | |
| 10614 | |
| 10615 AutoHandle::AutoHandle() | |
| 10616 : handle_(INVALID_HANDLE_VALUE) {} | |
| 10617 | |
| 10618 AutoHandle::AutoHandle(Handle handle) | |
| 10619 : handle_(handle) {} | |
| 10620 | |
| 10621 AutoHandle::~AutoHandle() { | |
| 10622 Reset(); | |
| 10623 } | |
| 10624 | |
| 10625 AutoHandle::Handle AutoHandle::Get() const { | |
| 10626 return handle_; | |
| 10627 } | |
| 10628 | |
| 10629 void AutoHandle::Reset() { | |
| 10630 Reset(INVALID_HANDLE_VALUE); | |
| 10631 } | |
| 10632 | |
| 10633 void AutoHandle::Reset(HANDLE handle) { | |
| 10634 // Resetting with the same handle we already own is invalid. | |
| 10635 if (handle_ != handle) { | |
| 10636 if (IsCloseable()) { | |
| 10637 ::CloseHandle(handle_); | |
| 10638 } | |
| 10639 handle_ = handle; | |
| 10640 } else { | |
| 10641 GTEST_CHECK_(!IsCloseable()) | |
| 10642 << "Resetting a valid handle to itself is likely a programmer error " | |
| 10643 "and thus not allowed."; | |
| 10644 } | |
| 10645 } | |
| 10646 | |
| 10647 bool AutoHandle::IsCloseable() const { | |
| 10648 // Different Windows APIs may use either of these values to represent an | |
| 10649 // invalid handle. | |
| 10650 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE; | |
| 10651 } | |
| 10652 | |
| 10653 Notification::Notification() | |
| 10654 : event_(::CreateEvent(nullptr, // Default security attributes. | |
| 10655 TRUE, // Do not reset automatically. | |
| 10656 FALSE, // Initially unset. | |
| 10657 nullptr)) { // Anonymous event. | |
| 10658 GTEST_CHECK_(event_.Get() != nullptr); | |
| 10659 } | |
| 10660 | |
| 10661 void Notification::Notify() { | |
| 10662 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); | |
| 10663 } | |
| 10664 | |
| 10665 void Notification::WaitForNotification() { | |
| 10666 GTEST_CHECK_( | |
| 10667 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); | |
| 10668 } | |
| 10669 | |
| 10670 Mutex::Mutex() | |
| 10671 : owner_thread_id_(0), | |
| 10672 type_(kDynamic), | |
| 10673 critical_section_init_phase_(0), | |
| 10674 critical_section_(new CRITICAL_SECTION) { | |
| 10675 ::InitializeCriticalSection(critical_section_); | |
| 10676 } | |
| 10677 | |
| 10678 Mutex::~Mutex() { | |
| 10679 // Static mutexes are leaked intentionally. It is not thread-safe to try | |
| 10680 // to clean them up. | |
| 10681 if (type_ == kDynamic) { | |
| 10682 ::DeleteCriticalSection(critical_section_); | |
| 10683 delete critical_section_; | |
| 10684 critical_section_ = nullptr; | |
| 10685 } | |
| 10686 } | |
| 10687 | |
| 10688 void Mutex::Lock() { | |
| 10689 ThreadSafeLazyInit(); | |
| 10690 ::EnterCriticalSection(critical_section_); | |
| 10691 owner_thread_id_ = ::GetCurrentThreadId(); | |
| 10692 } | |
| 10693 | |
| 10694 void Mutex::Unlock() { | |
| 10695 ThreadSafeLazyInit(); | |
| 10696 // We don't protect writing to owner_thread_id_ here, as it's the | |
| 10697 // caller's responsibility to ensure that the current thread holds the | |
| 10698 // mutex when this is called. | |
| 10699 owner_thread_id_ = 0; | |
| 10700 ::LeaveCriticalSection(critical_section_); | |
| 10701 } | |
| 10702 | |
| 10703 // Does nothing if the current thread holds the mutex. Otherwise, crashes | |
| 10704 // with high probability. | |
| 10705 void Mutex::AssertHeld() { | |
| 10706 ThreadSafeLazyInit(); | |
| 10707 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) | |
| 10708 << "The current thread is not holding the mutex @" << this; | |
| 10709 } | |
| 10710 | |
| 10711 namespace { | |
| 10712 | |
| 10713 #ifdef _MSC_VER | |
| 10714 // Use the RAII idiom to flag mem allocs that are intentionally never | |
| 10715 // deallocated. The motivation is to silence the false positive mem leaks | |
| 10716 // that are reported by the debug version of MS's CRT which can only detect | |
| 10717 // if an alloc is missing a matching deallocation. | |
| 10718 // Example: | |
| 10719 // MemoryIsNotDeallocated memory_is_not_deallocated; | |
| 10720 // critical_section_ = new CRITICAL_SECTION; | |
| 10721 // | |
| 10722 class MemoryIsNotDeallocated | |
| 10723 { | |
| 10724 public: | |
| 10725 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { | |
| 10726 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); | |
| 10727 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT | |
| 10728 // doesn't report mem leak if there's no matching deallocation. | |
| 10729 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); | |
| 10730 } | |
| 10731 | |
| 10732 ~MemoryIsNotDeallocated() { | |
| 10733 // Restore the original _CRTDBG_ALLOC_MEM_DF flag | |
| 10734 _CrtSetDbgFlag(old_crtdbg_flag_); | |
| 10735 } | |
| 10736 | |
| 10737 private: | |
| 10738 int old_crtdbg_flag_; | |
| 10739 | |
| 10740 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); | |
| 10741 }; | |
| 10742 #endif // _MSC_VER | |
| 10743 | |
| 10744 } // namespace | |
| 10745 | |
| 10746 // Initializes owner_thread_id_ and critical_section_ in static mutexes. | |
| 10747 void Mutex::ThreadSafeLazyInit() { | |
| 10748 // Dynamic mutexes are initialized in the constructor. | |
| 10749 if (type_ == kStatic) { | |
| 10750 switch ( | |
| 10751 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { | |
| 10752 case 0: | |
| 10753 // If critical_section_init_phase_ was 0 before the exchange, we | |
| 10754 // are the first to test it and need to perform the initialization. | |
| 10755 owner_thread_id_ = 0; | |
| 10756 { | |
| 10757 // Use RAII to flag that following mem alloc is never deallocated. | |
| 10758 #ifdef _MSC_VER | |
| 10759 MemoryIsNotDeallocated memory_is_not_deallocated; | |
| 10760 #endif // _MSC_VER | |
| 10761 critical_section_ = new CRITICAL_SECTION; | |
| 10762 } | |
| 10763 ::InitializeCriticalSection(critical_section_); | |
| 10764 // Updates the critical_section_init_phase_ to 2 to signal | |
| 10765 // initialization complete. | |
| 10766 GTEST_CHECK_(::InterlockedCompareExchange( | |
| 10767 &critical_section_init_phase_, 2L, 1L) == | |
| 10768 1L); | |
| 10769 break; | |
| 10770 case 1: | |
| 10771 // Somebody else is already initializing the mutex; spin until they | |
| 10772 // are done. | |
| 10773 while (::InterlockedCompareExchange(&critical_section_init_phase_, | |
| 10774 2L, | |
| 10775 2L) != 2L) { | |
| 10776 // Possibly yields the rest of the thread's time slice to other | |
| 10777 // threads. | |
| 10778 ::Sleep(0); | |
| 10779 } | |
| 10780 break; | |
| 10781 | |
| 10782 case 2: | |
| 10783 break; // The mutex is already initialized and ready for use. | |
| 10784 | |
| 10785 default: | |
| 10786 GTEST_CHECK_(false) | |
| 10787 << "Unexpected value of critical_section_init_phase_ " | |
| 10788 << "while initializing a static mutex."; | |
| 10789 } | |
| 10790 } | |
| 10791 } | |
| 10792 | |
| 10793 namespace { | |
| 10794 | |
| 10795 class ThreadWithParamSupport : public ThreadWithParamBase { | |
| 10796 public: | |
| 10797 static HANDLE CreateThread(Runnable* runnable, | |
| 10798 Notification* thread_can_start) { | |
| 10799 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); | |
| 10800 DWORD thread_id; | |
| 10801 HANDLE thread_handle = ::CreateThread( | |
| 10802 nullptr, // Default security. | |
| 10803 0, // Default stack size. | |
| 10804 &ThreadWithParamSupport::ThreadMain, | |
| 10805 param, // Parameter to ThreadMainStatic | |
| 10806 0x0, // Default creation flags. | |
| 10807 &thread_id); // Need a valid pointer for the call to work under Win98. | |
| 10808 GTEST_CHECK_(thread_handle != nullptr) | |
| 10809 << "CreateThread failed with error " << ::GetLastError() << "."; | |
| 10810 if (thread_handle == nullptr) { | |
| 10811 delete param; | |
| 10812 } | |
| 10813 return thread_handle; | |
| 10814 } | |
| 10815 | |
| 10816 private: | |
| 10817 struct ThreadMainParam { | |
| 10818 ThreadMainParam(Runnable* runnable, Notification* thread_can_start) | |
| 10819 : runnable_(runnable), | |
| 10820 thread_can_start_(thread_can_start) { | |
| 10821 } | |
| 10822 std::unique_ptr<Runnable> runnable_; | |
| 10823 // Does not own. | |
| 10824 Notification* thread_can_start_; | |
| 10825 }; | |
| 10826 | |
| 10827 static DWORD WINAPI ThreadMain(void* ptr) { | |
| 10828 // Transfers ownership. | |
| 10829 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); | |
| 10830 if (param->thread_can_start_ != nullptr) | |
| 10831 param->thread_can_start_->WaitForNotification(); | |
| 10832 param->runnable_->Run(); | |
| 10833 return 0; | |
| 10834 } | |
| 10835 | |
| 10836 // Prohibit instantiation. | |
| 10837 ThreadWithParamSupport(); | |
| 10838 | |
| 10839 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); | |
| 10840 }; | |
| 10841 | |
| 10842 } // namespace | |
| 10843 | |
| 10844 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, | |
| 10845 Notification* thread_can_start) | |
| 10846 : thread_(ThreadWithParamSupport::CreateThread(runnable, | |
| 10847 thread_can_start)) { | |
| 10848 } | |
| 10849 | |
| 10850 ThreadWithParamBase::~ThreadWithParamBase() { | |
| 10851 Join(); | |
| 10852 } | |
| 10853 | |
| 10854 void ThreadWithParamBase::Join() { | |
| 10855 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) | |
| 10856 << "Failed to join the thread with error " << ::GetLastError() << "."; | |
| 10857 } | |
| 10858 | |
| 10859 // Maps a thread to a set of ThreadIdToThreadLocals that have values | |
| 10860 // instantiated on that thread and notifies them when the thread exits. A | |
| 10861 // ThreadLocal instance is expected to persist until all threads it has | |
| 10862 // values on have terminated. | |
| 10863 class ThreadLocalRegistryImpl { | |
| 10864 public: | |
| 10865 // Registers thread_local_instance as having value on the current thread. | |
| 10866 // Returns a value that can be used to identify the thread from other threads. | |
| 10867 static ThreadLocalValueHolderBase* GetValueOnCurrentThread( | |
| 10868 const ThreadLocalBase* thread_local_instance) { | |
| 10869 #ifdef _MSC_VER | |
| 10870 MemoryIsNotDeallocated memory_is_not_deallocated; | |
| 10871 #endif // _MSC_VER | |
| 10872 DWORD current_thread = ::GetCurrentThreadId(); | |
| 10873 MutexLock lock(&mutex_); | |
| 10874 ThreadIdToThreadLocals* const thread_to_thread_locals = | |
| 10875 GetThreadLocalsMapLocked(); | |
| 10876 ThreadIdToThreadLocals::iterator thread_local_pos = | |
| 10877 thread_to_thread_locals->find(current_thread); | |
| 10878 if (thread_local_pos == thread_to_thread_locals->end()) { | |
| 10879 thread_local_pos = thread_to_thread_locals->insert( | |
| 10880 std::make_pair(current_thread, ThreadLocalValues())).first; | |
| 10881 StartWatcherThreadFor(current_thread); | |
| 10882 } | |
| 10883 ThreadLocalValues& thread_local_values = thread_local_pos->second; | |
| 10884 ThreadLocalValues::iterator value_pos = | |
| 10885 thread_local_values.find(thread_local_instance); | |
| 10886 if (value_pos == thread_local_values.end()) { | |
| 10887 value_pos = | |
| 10888 thread_local_values | |
| 10889 .insert(std::make_pair( | |
| 10890 thread_local_instance, | |
| 10891 std::shared_ptr<ThreadLocalValueHolderBase>( | |
| 10892 thread_local_instance->NewValueForCurrentThread()))) | |
| 10893 .first; | |
| 10894 } | |
| 10895 return value_pos->second.get(); | |
| 10896 } | |
| 10897 | |
| 10898 static void OnThreadLocalDestroyed( | |
| 10899 const ThreadLocalBase* thread_local_instance) { | |
| 10900 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders; | |
| 10901 // Clean up the ThreadLocalValues data structure while holding the lock, but | |
| 10902 // defer the destruction of the ThreadLocalValueHolderBases. | |
| 10903 { | |
| 10904 MutexLock lock(&mutex_); | |
| 10905 ThreadIdToThreadLocals* const thread_to_thread_locals = | |
| 10906 GetThreadLocalsMapLocked(); | |
| 10907 for (ThreadIdToThreadLocals::iterator it = | |
| 10908 thread_to_thread_locals->begin(); | |
| 10909 it != thread_to_thread_locals->end(); | |
| 10910 ++it) { | |
| 10911 ThreadLocalValues& thread_local_values = it->second; | |
| 10912 ThreadLocalValues::iterator value_pos = | |
| 10913 thread_local_values.find(thread_local_instance); | |
| 10914 if (value_pos != thread_local_values.end()) { | |
| 10915 value_holders.push_back(value_pos->second); | |
| 10916 thread_local_values.erase(value_pos); | |
| 10917 // This 'if' can only be successful at most once, so theoretically we | |
| 10918 // could break out of the loop here, but we don't bother doing so. | |
| 10919 } | |
| 10920 } | |
| 10921 } | |
| 10922 // Outside the lock, let the destructor for 'value_holders' deallocate the | |
| 10923 // ThreadLocalValueHolderBases. | |
| 10924 } | |
| 10925 | |
| 10926 static void OnThreadExit(DWORD thread_id) { | |
| 10927 GTEST_CHECK_(thread_id != 0) << ::GetLastError(); | |
| 10928 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders; | |
| 10929 // Clean up the ThreadIdToThreadLocals data structure while holding the | |
| 10930 // lock, but defer the destruction of the ThreadLocalValueHolderBases. | |
| 10931 { | |
| 10932 MutexLock lock(&mutex_); | |
| 10933 ThreadIdToThreadLocals* const thread_to_thread_locals = | |
| 10934 GetThreadLocalsMapLocked(); | |
| 10935 ThreadIdToThreadLocals::iterator thread_local_pos = | |
| 10936 thread_to_thread_locals->find(thread_id); | |
| 10937 if (thread_local_pos != thread_to_thread_locals->end()) { | |
| 10938 ThreadLocalValues& thread_local_values = thread_local_pos->second; | |
| 10939 for (ThreadLocalValues::iterator value_pos = | |
| 10940 thread_local_values.begin(); | |
| 10941 value_pos != thread_local_values.end(); | |
| 10942 ++value_pos) { | |
| 10943 value_holders.push_back(value_pos->second); | |
| 10944 } | |
| 10945 thread_to_thread_locals->erase(thread_local_pos); | |
| 10946 } | |
| 10947 } | |
| 10948 // Outside the lock, let the destructor for 'value_holders' deallocate the | |
| 10949 // ThreadLocalValueHolderBases. | |
| 10950 } | |
| 10951 | |
| 10952 private: | |
| 10953 // In a particular thread, maps a ThreadLocal object to its value. | |
| 10954 typedef std::map<const ThreadLocalBase*, | |
| 10955 std::shared_ptr<ThreadLocalValueHolderBase> > | |
| 10956 ThreadLocalValues; | |
| 10957 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by | |
| 10958 // thread's ID. | |
| 10959 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; | |
| 10960 | |
| 10961 // Holds the thread id and thread handle that we pass from | |
| 10962 // StartWatcherThreadFor to WatcherThreadFunc. | |
| 10963 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle; | |
| 10964 | |
| 10965 static void StartWatcherThreadFor(DWORD thread_id) { | |
| 10966 // The returned handle will be kept in thread_map and closed by | |
| 10967 // watcher_thread in WatcherThreadFunc. | |
| 10968 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, | |
| 10969 FALSE, | |
| 10970 thread_id); | |
| 10971 GTEST_CHECK_(thread != nullptr); | |
| 10972 // We need to pass a valid thread ID pointer into CreateThread for it | |
| 10973 // to work correctly under Win98. | |
| 10974 DWORD watcher_thread_id; | |
| 10975 HANDLE watcher_thread = ::CreateThread( | |
| 10976 nullptr, // Default security. | |
| 10977 0, // Default stack size | |
| 10978 &ThreadLocalRegistryImpl::WatcherThreadFunc, | |
| 10979 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), | |
| 10980 CREATE_SUSPENDED, &watcher_thread_id); | |
| 10981 GTEST_CHECK_(watcher_thread != nullptr); | |
| 10982 // Give the watcher thread the same priority as ours to avoid being | |
| 10983 // blocked by it. | |
| 10984 ::SetThreadPriority(watcher_thread, | |
| 10985 ::GetThreadPriority(::GetCurrentThread())); | |
| 10986 ::ResumeThread(watcher_thread); | |
| 10987 ::CloseHandle(watcher_thread); | |
| 10988 } | |
| 10989 | |
| 10990 // Monitors exit from a given thread and notifies those | |
| 10991 // ThreadIdToThreadLocals about thread termination. | |
| 10992 static DWORD WINAPI WatcherThreadFunc(LPVOID param) { | |
| 10993 const ThreadIdAndHandle* tah = | |
| 10994 reinterpret_cast<const ThreadIdAndHandle*>(param); | |
| 10995 GTEST_CHECK_( | |
| 10996 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); | |
| 10997 OnThreadExit(tah->first); | |
| 10998 ::CloseHandle(tah->second); | |
| 10999 delete tah; | |
| 11000 return 0; | |
| 11001 } | |
| 11002 | |
| 11003 // Returns map of thread local instances. | |
| 11004 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { | |
| 11005 mutex_.AssertHeld(); | |
| 11006 #ifdef _MSC_VER | |
| 11007 MemoryIsNotDeallocated memory_is_not_deallocated; | |
| 11008 #endif // _MSC_VER | |
| 11009 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); | |
| 11010 return map; | |
| 11011 } | |
| 11012 | |
| 11013 // Protects access to GetThreadLocalsMapLocked() and its return value. | |
| 11014 static Mutex mutex_; | |
| 11015 // Protects access to GetThreadMapLocked() and its return value. | |
| 11016 static Mutex thread_map_mutex_; | |
| 11017 }; | |
| 11018 | |
| 11019 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); | |
| 11020 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); | |
| 11021 | |
| 11022 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( | |
| 11023 const ThreadLocalBase* thread_local_instance) { | |
| 11024 return ThreadLocalRegistryImpl::GetValueOnCurrentThread( | |
| 11025 thread_local_instance); | |
| 11026 } | |
| 11027 | |
| 11028 void ThreadLocalRegistry::OnThreadLocalDestroyed( | |
| 11029 const ThreadLocalBase* thread_local_instance) { | |
| 11030 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); | |
| 11031 } | |
| 11032 | |
| 11033 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS | |
| 11034 | |
| 11035 #if GTEST_USES_POSIX_RE | |
| 11036 | |
| 11037 // Implements RE. Currently only needed for death tests. | |
| 11038 | |
| 11039 RE::~RE() { | |
| 11040 if (is_valid_) { | |
| 11041 // regfree'ing an invalid regex might crash because the content | |
| 11042 // of the regex is undefined. Since the regex's are essentially | |
| 11043 // the same, one cannot be valid (or invalid) without the other | |
| 11044 // being so too. | |
| 11045 regfree(&partial_regex_); | |
| 11046 regfree(&full_regex_); | |
| 11047 } | |
| 11048 free(const_cast<char*>(pattern_)); | |
| 11049 } | |
| 11050 | |
| 11051 // Returns true if and only if regular expression re matches the entire str. | |
| 11052 bool RE::FullMatch(const char* str, const RE& re) { | |
| 11053 if (!re.is_valid_) return false; | |
| 11054 | |
| 11055 regmatch_t match; | |
| 11056 return regexec(&re.full_regex_, str, 1, &match, 0) == 0; | |
| 11057 } | |
| 11058 | |
| 11059 // Returns true if and only if regular expression re matches a substring of | |
| 11060 // str (including str itself). | |
| 11061 bool RE::PartialMatch(const char* str, const RE& re) { | |
| 11062 if (!re.is_valid_) return false; | |
| 11063 | |
| 11064 regmatch_t match; | |
| 11065 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; | |
| 11066 } | |
| 11067 | |
| 11068 // Initializes an RE from its string representation. | |
| 11069 void RE::Init(const char* regex) { | |
| 11070 pattern_ = posix::StrDup(regex); | |
| 11071 | |
| 11072 // Reserves enough bytes to hold the regular expression used for a | |
| 11073 // full match. | |
| 11074 const size_t full_regex_len = strlen(regex) + 10; | |
| 11075 char* const full_pattern = new char[full_regex_len]; | |
| 11076 | |
| 11077 snprintf(full_pattern, full_regex_len, "^(%s)$", regex); | |
| 11078 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; | |
| 11079 // We want to call regcomp(&partial_regex_, ...) even if the | |
| 11080 // previous expression returns false. Otherwise partial_regex_ may | |
| 11081 // not be properly initialized can may cause trouble when it's | |
| 11082 // freed. | |
| 11083 // | |
| 11084 // Some implementation of POSIX regex (e.g. on at least some | |
| 11085 // versions of Cygwin) doesn't accept the empty string as a valid | |
| 11086 // regex. We change it to an equivalent form "()" to be safe. | |
| 11087 if (is_valid_) { | |
| 11088 const char* const partial_regex = (*regex == '\0') ? "()" : regex; | |
| 11089 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; | |
| 11090 } | |
| 11091 EXPECT_TRUE(is_valid_) | |
| 11092 << "Regular expression \"" << regex | |
| 11093 << "\" is not a valid POSIX Extended regular expression."; | |
| 11094 | |
| 11095 delete[] full_pattern; | |
| 11096 } | |
| 11097 | |
| 11098 #elif GTEST_USES_SIMPLE_RE | |
| 11099 | |
| 11100 // Returns true if and only if ch appears anywhere in str (excluding the | |
| 11101 // terminating '\0' character). | |
| 11102 bool IsInSet(char ch, const char* str) { | |
| 11103 return ch != '\0' && strchr(str, ch) != nullptr; | |
| 11104 } | |
| 11105 | |
| 11106 // Returns true if and only if ch belongs to the given classification. | |
| 11107 // Unlike similar functions in <ctype.h>, these aren't affected by the | |
| 11108 // current locale. | |
| 11109 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } | |
| 11110 bool IsAsciiPunct(char ch) { | |
| 11111 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); | |
| 11112 } | |
| 11113 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } | |
| 11114 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } | |
| 11115 bool IsAsciiWordChar(char ch) { | |
| 11116 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || | |
| 11117 ('0' <= ch && ch <= '9') || ch == '_'; | |
| 11118 } | |
| 11119 | |
| 11120 // Returns true if and only if "\\c" is a supported escape sequence. | |
| 11121 bool IsValidEscape(char c) { | |
| 11122 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); | |
| 11123 } | |
| 11124 | |
| 11125 // Returns true if and only if the given atom (specified by escaped and | |
| 11126 // pattern) matches ch. The result is undefined if the atom is invalid. | |
| 11127 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { | |
| 11128 if (escaped) { // "\\p" where p is pattern_char. | |
| 11129 switch (pattern_char) { | |
| 11130 case 'd': return IsAsciiDigit(ch); | |
| 11131 case 'D': return !IsAsciiDigit(ch); | |
| 11132 case 'f': return ch == '\f'; | |
| 11133 case 'n': return ch == '\n'; | |
| 11134 case 'r': return ch == '\r'; | |
| 11135 case 's': return IsAsciiWhiteSpace(ch); | |
| 11136 case 'S': return !IsAsciiWhiteSpace(ch); | |
| 11137 case 't': return ch == '\t'; | |
| 11138 case 'v': return ch == '\v'; | |
| 11139 case 'w': return IsAsciiWordChar(ch); | |
| 11140 case 'W': return !IsAsciiWordChar(ch); | |
| 11141 } | |
| 11142 return IsAsciiPunct(pattern_char) && pattern_char == ch; | |
| 11143 } | |
| 11144 | |
| 11145 return (pattern_char == '.' && ch != '\n') || pattern_char == ch; | |
| 11146 } | |
| 11147 | |
| 11148 // Helper function used by ValidateRegex() to format error messages. | |
| 11149 static std::string FormatRegexSyntaxError(const char* regex, int index) { | |
| 11150 return (Message() << "Syntax error at index " << index | |
| 11151 << " in simple regular expression \"" << regex << "\": ").GetString(); | |
| 11152 } | |
| 11153 | |
| 11154 // Generates non-fatal failures and returns false if regex is invalid; | |
| 11155 // otherwise returns true. | |
| 11156 bool ValidateRegex(const char* regex) { | |
| 11157 if (regex == nullptr) { | |
| 11158 ADD_FAILURE() << "NULL is not a valid simple regular expression."; | |
| 11159 return false; | |
| 11160 } | |
| 11161 | |
| 11162 bool is_valid = true; | |
| 11163 | |
| 11164 // True if and only if ?, *, or + can follow the previous atom. | |
| 11165 bool prev_repeatable = false; | |
| 11166 for (int i = 0; regex[i]; i++) { | |
| 11167 if (regex[i] == '\\') { // An escape sequence | |
| 11168 i++; | |
| 11169 if (regex[i] == '\0') { | |
| 11170 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) | |
| 11171 << "'\\' cannot appear at the end."; | |
| 11172 return false; | |
| 11173 } | |
| 11174 | |
| 11175 if (!IsValidEscape(regex[i])) { | |
| 11176 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) | |
| 11177 << "invalid escape sequence \"\\" << regex[i] << "\"."; | |
| 11178 is_valid = false; | |
| 11179 } | |
| 11180 prev_repeatable = true; | |
| 11181 } else { // Not an escape sequence. | |
| 11182 const char ch = regex[i]; | |
| 11183 | |
| 11184 if (ch == '^' && i > 0) { | |
| 11185 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) | |
| 11186 << "'^' can only appear at the beginning."; | |
| 11187 is_valid = false; | |
| 11188 } else if (ch == '$' && regex[i + 1] != '\0') { | |
| 11189 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) | |
| 11190 << "'$' can only appear at the end."; | |
| 11191 is_valid = false; | |
| 11192 } else if (IsInSet(ch, "()[]{}|")) { | |
| 11193 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) | |
| 11194 << "'" << ch << "' is unsupported."; | |
| 11195 is_valid = false; | |
| 11196 } else if (IsRepeat(ch) && !prev_repeatable) { | |
| 11197 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) | |
| 11198 << "'" << ch << "' can only follow a repeatable token."; | |
| 11199 is_valid = false; | |
| 11200 } | |
| 11201 | |
| 11202 prev_repeatable = !IsInSet(ch, "^$?*+"); | |
| 11203 } | |
| 11204 } | |
| 11205 | |
| 11206 return is_valid; | |
| 11207 } | |
| 11208 | |
| 11209 // Matches a repeated regex atom followed by a valid simple regular | |
| 11210 // expression. The regex atom is defined as c if escaped is false, | |
| 11211 // or \c otherwise. repeat is the repetition meta character (?, *, | |
| 11212 // or +). The behavior is undefined if str contains too many | |
| 11213 // characters to be indexable by size_t, in which case the test will | |
| 11214 // probably time out anyway. We are fine with this limitation as | |
| 11215 // std::string has it too. | |
| 11216 bool MatchRepetitionAndRegexAtHead( | |
| 11217 bool escaped, char c, char repeat, const char* regex, | |
| 11218 const char* str) { | |
| 11219 const size_t min_count = (repeat == '+') ? 1 : 0; | |
| 11220 const size_t max_count = (repeat == '?') ? 1 : | |
| 11221 static_cast<size_t>(-1) - 1; | |
| 11222 // We cannot call numeric_limits::max() as it conflicts with the | |
| 11223 // max() macro on Windows. | |
| 11224 | |
| 11225 for (size_t i = 0; i <= max_count; ++i) { | |
| 11226 // We know that the atom matches each of the first i characters in str. | |
| 11227 if (i >= min_count && MatchRegexAtHead(regex, str + i)) { | |
| 11228 // We have enough matches at the head, and the tail matches too. | |
| 11229 // Since we only care about *whether* the pattern matches str | |
| 11230 // (as opposed to *how* it matches), there is no need to find a | |
| 11231 // greedy match. | |
| 11232 return true; | |
| 11233 } | |
| 11234 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) | |
| 11235 return false; | |
| 11236 } | |
| 11237 return false; | |
| 11238 } | |
| 11239 | |
| 11240 // Returns true if and only if regex matches a prefix of str. regex must | |
| 11241 // be a valid simple regular expression and not start with "^", or the | |
| 11242 // result is undefined. | |
| 11243 bool MatchRegexAtHead(const char* regex, const char* str) { | |
| 11244 if (*regex == '\0') // An empty regex matches a prefix of anything. | |
| 11245 return true; | |
| 11246 | |
| 11247 // "$" only matches the end of a string. Note that regex being | |
| 11248 // valid guarantees that there's nothing after "$" in it. | |
| 11249 if (*regex == '$') | |
| 11250 return *str == '\0'; | |
| 11251 | |
| 11252 // Is the first thing in regex an escape sequence? | |
| 11253 const bool escaped = *regex == '\\'; | |
| 11254 if (escaped) | |
| 11255 ++regex; | |
| 11256 if (IsRepeat(regex[1])) { | |
| 11257 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so | |
| 11258 // here's an indirect recursion. It terminates as the regex gets | |
| 11259 // shorter in each recursion. | |
| 11260 return MatchRepetitionAndRegexAtHead( | |
| 11261 escaped, regex[0], regex[1], regex + 2, str); | |
| 11262 } else { | |
| 11263 // regex isn't empty, isn't "$", and doesn't start with a | |
| 11264 // repetition. We match the first atom of regex with the first | |
| 11265 // character of str and recurse. | |
| 11266 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && | |
| 11267 MatchRegexAtHead(regex + 1, str + 1); | |
| 11268 } | |
| 11269 } | |
| 11270 | |
| 11271 // Returns true if and only if regex matches any substring of str. regex must | |
| 11272 // be a valid simple regular expression, or the result is undefined. | |
| 11273 // | |
| 11274 // The algorithm is recursive, but the recursion depth doesn't exceed | |
| 11275 // the regex length, so we won't need to worry about running out of | |
| 11276 // stack space normally. In rare cases the time complexity can be | |
| 11277 // exponential with respect to the regex length + the string length, | |
| 11278 // but usually it's must faster (often close to linear). | |
| 11279 bool MatchRegexAnywhere(const char* regex, const char* str) { | |
| 11280 if (regex == nullptr || str == nullptr) return false; | |
| 11281 | |
| 11282 if (*regex == '^') | |
| 11283 return MatchRegexAtHead(regex + 1, str); | |
| 11284 | |
| 11285 // A successful match can be anywhere in str. | |
| 11286 do { | |
| 11287 if (MatchRegexAtHead(regex, str)) | |
| 11288 return true; | |
| 11289 } while (*str++ != '\0'); | |
| 11290 return false; | |
| 11291 } | |
| 11292 | |
| 11293 // Implements the RE class. | |
| 11294 | |
| 11295 RE::~RE() { | |
| 11296 free(const_cast<char*>(pattern_)); | |
| 11297 free(const_cast<char*>(full_pattern_)); | |
| 11298 } | |
| 11299 | |
| 11300 // Returns true if and only if regular expression re matches the entire str. | |
| 11301 bool RE::FullMatch(const char* str, const RE& re) { | |
| 11302 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); | |
| 11303 } | |
| 11304 | |
| 11305 // Returns true if and only if regular expression re matches a substring of | |
| 11306 // str (including str itself). | |
| 11307 bool RE::PartialMatch(const char* str, const RE& re) { | |
| 11308 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); | |
| 11309 } | |
| 11310 | |
| 11311 // Initializes an RE from its string representation. | |
| 11312 void RE::Init(const char* regex) { | |
| 11313 pattern_ = full_pattern_ = nullptr; | |
| 11314 if (regex != nullptr) { | |
| 11315 pattern_ = posix::StrDup(regex); | |
| 11316 } | |
| 11317 | |
| 11318 is_valid_ = ValidateRegex(regex); | |
| 11319 if (!is_valid_) { | |
| 11320 // No need to calculate the full pattern when the regex is invalid. | |
| 11321 return; | |
| 11322 } | |
| 11323 | |
| 11324 const size_t len = strlen(regex); | |
| 11325 // Reserves enough bytes to hold the regular expression used for a | |
| 11326 // full match: we need space to prepend a '^', append a '$', and | |
| 11327 // terminate the string with '\0'. | |
| 11328 char* buffer = static_cast<char*>(malloc(len + 3)); | |
| 11329 full_pattern_ = buffer; | |
| 11330 | |
| 11331 if (*regex != '^') | |
| 11332 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. | |
| 11333 | |
| 11334 // We don't use snprintf or strncpy, as they trigger a warning when | |
| 11335 // compiled with VC++ 8.0. | |
| 11336 memcpy(buffer, regex, len); | |
| 11337 buffer += len; | |
| 11338 | |
| 11339 if (len == 0 || regex[len - 1] != '$') | |
| 11340 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. | |
| 11341 | |
| 11342 *buffer = '\0'; | |
| 11343 } | |
| 11344 | |
| 11345 #endif // GTEST_USES_POSIX_RE | |
| 11346 | |
| 11347 const char kUnknownFile[] = "unknown file"; | |
| 11348 | |
| 11349 // Formats a source file path and a line number as they would appear | |
| 11350 // in an error message from the compiler used to compile this code. | |
| 11351 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { | |
| 11352 const std::string file_name(file == nullptr ? kUnknownFile : file); | |
| 11353 | |
| 11354 if (line < 0) { | |
| 11355 return file_name + ":"; | |
| 11356 } | |
| 11357 #ifdef _MSC_VER | |
| 11358 return file_name + "(" + StreamableToString(line) + "):"; | |
| 11359 #else | |
| 11360 return file_name + ":" + StreamableToString(line) + ":"; | |
| 11361 #endif // _MSC_VER | |
| 11362 } | |
| 11363 | |
| 11364 // Formats a file location for compiler-independent XML output. | |
| 11365 // Although this function is not platform dependent, we put it next to | |
| 11366 // FormatFileLocation in order to contrast the two functions. | |
| 11367 // Note that FormatCompilerIndependentFileLocation() does NOT append colon | |
| 11368 // to the file location it produces, unlike FormatFileLocation(). | |
| 11369 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( | |
| 11370 const char* file, int line) { | |
| 11371 const std::string file_name(file == nullptr ? kUnknownFile : file); | |
| 11372 | |
| 11373 if (line < 0) | |
| 11374 return file_name; | |
| 11375 else | |
| 11376 return file_name + ":" + StreamableToString(line); | |
| 11377 } | |
| 11378 | |
| 11379 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) | |
| 11380 : severity_(severity) { | |
| 11381 const char* const marker = | |
| 11382 severity == GTEST_INFO ? "[ INFO ]" : | |
| 11383 severity == GTEST_WARNING ? "[WARNING]" : | |
| 11384 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; | |
| 11385 GetStream() << ::std::endl << marker << " " | |
| 11386 << FormatFileLocation(file, line).c_str() << ": "; | |
| 11387 } | |
| 11388 | |
| 11389 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. | |
| 11390 GTestLog::~GTestLog() { | |
| 11391 GetStream() << ::std::endl; | |
| 11392 if (severity_ == GTEST_FATAL) { | |
| 11393 fflush(stderr); | |
| 11394 posix::Abort(); | |
| 11395 } | |
| 11396 } | |
| 11397 | |
| 11398 // Disable Microsoft deprecation warnings for POSIX functions called from | |
| 11399 // this class (creat, dup, dup2, and close) | |
| 11400 GTEST_DISABLE_MSC_DEPRECATED_PUSH_() | |
| 11401 | |
| 11402 #if GTEST_HAS_STREAM_REDIRECTION | |
| 11403 | |
| 11404 // Object that captures an output stream (stdout/stderr). | |
| 11405 class CapturedStream { | |
| 11406 public: | |
| 11407 // The ctor redirects the stream to a temporary file. | |
| 11408 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { | |
| 11409 # if GTEST_OS_WINDOWS | |
| 11410 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT | |
| 11411 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT | |
| 11412 | |
| 11413 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); | |
| 11414 const UINT success = ::GetTempFileNameA(temp_dir_path, | |
| 11415 "gtest_redir", | |
| 11416 0, // Generate unique file name. | |
| 11417 temp_file_path); | |
| 11418 GTEST_CHECK_(success != 0) | |
| 11419 << "Unable to create a temporary file in " << temp_dir_path; | |
| 11420 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); | |
| 11421 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " | |
| 11422 << temp_file_path; | |
| 11423 filename_ = temp_file_path; | |
| 11424 # else | |
| 11425 // There's no guarantee that a test has write access to the current | |
| 11426 // directory, so we create the temporary file in the /tmp directory | |
| 11427 // instead. We use /tmp on most systems, and /sdcard on Android. | |
| 11428 // That's because Android doesn't have /tmp. | |
| 11429 # if GTEST_OS_LINUX_ANDROID | |
| 11430 // Note: Android applications are expected to call the framework's | |
| 11431 // Context.getExternalStorageDirectory() method through JNI to get | |
| 11432 // the location of the world-writable SD Card directory. However, | |
| 11433 // this requires a Context handle, which cannot be retrieved | |
| 11434 // globally from native code. Doing so also precludes running the | |
| 11435 // code as part of a regular standalone executable, which doesn't | |
| 11436 // run in a Dalvik process (e.g. when running it through 'adb shell'). | |
| 11437 // | |
| 11438 // The location /data/local/tmp is directly accessible from native code. | |
| 11439 // '/sdcard' and other variants cannot be relied on, as they are not | |
| 11440 // guaranteed to be mounted, or may have a delay in mounting. | |
| 11441 char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX"; | |
| 11442 # else | |
| 11443 char name_template[] = "/tmp/captured_stream.XXXXXX"; | |
| 11444 # endif // GTEST_OS_LINUX_ANDROID | |
| 11445 const int captured_fd = mkstemp(name_template); | |
| 11446 if (captured_fd == -1) { | |
| 11447 GTEST_LOG_(WARNING) | |
| 11448 << "Failed to create tmp file " << name_template | |
| 11449 << " for test; does the test have access to the /tmp directory?"; | |
| 11450 } | |
| 11451 filename_ = name_template; | |
| 11452 # endif // GTEST_OS_WINDOWS | |
| 11453 fflush(nullptr); | |
| 11454 dup2(captured_fd, fd_); | |
| 11455 close(captured_fd); | |
| 11456 } | |
| 11457 | |
| 11458 ~CapturedStream() { | |
| 11459 remove(filename_.c_str()); | |
| 11460 } | |
| 11461 | |
| 11462 std::string GetCapturedString() { | |
| 11463 if (uncaptured_fd_ != -1) { | |
| 11464 // Restores the original stream. | |
| 11465 fflush(nullptr); | |
| 11466 dup2(uncaptured_fd_, fd_); | |
| 11467 close(uncaptured_fd_); | |
| 11468 uncaptured_fd_ = -1; | |
| 11469 } | |
| 11470 | |
| 11471 FILE* const file = posix::FOpen(filename_.c_str(), "r"); | |
| 11472 if (file == nullptr) { | |
| 11473 GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_ | |
| 11474 << " for capturing stream."; | |
| 11475 } | |
| 11476 const std::string content = ReadEntireFile(file); | |
| 11477 posix::FClose(file); | |
| 11478 return content; | |
| 11479 } | |
| 11480 | |
| 11481 private: | |
| 11482 const int fd_; // A stream to capture. | |
| 11483 int uncaptured_fd_; | |
| 11484 // Name of the temporary file holding the stderr output. | |
| 11485 ::std::string filename_; | |
| 11486 | |
| 11487 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); | |
| 11488 }; | |
| 11489 | |
| 11490 GTEST_DISABLE_MSC_DEPRECATED_POP_() | |
| 11491 | |
| 11492 static CapturedStream* g_captured_stderr = nullptr; | |
| 11493 static CapturedStream* g_captured_stdout = nullptr; | |
| 11494 | |
| 11495 // Starts capturing an output stream (stdout/stderr). | |
| 11496 static void CaptureStream(int fd, const char* stream_name, | |
| 11497 CapturedStream** stream) { | |
| 11498 if (*stream != nullptr) { | |
| 11499 GTEST_LOG_(FATAL) << "Only one " << stream_name | |
| 11500 << " capturer can exist at a time."; | |
| 11501 } | |
| 11502 *stream = new CapturedStream(fd); | |
| 11503 } | |
| 11504 | |
| 11505 // Stops capturing the output stream and returns the captured string. | |
| 11506 static std::string GetCapturedStream(CapturedStream** captured_stream) { | |
| 11507 const std::string content = (*captured_stream)->GetCapturedString(); | |
| 11508 | |
| 11509 delete *captured_stream; | |
| 11510 *captured_stream = nullptr; | |
| 11511 | |
| 11512 return content; | |
| 11513 } | |
| 11514 | |
| 11515 // Starts capturing stdout. | |
| 11516 void CaptureStdout() { | |
| 11517 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); | |
| 11518 } | |
| 11519 | |
| 11520 // Starts capturing stderr. | |
| 11521 void CaptureStderr() { | |
| 11522 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); | |
| 11523 } | |
| 11524 | |
| 11525 // Stops capturing stdout and returns the captured string. | |
| 11526 std::string GetCapturedStdout() { | |
| 11527 return GetCapturedStream(&g_captured_stdout); | |
| 11528 } | |
| 11529 | |
| 11530 // Stops capturing stderr and returns the captured string. | |
| 11531 std::string GetCapturedStderr() { | |
| 11532 return GetCapturedStream(&g_captured_stderr); | |
| 11533 } | |
| 11534 | |
| 11535 #endif // GTEST_HAS_STREAM_REDIRECTION | |
| 11536 | |
| 11537 | |
| 11538 | |
| 11539 | |
| 11540 | |
| 11541 size_t GetFileSize(FILE* file) { | |
| 11542 fseek(file, 0, SEEK_END); | |
| 11543 return static_cast<size_t>(ftell(file)); | |
| 11544 } | |
| 11545 | |
| 11546 std::string ReadEntireFile(FILE* file) { | |
| 11547 const size_t file_size = GetFileSize(file); | |
| 11548 char* const buffer = new char[file_size]; | |
| 11549 | |
| 11550 size_t bytes_last_read = 0; // # of bytes read in the last fread() | |
| 11551 size_t bytes_read = 0; // # of bytes read so far | |
| 11552 | |
| 11553 fseek(file, 0, SEEK_SET); | |
| 11554 | |
| 11555 // Keeps reading the file until we cannot read further or the | |
| 11556 // pre-determined file size is reached. | |
| 11557 do { | |
| 11558 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); | |
| 11559 bytes_read += bytes_last_read; | |
| 11560 } while (bytes_last_read > 0 && bytes_read < file_size); | |
| 11561 | |
| 11562 const std::string content(buffer, bytes_read); | |
| 11563 delete[] buffer; | |
| 11564 | |
| 11565 return content; | |
| 11566 } | |
| 11567 | |
| 11568 #if GTEST_HAS_DEATH_TEST | |
| 11569 static const std::vector<std::string>* g_injected_test_argvs = | |
| 11570 nullptr; // Owned. | |
| 11571 | |
| 11572 std::vector<std::string> GetInjectableArgvs() { | |
| 11573 if (g_injected_test_argvs != nullptr) { | |
| 11574 return *g_injected_test_argvs; | |
| 11575 } | |
| 11576 return GetArgvs(); | |
| 11577 } | |
| 11578 | |
| 11579 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) { | |
| 11580 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs; | |
| 11581 g_injected_test_argvs = new_argvs; | |
| 11582 } | |
| 11583 | |
| 11584 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) { | |
| 11585 SetInjectableArgvs( | |
| 11586 new std::vector<std::string>(new_argvs.begin(), new_argvs.end())); | |
| 11587 } | |
| 11588 | |
| 11589 void ClearInjectableArgvs() { | |
| 11590 delete g_injected_test_argvs; | |
| 11591 g_injected_test_argvs = nullptr; | |
| 11592 } | |
| 11593 #endif // GTEST_HAS_DEATH_TEST | |
| 11594 | |
| 11595 #if GTEST_OS_WINDOWS_MOBILE | |
| 11596 namespace posix { | |
| 11597 void Abort() { | |
| 11598 DebugBreak(); | |
| 11599 TerminateProcess(GetCurrentProcess(), 1); | |
| 11600 } | |
| 11601 } // namespace posix | |
| 11602 #endif // GTEST_OS_WINDOWS_MOBILE | |
| 11603 | |
| 11604 // Returns the name of the environment variable corresponding to the | |
| 11605 // given flag. For example, FlagToEnvVar("foo") will return | |
| 11606 // "GTEST_FOO" in the open-source version. | |
| 11607 static std::string FlagToEnvVar(const char* flag) { | |
| 11608 const std::string full_flag = | |
| 11609 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); | |
| 11610 | |
| 11611 Message env_var; | |
| 11612 for (size_t i = 0; i != full_flag.length(); i++) { | |
| 11613 env_var << ToUpper(full_flag.c_str()[i]); | |
| 11614 } | |
| 11615 | |
| 11616 return env_var.GetString(); | |
| 11617 } | |
| 11618 | |
| 11619 // Parses 'str' for a 32-bit signed integer. If successful, writes | |
| 11620 // the result to *value and returns true; otherwise leaves *value | |
| 11621 // unchanged and returns false. | |
| 11622 bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { | |
| 11623 // Parses the environment variable as a decimal integer. | |
| 11624 char* end = nullptr; | |
| 11625 const long long_value = strtol(str, &end, 10); // NOLINT | |
| 11626 | |
| 11627 // Has strtol() consumed all characters in the string? | |
| 11628 if (*end != '\0') { | |
| 11629 // No - an invalid character was encountered. | |
| 11630 Message msg; | |
| 11631 msg << "WARNING: " << src_text | |
| 11632 << " is expected to be a 32-bit integer, but actually" | |
| 11633 << " has value \"" << str << "\".\n"; | |
| 11634 printf("%s", msg.GetString().c_str()); | |
| 11635 fflush(stdout); | |
| 11636 return false; | |
| 11637 } | |
| 11638 | |
| 11639 // Is the parsed value in the range of an int32_t? | |
| 11640 const auto result = static_cast<int32_t>(long_value); | |
| 11641 if (long_value == LONG_MAX || long_value == LONG_MIN || | |
| 11642 // The parsed value overflows as a long. (strtol() returns | |
| 11643 // LONG_MAX or LONG_MIN when the input overflows.) | |
| 11644 result != long_value | |
| 11645 // The parsed value overflows as an int32_t. | |
| 11646 ) { | |
| 11647 Message msg; | |
| 11648 msg << "WARNING: " << src_text | |
| 11649 << " is expected to be a 32-bit integer, but actually" | |
| 11650 << " has value " << str << ", which overflows.\n"; | |
| 11651 printf("%s", msg.GetString().c_str()); | |
| 11652 fflush(stdout); | |
| 11653 return false; | |
| 11654 } | |
| 11655 | |
| 11656 *value = result; | |
| 11657 return true; | |
| 11658 } | |
| 11659 | |
| 11660 // Reads and returns the Boolean environment variable corresponding to | |
| 11661 // the given flag; if it's not set, returns default_value. | |
| 11662 // | |
| 11663 // The value is considered true if and only if it's not "0". | |
| 11664 bool BoolFromGTestEnv(const char* flag, bool default_value) { | |
| 11665 #if defined(GTEST_GET_BOOL_FROM_ENV_) | |
| 11666 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); | |
| 11667 #else | |
| 11668 const std::string env_var = FlagToEnvVar(flag); | |
| 11669 const char* const string_value = posix::GetEnv(env_var.c_str()); | |
| 11670 return string_value == nullptr ? default_value | |
| 11671 : strcmp(string_value, "0") != 0; | |
| 11672 #endif // defined(GTEST_GET_BOOL_FROM_ENV_) | |
| 11673 } | |
| 11674 | |
| 11675 // Reads and returns a 32-bit integer stored in the environment | |
| 11676 // variable corresponding to the given flag; if it isn't set or | |
| 11677 // doesn't represent a valid 32-bit integer, returns default_value. | |
| 11678 int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { | |
| 11679 #if defined(GTEST_GET_INT32_FROM_ENV_) | |
| 11680 return GTEST_GET_INT32_FROM_ENV_(flag, default_value); | |
| 11681 #else | |
| 11682 const std::string env_var = FlagToEnvVar(flag); | |
| 11683 const char* const string_value = posix::GetEnv(env_var.c_str()); | |
| 11684 if (string_value == nullptr) { | |
| 11685 // The environment variable is not set. | |
| 11686 return default_value; | |
| 11687 } | |
| 11688 | |
| 11689 int32_t result = default_value; | |
| 11690 if (!ParseInt32(Message() << "Environment variable " << env_var, | |
| 11691 string_value, &result)) { | |
| 11692 printf("The default value %s is used.\n", | |
| 11693 (Message() << default_value).GetString().c_str()); | |
| 11694 fflush(stdout); | |
| 11695 return default_value; | |
| 11696 } | |
| 11697 | |
| 11698 return result; | |
| 11699 #endif // defined(GTEST_GET_INT32_FROM_ENV_) | |
| 11700 } | |
| 11701 | |
| 11702 // As a special case for the 'output' flag, if GTEST_OUTPUT is not | |
| 11703 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build | |
| 11704 // system. The value of XML_OUTPUT_FILE is a filename without the | |
| 11705 // "xml:" prefix of GTEST_OUTPUT. | |
| 11706 // Note that this is meant to be called at the call site so it does | |
| 11707 // not check that the flag is 'output' | |
| 11708 // In essence this checks an env variable called XML_OUTPUT_FILE | |
| 11709 // and if it is set we prepend "xml:" to its value, if it not set we return "" | |
| 11710 std::string OutputFlagAlsoCheckEnvVar(){ | |
| 11711 std::string default_value_for_output_flag = ""; | |
| 11712 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); | |
| 11713 if (nullptr != xml_output_file_env) { | |
| 11714 default_value_for_output_flag = std::string("xml:") + xml_output_file_env; | |
| 11715 } | |
| 11716 return default_value_for_output_flag; | |
| 11717 } | |
| 11718 | |
| 11719 // Reads and returns the string environment variable corresponding to | |
| 11720 // the given flag; if it's not set, returns default_value. | |
| 11721 const char* StringFromGTestEnv(const char* flag, const char* default_value) { | |
| 11722 #if defined(GTEST_GET_STRING_FROM_ENV_) | |
| 11723 return GTEST_GET_STRING_FROM_ENV_(flag, default_value); | |
| 11724 #else | |
| 11725 const std::string env_var = FlagToEnvVar(flag); | |
| 11726 const char* const value = posix::GetEnv(env_var.c_str()); | |
| 11727 return value == nullptr ? default_value : value; | |
| 11728 #endif // defined(GTEST_GET_STRING_FROM_ENV_) | |
| 11729 } | |
| 11730 | |
| 11731 } // namespace internal | |
| 11732 } // namespace testing | |
| 11733 // Copyright 2007, Google Inc. | |
| 11734 // All rights reserved. | |
| 11735 // | |
| 11736 // Redistribution and use in source and binary forms, with or without | |
| 11737 // modification, are permitted provided that the following conditions are | |
| 11738 // met: | |
| 11739 // | |
| 11740 // * Redistributions of source code must retain the above copyright | |
| 11741 // notice, this list of conditions and the following disclaimer. | |
| 11742 // * Redistributions in binary form must reproduce the above | |
| 11743 // copyright notice, this list of conditions and the following disclaimer | |
| 11744 // in the documentation and/or other materials provided with the | |
| 11745 // distribution. | |
| 11746 // * Neither the name of Google Inc. nor the names of its | |
| 11747 // contributors may be used to endorse or promote products derived from | |
| 11748 // this software without specific prior written permission. | |
| 11749 // | |
| 11750 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 11751 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 11752 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 11753 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 11754 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 11755 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 11756 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 11757 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 11758 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 11759 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 11760 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 11761 | |
| 11762 | |
| 11763 // Google Test - The Google C++ Testing and Mocking Framework | |
| 11764 // | |
| 11765 // This file implements a universal value printer that can print a | |
| 11766 // value of any type T: | |
| 11767 // | |
| 11768 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); | |
| 11769 // | |
| 11770 // It uses the << operator when possible, and prints the bytes in the | |
| 11771 // object otherwise. A user can override its behavior for a class | |
| 11772 // type Foo by defining either operator<<(::std::ostream&, const Foo&) | |
| 11773 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that | |
| 11774 // defines Foo. | |
| 11775 | |
| 11776 | |
| 11777 #include <stdio.h> | |
| 11778 | |
| 11779 #include <cctype> | |
| 11780 #include <cstdint> | |
| 11781 #include <cwchar> | |
| 11782 #include <ostream> // NOLINT | |
| 11783 #include <string> | |
| 11784 #include <type_traits> | |
| 11785 | |
| 11786 | |
| 11787 namespace testing { | |
| 11788 | |
| 11789 namespace { | |
| 11790 | |
| 11791 using ::std::ostream; | |
| 11792 | |
| 11793 // Prints a segment of bytes in the given object. | |
| 11794 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ | |
| 11795 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ | |
| 11796 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ | |
| 11797 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ | |
| 11798 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, | |
| 11799 size_t count, ostream* os) { | |
| 11800 char text[5] = ""; | |
| 11801 for (size_t i = 0; i != count; i++) { | |
| 11802 const size_t j = start + i; | |
| 11803 if (i != 0) { | |
| 11804 // Organizes the bytes into groups of 2 for easy parsing by | |
| 11805 // human. | |
| 11806 if ((j % 2) == 0) | |
| 11807 *os << ' '; | |
| 11808 else | |
| 11809 *os << '-'; | |
| 11810 } | |
| 11811 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); | |
| 11812 *os << text; | |
| 11813 } | |
| 11814 } | |
| 11815 | |
| 11816 // Prints the bytes in the given value to the given ostream. | |
| 11817 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, | |
| 11818 ostream* os) { | |
| 11819 // Tells the user how big the object is. | |
| 11820 *os << count << "-byte object <"; | |
| 11821 | |
| 11822 const size_t kThreshold = 132; | |
| 11823 const size_t kChunkSize = 64; | |
| 11824 // If the object size is bigger than kThreshold, we'll have to omit | |
| 11825 // some details by printing only the first and the last kChunkSize | |
| 11826 // bytes. | |
| 11827 if (count < kThreshold) { | |
| 11828 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); | |
| 11829 } else { | |
| 11830 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); | |
| 11831 *os << " ... "; | |
| 11832 // Rounds up to 2-byte boundary. | |
| 11833 const size_t resume_pos = (count - kChunkSize + 1)/2*2; | |
| 11834 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); | |
| 11835 } | |
| 11836 *os << ">"; | |
| 11837 } | |
| 11838 | |
| 11839 // Helpers for widening a character to char32_t. Since the standard does not | |
| 11840 // specify if char / wchar_t is signed or unsigned, it is important to first | |
| 11841 // convert it to the unsigned type of the same width before widening it to | |
| 11842 // char32_t. | |
| 11843 template <typename CharType> | |
| 11844 char32_t ToChar32(CharType in) { | |
| 11845 return static_cast<char32_t>( | |
| 11846 static_cast<typename std::make_unsigned<CharType>::type>(in)); | |
| 11847 } | |
| 11848 | |
| 11849 } // namespace | |
| 11850 | |
| 11851 namespace internal { | |
| 11852 | |
| 11853 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the | |
| 11854 // given object. The delegation simplifies the implementation, which | |
| 11855 // uses the << operator and thus is easier done outside of the | |
| 11856 // ::testing::internal namespace, which contains a << operator that | |
| 11857 // sometimes conflicts with the one in STL. | |
| 11858 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, | |
| 11859 ostream* os) { | |
| 11860 PrintBytesInObjectToImpl(obj_bytes, count, os); | |
| 11861 } | |
| 11862 | |
| 11863 // Depending on the value of a char (or wchar_t), we print it in one | |
| 11864 // of three formats: | |
| 11865 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), | |
| 11866 // - as a hexadecimal escape sequence (e.g. '\x7F'), or | |
| 11867 // - as a special escape sequence (e.g. '\r', '\n'). | |
| 11868 enum CharFormat { | |
| 11869 kAsIs, | |
| 11870 kHexEscape, | |
| 11871 kSpecialEscape | |
| 11872 }; | |
| 11873 | |
| 11874 // Returns true if c is a printable ASCII character. We test the | |
| 11875 // value of c directly instead of calling isprint(), which is buggy on | |
| 11876 // Windows Mobile. | |
| 11877 inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; } | |
| 11878 | |
| 11879 // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a | |
| 11880 // character literal without the quotes, escaping it when necessary; returns how | |
| 11881 // c was formatted. | |
| 11882 template <typename Char> | |
| 11883 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { | |
| 11884 const char32_t u_c = ToChar32(c); | |
| 11885 switch (u_c) { | |
| 11886 case L'\0': | |
| 11887 *os << "\\0"; | |
| 11888 break; | |
| 11889 case L'\'': | |
| 11890 *os << "\\'"; | |
| 11891 break; | |
| 11892 case L'\\': | |
| 11893 *os << "\\\\"; | |
| 11894 break; | |
| 11895 case L'\a': | |
| 11896 *os << "\\a"; | |
| 11897 break; | |
| 11898 case L'\b': | |
| 11899 *os << "\\b"; | |
| 11900 break; | |
| 11901 case L'\f': | |
| 11902 *os << "\\f"; | |
| 11903 break; | |
| 11904 case L'\n': | |
| 11905 *os << "\\n"; | |
| 11906 break; | |
| 11907 case L'\r': | |
| 11908 *os << "\\r"; | |
| 11909 break; | |
| 11910 case L'\t': | |
| 11911 *os << "\\t"; | |
| 11912 break; | |
| 11913 case L'\v': | |
| 11914 *os << "\\v"; | |
| 11915 break; | |
| 11916 default: | |
| 11917 if (IsPrintableAscii(u_c)) { | |
| 11918 *os << static_cast<char>(c); | |
| 11919 return kAsIs; | |
| 11920 } else { | |
| 11921 ostream::fmtflags flags = os->flags(); | |
| 11922 *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c); | |
| 11923 os->flags(flags); | |
| 11924 return kHexEscape; | |
| 11925 } | |
| 11926 } | |
| 11927 return kSpecialEscape; | |
| 11928 } | |
| 11929 | |
| 11930 // Prints a char32_t c as if it's part of a string literal, escaping it when | |
| 11931 // necessary; returns how c was formatted. | |
| 11932 static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) { | |
| 11933 switch (c) { | |
| 11934 case L'\'': | |
| 11935 *os << "'"; | |
| 11936 return kAsIs; | |
| 11937 case L'"': | |
| 11938 *os << "\\\""; | |
| 11939 return kSpecialEscape; | |
| 11940 default: | |
| 11941 return PrintAsCharLiteralTo(c, os); | |
| 11942 } | |
| 11943 } | |
| 11944 | |
| 11945 static const char* GetCharWidthPrefix(char) { | |
| 11946 return ""; | |
| 11947 } | |
| 11948 | |
| 11949 static const char* GetCharWidthPrefix(signed char) { | |
| 11950 return ""; | |
| 11951 } | |
| 11952 | |
| 11953 static const char* GetCharWidthPrefix(unsigned char) { | |
| 11954 return ""; | |
| 11955 } | |
| 11956 | |
| 11957 #ifdef __cpp_char8_t | |
| 11958 static const char* GetCharWidthPrefix(char8_t) { | |
| 11959 return "u8"; | |
| 11960 } | |
| 11961 #endif | |
| 11962 | |
| 11963 static const char* GetCharWidthPrefix(char16_t) { | |
| 11964 return "u"; | |
| 11965 } | |
| 11966 | |
| 11967 static const char* GetCharWidthPrefix(char32_t) { | |
| 11968 return "U"; | |
| 11969 } | |
| 11970 | |
| 11971 static const char* GetCharWidthPrefix(wchar_t) { | |
| 11972 return "L"; | |
| 11973 } | |
| 11974 | |
| 11975 // Prints a char c as if it's part of a string literal, escaping it when | |
| 11976 // necessary; returns how c was formatted. | |
| 11977 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { | |
| 11978 return PrintAsStringLiteralTo(ToChar32(c), os); | |
| 11979 } | |
| 11980 | |
| 11981 #ifdef __cpp_char8_t | |
| 11982 static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) { | |
| 11983 return PrintAsStringLiteralTo(ToChar32(c), os); | |
| 11984 } | |
| 11985 #endif | |
| 11986 | |
| 11987 static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) { | |
| 11988 return PrintAsStringLiteralTo(ToChar32(c), os); | |
| 11989 } | |
| 11990 | |
| 11991 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { | |
| 11992 return PrintAsStringLiteralTo(ToChar32(c), os); | |
| 11993 } | |
| 11994 | |
| 11995 // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t) | |
| 11996 // and its code. '\0' is printed as "'\\0'", other unprintable characters are | |
| 11997 // also properly escaped using the standard C++ escape sequence. | |
| 11998 template <typename Char> | |
| 11999 void PrintCharAndCodeTo(Char c, ostream* os) { | |
| 12000 // First, print c as a literal in the most readable form we can find. | |
| 12001 *os << GetCharWidthPrefix(c) << "'"; | |
| 12002 const CharFormat format = PrintAsCharLiteralTo(c, os); | |
| 12003 *os << "'"; | |
| 12004 | |
| 12005 // To aid user debugging, we also print c's code in decimal, unless | |
| 12006 // it's 0 (in which case c was printed as '\\0', making the code | |
| 12007 // obvious). | |
| 12008 if (c == 0) | |
| 12009 return; | |
| 12010 *os << " (" << static_cast<int>(c); | |
| 12011 | |
| 12012 // For more convenience, we print c's code again in hexadecimal, | |
| 12013 // unless c was already printed in the form '\x##' or the code is in | |
| 12014 // [1, 9]. | |
| 12015 if (format == kHexEscape || (1 <= c && c <= 9)) { | |
| 12016 // Do nothing. | |
| 12017 } else { | |
| 12018 *os << ", 0x" << String::FormatHexInt(static_cast<int>(c)); | |
| 12019 } | |
| 12020 *os << ")"; | |
| 12021 } | |
| 12022 | |
| 12023 void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } | |
| 12024 void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } | |
| 12025 | |
| 12026 // Prints a wchar_t as a symbol if it is printable or as its internal | |
| 12027 // code otherwise and also as its code. L'\0' is printed as "L'\\0'". | |
| 12028 void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); } | |
| 12029 | |
| 12030 // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well. | |
| 12031 void PrintTo(char32_t c, ::std::ostream* os) { | |
| 12032 *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4) | |
| 12033 << static_cast<uint32_t>(c); | |
| 12034 } | |
| 12035 | |
| 12036 // Prints the given array of characters to the ostream. CharType must be either | |
| 12037 // char, char8_t, char16_t, char32_t, or wchar_t. | |
| 12038 // The array starts at begin, the length is len, it may include '\0' characters | |
| 12039 // and may not be NUL-terminated. | |
| 12040 template <typename CharType> | |
| 12041 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ | |
| 12042 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ | |
| 12043 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ | |
| 12044 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ | |
| 12045 static CharFormat PrintCharsAsStringTo( | |
| 12046 const CharType* begin, size_t len, ostream* os) { | |
| 12047 const char* const quote_prefix = GetCharWidthPrefix(*begin); | |
| 12048 *os << quote_prefix << "\""; | |
| 12049 bool is_previous_hex = false; | |
| 12050 CharFormat print_format = kAsIs; | |
| 12051 for (size_t index = 0; index < len; ++index) { | |
| 12052 const CharType cur = begin[index]; | |
| 12053 if (is_previous_hex && IsXDigit(cur)) { | |
| 12054 // Previous character is of '\x..' form and this character can be | |
| 12055 // interpreted as another hexadecimal digit in its number. Break string to | |
| 12056 // disambiguate. | |
| 12057 *os << "\" " << quote_prefix << "\""; | |
| 12058 } | |
| 12059 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; | |
| 12060 // Remember if any characters required hex escaping. | |
| 12061 if (is_previous_hex) { | |
| 12062 print_format = kHexEscape; | |
| 12063 } | |
| 12064 } | |
| 12065 *os << "\""; | |
| 12066 return print_format; | |
| 12067 } | |
| 12068 | |
| 12069 // Prints a (const) char/wchar_t array of 'len' elements, starting at address | |
| 12070 // 'begin'. CharType must be either char or wchar_t. | |
| 12071 template <typename CharType> | |
| 12072 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ | |
| 12073 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ | |
| 12074 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ | |
| 12075 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ | |
| 12076 static void UniversalPrintCharArray( | |
| 12077 const CharType* begin, size_t len, ostream* os) { | |
| 12078 // The code | |
| 12079 // const char kFoo[] = "foo"; | |
| 12080 // generates an array of 4, not 3, elements, with the last one being '\0'. | |
| 12081 // | |
| 12082 // Therefore when printing a char array, we don't print the last element if | |
| 12083 // it's '\0', such that the output matches the string literal as it's | |
| 12084 // written in the source code. | |
| 12085 if (len > 0 && begin[len - 1] == '\0') { | |
| 12086 PrintCharsAsStringTo(begin, len - 1, os); | |
| 12087 return; | |
| 12088 } | |
| 12089 | |
| 12090 // If, however, the last element in the array is not '\0', e.g. | |
| 12091 // const char kFoo[] = { 'f', 'o', 'o' }; | |
| 12092 // we must print the entire array. We also print a message to indicate | |
| 12093 // that the array is not NUL-terminated. | |
| 12094 PrintCharsAsStringTo(begin, len, os); | |
| 12095 *os << " (no terminating NUL)"; | |
| 12096 } | |
| 12097 | |
| 12098 // Prints a (const) char array of 'len' elements, starting at address 'begin'. | |
| 12099 void UniversalPrintArray(const char* begin, size_t len, ostream* os) { | |
| 12100 UniversalPrintCharArray(begin, len, os); | |
| 12101 } | |
| 12102 | |
| 12103 #ifdef __cpp_char8_t | |
| 12104 // Prints a (const) char8_t array of 'len' elements, starting at address | |
| 12105 // 'begin'. | |
| 12106 void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) { | |
| 12107 UniversalPrintCharArray(begin, len, os); | |
| 12108 } | |
| 12109 #endif | |
| 12110 | |
| 12111 // Prints a (const) char16_t array of 'len' elements, starting at address | |
| 12112 // 'begin'. | |
| 12113 void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) { | |
| 12114 UniversalPrintCharArray(begin, len, os); | |
| 12115 } | |
| 12116 | |
| 12117 // Prints a (const) char32_t array of 'len' elements, starting at address | |
| 12118 // 'begin'. | |
| 12119 void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) { | |
| 12120 UniversalPrintCharArray(begin, len, os); | |
| 12121 } | |
| 12122 | |
| 12123 // Prints a (const) wchar_t array of 'len' elements, starting at address | |
| 12124 // 'begin'. | |
| 12125 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { | |
| 12126 UniversalPrintCharArray(begin, len, os); | |
| 12127 } | |
| 12128 | |
| 12129 namespace { | |
| 12130 | |
| 12131 // Prints a null-terminated C-style string to the ostream. | |
| 12132 template <typename Char> | |
| 12133 void PrintCStringTo(const Char* s, ostream* os) { | |
| 12134 if (s == nullptr) { | |
| 12135 *os << "NULL"; | |
| 12136 } else { | |
| 12137 *os << ImplicitCast_<const void*>(s) << " pointing to "; | |
| 12138 PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os); | |
| 12139 } | |
| 12140 } | |
| 12141 | |
| 12142 } // anonymous namespace | |
| 12143 | |
| 12144 void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); } | |
| 12145 | |
| 12146 #ifdef __cpp_char8_t | |
| 12147 void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); } | |
| 12148 #endif | |
| 12149 | |
| 12150 void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); } | |
| 12151 | |
| 12152 void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); } | |
| 12153 | |
| 12154 // MSVC compiler can be configured to define whar_t as a typedef | |
| 12155 // of unsigned short. Defining an overload for const wchar_t* in that case | |
| 12156 // would cause pointers to unsigned shorts be printed as wide strings, | |
| 12157 // possibly accessing more memory than intended and causing invalid | |
| 12158 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when | |
| 12159 // wchar_t is implemented as a native type. | |
| 12160 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) | |
| 12161 // Prints the given wide C string to the ostream. | |
| 12162 void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); } | |
| 12163 #endif // wchar_t is native | |
| 12164 | |
| 12165 namespace { | |
| 12166 | |
| 12167 bool ContainsUnprintableControlCodes(const char* str, size_t length) { | |
| 12168 const unsigned char *s = reinterpret_cast<const unsigned char *>(str); | |
| 12169 | |
| 12170 for (size_t i = 0; i < length; i++) { | |
| 12171 unsigned char ch = *s++; | |
| 12172 if (std::iscntrl(ch)) { | |
| 12173 switch (ch) { | |
| 12174 case '\t': | |
| 12175 case '\n': | |
| 12176 case '\r': | |
| 12177 break; | |
| 12178 default: | |
| 12179 return true; | |
| 12180 } | |
| 12181 } | |
| 12182 } | |
| 12183 return false; | |
| 12184 } | |
| 12185 | |
| 12186 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; } | |
| 12187 | |
| 12188 bool IsValidUTF8(const char* str, size_t length) { | |
| 12189 const unsigned char *s = reinterpret_cast<const unsigned char *>(str); | |
| 12190 | |
| 12191 for (size_t i = 0; i < length;) { | |
| 12192 unsigned char lead = s[i++]; | |
| 12193 | |
| 12194 if (lead <= 0x7f) { | |
| 12195 continue; // single-byte character (ASCII) 0..7F | |
| 12196 } | |
| 12197 if (lead < 0xc2) { | |
| 12198 return false; // trail byte or non-shortest form | |
| 12199 } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { | |
| 12200 ++i; // 2-byte character | |
| 12201 } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && | |
| 12202 IsUTF8TrailByte(s[i]) && | |
| 12203 IsUTF8TrailByte(s[i + 1]) && | |
| 12204 // check for non-shortest form and surrogate | |
| 12205 (lead != 0xe0 || s[i] >= 0xa0) && | |
| 12206 (lead != 0xed || s[i] < 0xa0)) { | |
| 12207 i += 2; // 3-byte character | |
| 12208 } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && | |
| 12209 IsUTF8TrailByte(s[i]) && | |
| 12210 IsUTF8TrailByte(s[i + 1]) && | |
| 12211 IsUTF8TrailByte(s[i + 2]) && | |
| 12212 // check for non-shortest form | |
| 12213 (lead != 0xf0 || s[i] >= 0x90) && | |
| 12214 (lead != 0xf4 || s[i] < 0x90)) { | |
| 12215 i += 3; // 4-byte character | |
| 12216 } else { | |
| 12217 return false; | |
| 12218 } | |
| 12219 } | |
| 12220 return true; | |
| 12221 } | |
| 12222 | |
| 12223 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) { | |
| 12224 if (!ContainsUnprintableControlCodes(str, length) && | |
| 12225 IsValidUTF8(str, length)) { | |
| 12226 *os << "\n As Text: \"" << str << "\""; | |
| 12227 } | |
| 12228 } | |
| 12229 | |
| 12230 } // anonymous namespace | |
| 12231 | |
| 12232 void PrintStringTo(const ::std::string& s, ostream* os) { | |
| 12233 if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) { | |
| 12234 if (GTEST_FLAG(print_utf8)) { | |
| 12235 ConditionalPrintAsText(s.data(), s.size(), os); | |
| 12236 } | |
| 12237 } | |
| 12238 } | |
| 12239 | |
| 12240 #ifdef __cpp_char8_t | |
| 12241 void PrintU8StringTo(const ::std::u8string& s, ostream* os) { | |
| 12242 PrintCharsAsStringTo(s.data(), s.size(), os); | |
| 12243 } | |
| 12244 #endif | |
| 12245 | |
| 12246 void PrintU16StringTo(const ::std::u16string& s, ostream* os) { | |
| 12247 PrintCharsAsStringTo(s.data(), s.size(), os); | |
| 12248 } | |
| 12249 | |
| 12250 void PrintU32StringTo(const ::std::u32string& s, ostream* os) { | |
| 12251 PrintCharsAsStringTo(s.data(), s.size(), os); | |
| 12252 } | |
| 12253 | |
| 12254 #if GTEST_HAS_STD_WSTRING | |
| 12255 void PrintWideStringTo(const ::std::wstring& s, ostream* os) { | |
| 12256 PrintCharsAsStringTo(s.data(), s.size(), os); | |
| 12257 } | |
| 12258 #endif // GTEST_HAS_STD_WSTRING | |
| 12259 | |
| 12260 } // namespace internal | |
| 12261 | |
| 12262 } // namespace testing | |
| 12263 // Copyright 2008, Google Inc. | |
| 12264 // All rights reserved. | |
| 12265 // | |
| 12266 // Redistribution and use in source and binary forms, with or without | |
| 12267 // modification, are permitted provided that the following conditions are | |
| 12268 // met: | |
| 12269 // | |
| 12270 // * Redistributions of source code must retain the above copyright | |
| 12271 // notice, this list of conditions and the following disclaimer. | |
| 12272 // * Redistributions in binary form must reproduce the above | |
| 12273 // copyright notice, this list of conditions and the following disclaimer | |
| 12274 // in the documentation and/or other materials provided with the | |
| 12275 // distribution. | |
| 12276 // * Neither the name of Google Inc. nor the names of its | |
| 12277 // contributors may be used to endorse or promote products derived from | |
| 12278 // this software without specific prior written permission. | |
| 12279 // | |
| 12280 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12281 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12282 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12283 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12284 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12285 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12286 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12287 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12288 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12289 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12290 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12291 | |
| 12292 // | |
| 12293 // The Google C++ Testing and Mocking Framework (Google Test) | |
| 12294 | |
| 12295 | |
| 12296 | |
| 12297 namespace testing { | |
| 12298 | |
| 12299 using internal::GetUnitTestImpl; | |
| 12300 | |
| 12301 // Gets the summary of the failure message by omitting the stack trace | |
| 12302 // in it. | |
| 12303 std::string TestPartResult::ExtractSummary(const char* message) { | |
| 12304 const char* const stack_trace = strstr(message, internal::kStackTraceMarker); | |
| 12305 return stack_trace == nullptr ? message : std::string(message, stack_trace); | |
| 12306 } | |
| 12307 | |
| 12308 // Prints a TestPartResult object. | |
| 12309 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { | |
| 12310 return os << internal::FormatFileLocation(result.file_name(), | |
| 12311 result.line_number()) | |
| 12312 << " " | |
| 12313 << (result.type() == TestPartResult::kSuccess | |
| 12314 ? "Success" | |
| 12315 : result.type() == TestPartResult::kSkip | |
| 12316 ? "Skipped" | |
| 12317 : result.type() == TestPartResult::kFatalFailure | |
| 12318 ? "Fatal failure" | |
| 12319 : "Non-fatal failure") | |
| 12320 << ":\n" | |
| 12321 << result.message() << std::endl; | |
| 12322 } | |
| 12323 | |
| 12324 // Appends a TestPartResult to the array. | |
| 12325 void TestPartResultArray::Append(const TestPartResult& result) { | |
| 12326 array_.push_back(result); | |
| 12327 } | |
| 12328 | |
| 12329 // Returns the TestPartResult at the given index (0-based). | |
| 12330 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { | |
| 12331 if (index < 0 || index >= size()) { | |
| 12332 printf("\nInvalid index (%d) into TestPartResultArray.\n", index); | |
| 12333 internal::posix::Abort(); | |
| 12334 } | |
| 12335 | |
| 12336 return array_[static_cast<size_t>(index)]; | |
| 12337 } | |
| 12338 | |
| 12339 // Returns the number of TestPartResult objects in the array. | |
| 12340 int TestPartResultArray::size() const { | |
| 12341 return static_cast<int>(array_.size()); | |
| 12342 } | |
| 12343 | |
| 12344 namespace internal { | |
| 12345 | |
| 12346 HasNewFatalFailureHelper::HasNewFatalFailureHelper() | |
| 12347 : has_new_fatal_failure_(false), | |
| 12348 original_reporter_(GetUnitTestImpl()-> | |
| 12349 GetTestPartResultReporterForCurrentThread()) { | |
| 12350 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); | |
| 12351 } | |
| 12352 | |
| 12353 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { | |
| 12354 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( | |
| 12355 original_reporter_); | |
| 12356 } | |
| 12357 | |
| 12358 void HasNewFatalFailureHelper::ReportTestPartResult( | |
| 12359 const TestPartResult& result) { | |
| 12360 if (result.fatally_failed()) | |
| 12361 has_new_fatal_failure_ = true; | |
| 12362 original_reporter_->ReportTestPartResult(result); | |
| 12363 } | |
| 12364 | |
| 12365 } // namespace internal | |
| 12366 | |
| 12367 } // namespace testing | |
| 12368 // Copyright 2008 Google Inc. | |
| 12369 // All Rights Reserved. | |
| 12370 // | |
| 12371 // Redistribution and use in source and binary forms, with or without | |
| 12372 // modification, are permitted provided that the following conditions are | |
| 12373 // met: | |
| 12374 // | |
| 12375 // * Redistributions of source code must retain the above copyright | |
| 12376 // notice, this list of conditions and the following disclaimer. | |
| 12377 // * Redistributions in binary form must reproduce the above | |
| 12378 // copyright notice, this list of conditions and the following disclaimer | |
| 12379 // in the documentation and/or other materials provided with the | |
| 12380 // distribution. | |
| 12381 // * Neither the name of Google Inc. nor the names of its | |
| 12382 // contributors may be used to endorse or promote products derived from | |
| 12383 // this software without specific prior written permission. | |
| 12384 // | |
| 12385 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12386 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12387 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12388 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12389 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12390 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12391 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12392 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12393 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12394 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12395 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12396 | |
| 12397 | |
| 12398 | |
| 12399 | |
| 12400 namespace testing { | |
| 12401 namespace internal { | |
| 12402 | |
| 12403 // Skips to the first non-space char in str. Returns an empty string if str | |
| 12404 // contains only whitespace characters. | |
| 12405 static const char* SkipSpaces(const char* str) { | |
| 12406 while (IsSpace(*str)) | |
| 12407 str++; | |
| 12408 return str; | |
| 12409 } | |
| 12410 | |
| 12411 static std::vector<std::string> SplitIntoTestNames(const char* src) { | |
| 12412 std::vector<std::string> name_vec; | |
| 12413 src = SkipSpaces(src); | |
| 12414 for (; src != nullptr; src = SkipComma(src)) { | |
| 12415 name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); | |
| 12416 } | |
| 12417 return name_vec; | |
| 12418 } | |
| 12419 | |
| 12420 // Verifies that registered_tests match the test names in | |
| 12421 // registered_tests_; returns registered_tests if successful, or | |
| 12422 // aborts the program otherwise. | |
| 12423 const char* TypedTestSuitePState::VerifyRegisteredTestNames( | |
| 12424 const char* test_suite_name, const char* file, int line, | |
| 12425 const char* registered_tests) { | |
| 12426 RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line)); | |
| 12427 | |
| 12428 typedef RegisteredTestsMap::const_iterator RegisteredTestIter; | |
| 12429 registered_ = true; | |
| 12430 | |
| 12431 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); | |
| 12432 | |
| 12433 Message errors; | |
| 12434 | |
| 12435 std::set<std::string> tests; | |
| 12436 for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); | |
| 12437 name_it != name_vec.end(); ++name_it) { | |
| 12438 const std::string& name = *name_it; | |
| 12439 if (tests.count(name) != 0) { | |
| 12440 errors << "Test " << name << " is listed more than once.\n"; | |
| 12441 continue; | |
| 12442 } | |
| 12443 | |
| 12444 if (registered_tests_.count(name) != 0) { | |
| 12445 tests.insert(name); | |
| 12446 } else { | |
| 12447 errors << "No test named " << name | |
| 12448 << " can be found in this test suite.\n"; | |
| 12449 } | |
| 12450 } | |
| 12451 | |
| 12452 for (RegisteredTestIter it = registered_tests_.begin(); | |
| 12453 it != registered_tests_.end(); | |
| 12454 ++it) { | |
| 12455 if (tests.count(it->first) == 0) { | |
| 12456 errors << "You forgot to list test " << it->first << ".\n"; | |
| 12457 } | |
| 12458 } | |
| 12459 | |
| 12460 const std::string& errors_str = errors.GetString(); | |
| 12461 if (errors_str != "") { | |
| 12462 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), | |
| 12463 errors_str.c_str()); | |
| 12464 fflush(stderr); | |
| 12465 posix::Abort(); | |
| 12466 } | |
| 12467 | |
| 12468 return registered_tests; | |
| 12469 } | |
| 12470 | |
| 12471 } // namespace internal | |
| 12472 } // namespace testing | |
| 12473 // Copyright 2008, Google Inc. | |
| 12474 // All rights reserved. | |
| 12475 // | |
| 12476 // Redistribution and use in source and binary forms, with or without | |
| 12477 // modification, are permitted provided that the following conditions are | |
| 12478 // met: | |
| 12479 // | |
| 12480 // * Redistributions of source code must retain the above copyright | |
| 12481 // notice, this list of conditions and the following disclaimer. | |
| 12482 // * Redistributions in binary form must reproduce the above | |
| 12483 // copyright notice, this list of conditions and the following disclaimer | |
| 12484 // in the documentation and/or other materials provided with the | |
| 12485 // distribution. | |
| 12486 // * Neither the name of Google Inc. nor the names of its | |
| 12487 // contributors may be used to endorse or promote products derived from | |
| 12488 // this software without specific prior written permission. | |
| 12489 // | |
| 12490 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12491 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12492 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12493 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12494 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12495 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12496 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12497 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12498 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12499 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12500 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12501 | |
| 12502 // | |
| 12503 // Google C++ Mocking Framework (Google Mock) | |
| 12504 // | |
| 12505 // This file #includes all Google Mock implementation .cc files. The | |
| 12506 // purpose is to allow a user to build Google Mock by compiling this | |
| 12507 // file alone. | |
| 12508 | |
| 12509 // This line ensures that gmock.h can be compiled on its own, even | |
| 12510 // when it's fused. | |
| 12511 #include "gmock/gmock.h" | |
| 12512 | |
| 12513 // The following lines pull in the real gmock *.cc files. | |
| 12514 // Copyright 2007, Google Inc. | |
| 12515 // All rights reserved. | |
| 12516 // | |
| 12517 // Redistribution and use in source and binary forms, with or without | |
| 12518 // modification, are permitted provided that the following conditions are | |
| 12519 // met: | |
| 12520 // | |
| 12521 // * Redistributions of source code must retain the above copyright | |
| 12522 // notice, this list of conditions and the following disclaimer. | |
| 12523 // * Redistributions in binary form must reproduce the above | |
| 12524 // copyright notice, this list of conditions and the following disclaimer | |
| 12525 // in the documentation and/or other materials provided with the | |
| 12526 // distribution. | |
| 12527 // * Neither the name of Google Inc. nor the names of its | |
| 12528 // contributors may be used to endorse or promote products derived from | |
| 12529 // this software without specific prior written permission. | |
| 12530 // | |
| 12531 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12532 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12533 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12534 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12535 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12536 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12537 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12538 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12539 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12540 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12541 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12542 | |
| 12543 | |
| 12544 // Google Mock - a framework for writing C++ mock classes. | |
| 12545 // | |
| 12546 // This file implements cardinalities. | |
| 12547 | |
| 12548 | |
| 12549 #include <limits.h> | |
| 12550 #include <ostream> // NOLINT | |
| 12551 #include <sstream> | |
| 12552 #include <string> | |
| 12553 | |
| 12554 namespace testing { | |
| 12555 | |
| 12556 namespace { | |
| 12557 | |
| 12558 // Implements the Between(m, n) cardinality. | |
| 12559 class BetweenCardinalityImpl : public CardinalityInterface { | |
| 12560 public: | |
| 12561 BetweenCardinalityImpl(int min, int max) | |
| 12562 : min_(min >= 0 ? min : 0), | |
| 12563 max_(max >= min_ ? max : min_) { | |
| 12564 std::stringstream ss; | |
| 12565 if (min < 0) { | |
| 12566 ss << "The invocation lower bound must be >= 0, " | |
| 12567 << "but is actually " << min << "."; | |
| 12568 internal::Expect(false, __FILE__, __LINE__, ss.str()); | |
| 12569 } else if (max < 0) { | |
| 12570 ss << "The invocation upper bound must be >= 0, " | |
| 12571 << "but is actually " << max << "."; | |
| 12572 internal::Expect(false, __FILE__, __LINE__, ss.str()); | |
| 12573 } else if (min > max) { | |
| 12574 ss << "The invocation upper bound (" << max | |
| 12575 << ") must be >= the invocation lower bound (" << min | |
| 12576 << ")."; | |
| 12577 internal::Expect(false, __FILE__, __LINE__, ss.str()); | |
| 12578 } | |
| 12579 } | |
| 12580 | |
| 12581 // Conservative estimate on the lower/upper bound of the number of | |
| 12582 // calls allowed. | |
| 12583 int ConservativeLowerBound() const override { return min_; } | |
| 12584 int ConservativeUpperBound() const override { return max_; } | |
| 12585 | |
| 12586 bool IsSatisfiedByCallCount(int call_count) const override { | |
| 12587 return min_ <= call_count && call_count <= max_; | |
| 12588 } | |
| 12589 | |
| 12590 bool IsSaturatedByCallCount(int call_count) const override { | |
| 12591 return call_count >= max_; | |
| 12592 } | |
| 12593 | |
| 12594 void DescribeTo(::std::ostream* os) const override; | |
| 12595 | |
| 12596 private: | |
| 12597 const int min_; | |
| 12598 const int max_; | |
| 12599 | |
| 12600 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl); | |
| 12601 }; | |
| 12602 | |
| 12603 // Formats "n times" in a human-friendly way. | |
| 12604 inline std::string FormatTimes(int n) { | |
| 12605 if (n == 1) { | |
| 12606 return "once"; | |
| 12607 } else if (n == 2) { | |
| 12608 return "twice"; | |
| 12609 } else { | |
| 12610 std::stringstream ss; | |
| 12611 ss << n << " times"; | |
| 12612 return ss.str(); | |
| 12613 } | |
| 12614 } | |
| 12615 | |
| 12616 // Describes the Between(m, n) cardinality in human-friendly text. | |
| 12617 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { | |
| 12618 if (min_ == 0) { | |
| 12619 if (max_ == 0) { | |
| 12620 *os << "never called"; | |
| 12621 } else if (max_ == INT_MAX) { | |
| 12622 *os << "called any number of times"; | |
| 12623 } else { | |
| 12624 *os << "called at most " << FormatTimes(max_); | |
| 12625 } | |
| 12626 } else if (min_ == max_) { | |
| 12627 *os << "called " << FormatTimes(min_); | |
| 12628 } else if (max_ == INT_MAX) { | |
| 12629 *os << "called at least " << FormatTimes(min_); | |
| 12630 } else { | |
| 12631 // 0 < min_ < max_ < INT_MAX | |
| 12632 *os << "called between " << min_ << " and " << max_ << " times"; | |
| 12633 } | |
| 12634 } | |
| 12635 | |
| 12636 } // Unnamed namespace | |
| 12637 | |
| 12638 // Describes the given call count to an ostream. | |
| 12639 void Cardinality::DescribeActualCallCountTo(int actual_call_count, | |
| 12640 ::std::ostream* os) { | |
| 12641 if (actual_call_count > 0) { | |
| 12642 *os << "called " << FormatTimes(actual_call_count); | |
| 12643 } else { | |
| 12644 *os << "never called"; | |
| 12645 } | |
| 12646 } | |
| 12647 | |
| 12648 // Creates a cardinality that allows at least n calls. | |
| 12649 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } | |
| 12650 | |
| 12651 // Creates a cardinality that allows at most n calls. | |
| 12652 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } | |
| 12653 | |
| 12654 // Creates a cardinality that allows any number of calls. | |
| 12655 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } | |
| 12656 | |
| 12657 // Creates a cardinality that allows between min and max calls. | |
| 12658 GTEST_API_ Cardinality Between(int min, int max) { | |
| 12659 return Cardinality(new BetweenCardinalityImpl(min, max)); | |
| 12660 } | |
| 12661 | |
| 12662 // Creates a cardinality that allows exactly n calls. | |
| 12663 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } | |
| 12664 | |
| 12665 } // namespace testing | |
| 12666 // Copyright 2007, Google Inc. | |
| 12667 // All rights reserved. | |
| 12668 // | |
| 12669 // Redistribution and use in source and binary forms, with or without | |
| 12670 // modification, are permitted provided that the following conditions are | |
| 12671 // met: | |
| 12672 // | |
| 12673 // * Redistributions of source code must retain the above copyright | |
| 12674 // notice, this list of conditions and the following disclaimer. | |
| 12675 // * Redistributions in binary form must reproduce the above | |
| 12676 // copyright notice, this list of conditions and the following disclaimer | |
| 12677 // in the documentation and/or other materials provided with the | |
| 12678 // distribution. | |
| 12679 // * Neither the name of Google Inc. nor the names of its | |
| 12680 // contributors may be used to endorse or promote products derived from | |
| 12681 // this software without specific prior written permission. | |
| 12682 // | |
| 12683 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12684 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12685 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12686 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12687 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12688 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12689 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12690 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12691 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12692 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12693 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12694 | |
| 12695 | |
| 12696 // Google Mock - a framework for writing C++ mock classes. | |
| 12697 // | |
| 12698 // This file defines some utilities useful for implementing Google | |
| 12699 // Mock. They are subject to change without notice, so please DO NOT | |
| 12700 // USE THEM IN USER CODE. | |
| 12701 | |
| 12702 | |
| 12703 #include <ctype.h> | |
| 12704 #include <ostream> // NOLINT | |
| 12705 #include <string> | |
| 12706 | |
| 12707 namespace testing { | |
| 12708 namespace internal { | |
| 12709 | |
| 12710 // Joins a vector of strings as if they are fields of a tuple; returns | |
| 12711 // the joined string. | |
| 12712 GTEST_API_ std::string JoinAsTuple(const Strings& fields) { | |
| 12713 switch (fields.size()) { | |
| 12714 case 0: | |
| 12715 return ""; | |
| 12716 case 1: | |
| 12717 return fields[0]; | |
| 12718 default: | |
| 12719 std::string result = "(" + fields[0]; | |
| 12720 for (size_t i = 1; i < fields.size(); i++) { | |
| 12721 result += ", "; | |
| 12722 result += fields[i]; | |
| 12723 } | |
| 12724 result += ")"; | |
| 12725 return result; | |
| 12726 } | |
| 12727 } | |
| 12728 | |
| 12729 // Converts an identifier name to a space-separated list of lower-case | |
| 12730 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is | |
| 12731 // treated as one word. For example, both "FooBar123" and | |
| 12732 // "foo_bar_123" are converted to "foo bar 123". | |
| 12733 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { | |
| 12734 std::string result; | |
| 12735 char prev_char = '\0'; | |
| 12736 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { | |
| 12737 // We don't care about the current locale as the input is | |
| 12738 // guaranteed to be a valid C++ identifier name. | |
| 12739 const bool starts_new_word = IsUpper(*p) || | |
| 12740 (!IsAlpha(prev_char) && IsLower(*p)) || | |
| 12741 (!IsDigit(prev_char) && IsDigit(*p)); | |
| 12742 | |
| 12743 if (IsAlNum(*p)) { | |
| 12744 if (starts_new_word && result != "") | |
| 12745 result += ' '; | |
| 12746 result += ToLower(*p); | |
| 12747 } | |
| 12748 } | |
| 12749 return result; | |
| 12750 } | |
| 12751 | |
| 12752 // This class reports Google Mock failures as Google Test failures. A | |
| 12753 // user can define another class in a similar fashion if they intend to | |
| 12754 // use Google Mock with a testing framework other than Google Test. | |
| 12755 class GoogleTestFailureReporter : public FailureReporterInterface { | |
| 12756 public: | |
| 12757 void ReportFailure(FailureType type, const char* file, int line, | |
| 12758 const std::string& message) override { | |
| 12759 AssertHelper(type == kFatal ? | |
| 12760 TestPartResult::kFatalFailure : | |
| 12761 TestPartResult::kNonFatalFailure, | |
| 12762 file, | |
| 12763 line, | |
| 12764 message.c_str()) = Message(); | |
| 12765 if (type == kFatal) { | |
| 12766 posix::Abort(); | |
| 12767 } | |
| 12768 } | |
| 12769 }; | |
| 12770 | |
| 12771 // Returns the global failure reporter. Will create a | |
| 12772 // GoogleTestFailureReporter and return it the first time called. | |
| 12773 GTEST_API_ FailureReporterInterface* GetFailureReporter() { | |
| 12774 // Points to the global failure reporter used by Google Mock. gcc | |
| 12775 // guarantees that the following use of failure_reporter is | |
| 12776 // thread-safe. We may need to add additional synchronization to | |
| 12777 // protect failure_reporter if we port Google Mock to other | |
| 12778 // compilers. | |
| 12779 static FailureReporterInterface* const failure_reporter = | |
| 12780 new GoogleTestFailureReporter(); | |
| 12781 return failure_reporter; | |
| 12782 } | |
| 12783 | |
| 12784 // Protects global resources (stdout in particular) used by Log(). | |
| 12785 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); | |
| 12786 | |
| 12787 // Returns true if and only if a log with the given severity is visible | |
| 12788 // according to the --gmock_verbose flag. | |
| 12789 GTEST_API_ bool LogIsVisible(LogSeverity severity) { | |
| 12790 if (GMOCK_FLAG(verbose) == kInfoVerbosity) { | |
| 12791 // Always show the log if --gmock_verbose=info. | |
| 12792 return true; | |
| 12793 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) { | |
| 12794 // Always hide it if --gmock_verbose=error. | |
| 12795 return false; | |
| 12796 } else { | |
| 12797 // If --gmock_verbose is neither "info" nor "error", we treat it | |
| 12798 // as "warning" (its default value). | |
| 12799 return severity == kWarning; | |
| 12800 } | |
| 12801 } | |
| 12802 | |
| 12803 // Prints the given message to stdout if and only if 'severity' >= the level | |
| 12804 // specified by the --gmock_verbose flag. If stack_frames_to_skip >= | |
| 12805 // 0, also prints the stack trace excluding the top | |
| 12806 // stack_frames_to_skip frames. In opt mode, any positive | |
| 12807 // stack_frames_to_skip is treated as 0, since we don't know which | |
| 12808 // function calls will be inlined by the compiler and need to be | |
| 12809 // conservative. | |
| 12810 GTEST_API_ void Log(LogSeverity severity, const std::string& message, | |
| 12811 int stack_frames_to_skip) { | |
| 12812 if (!LogIsVisible(severity)) | |
| 12813 return; | |
| 12814 | |
| 12815 // Ensures that logs from different threads don't interleave. | |
| 12816 MutexLock l(&g_log_mutex); | |
| 12817 | |
| 12818 if (severity == kWarning) { | |
| 12819 // Prints a GMOCK WARNING marker to make the warnings easily searchable. | |
| 12820 std::cout << "\nGMOCK WARNING:"; | |
| 12821 } | |
| 12822 // Pre-pends a new-line to message if it doesn't start with one. | |
| 12823 if (message.empty() || message[0] != '\n') { | |
| 12824 std::cout << "\n"; | |
| 12825 } | |
| 12826 std::cout << message; | |
| 12827 if (stack_frames_to_skip >= 0) { | |
| 12828 #ifdef NDEBUG | |
| 12829 // In opt mode, we have to be conservative and skip no stack frame. | |
| 12830 const int actual_to_skip = 0; | |
| 12831 #else | |
| 12832 // In dbg mode, we can do what the caller tell us to do (plus one | |
| 12833 // for skipping this function's stack frame). | |
| 12834 const int actual_to_skip = stack_frames_to_skip + 1; | |
| 12835 #endif // NDEBUG | |
| 12836 | |
| 12837 // Appends a new-line to message if it doesn't end with one. | |
| 12838 if (!message.empty() && *message.rbegin() != '\n') { | |
| 12839 std::cout << "\n"; | |
| 12840 } | |
| 12841 std::cout << "Stack trace:\n" | |
| 12842 << ::testing::internal::GetCurrentOsStackTraceExceptTop( | |
| 12843 ::testing::UnitTest::GetInstance(), actual_to_skip); | |
| 12844 } | |
| 12845 std::cout << ::std::flush; | |
| 12846 } | |
| 12847 | |
| 12848 GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); } | |
| 12849 | |
| 12850 GTEST_API_ void IllegalDoDefault(const char* file, int line) { | |
| 12851 internal::Assert( | |
| 12852 false, file, line, | |
| 12853 "You are using DoDefault() inside a composite action like " | |
| 12854 "DoAll() or WithArgs(). This is not supported for technical " | |
| 12855 "reasons. Please instead spell out the default action, or " | |
| 12856 "assign the default action to an Action variable and use " | |
| 12857 "the variable in various places."); | |
| 12858 } | |
| 12859 | |
| 12860 } // namespace internal | |
| 12861 } // namespace testing | |
| 12862 // Copyright 2007, Google Inc. | |
| 12863 // All rights reserved. | |
| 12864 // | |
| 12865 // Redistribution and use in source and binary forms, with or without | |
| 12866 // modification, are permitted provided that the following conditions are | |
| 12867 // met: | |
| 12868 // | |
| 12869 // * Redistributions of source code must retain the above copyright | |
| 12870 // notice, this list of conditions and the following disclaimer. | |
| 12871 // * Redistributions in binary form must reproduce the above | |
| 12872 // copyright notice, this list of conditions and the following disclaimer | |
| 12873 // in the documentation and/or other materials provided with the | |
| 12874 // distribution. | |
| 12875 // * Neither the name of Google Inc. nor the names of its | |
| 12876 // contributors may be used to endorse or promote products derived from | |
| 12877 // this software without specific prior written permission. | |
| 12878 // | |
| 12879 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 12880 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 12881 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 12882 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 12883 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 12884 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 12885 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 12886 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 12887 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 12888 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 12889 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 12890 | |
| 12891 | |
| 12892 // Google Mock - a framework for writing C++ mock classes. | |
| 12893 // | |
| 12894 // This file implements Matcher<const string&>, Matcher<string>, and | |
| 12895 // utilities for defining matchers. | |
| 12896 | |
| 12897 | |
| 12898 #include <string.h> | |
| 12899 #include <iostream> | |
| 12900 #include <sstream> | |
| 12901 #include <string> | |
| 12902 | |
| 12903 namespace testing { | |
| 12904 namespace internal { | |
| 12905 | |
| 12906 // Returns the description for a matcher defined using the MATCHER*() | |
| 12907 // macro where the user-supplied description string is "", if | |
| 12908 // 'negation' is false; otherwise returns the description of the | |
| 12909 // negation of the matcher. 'param_values' contains a list of strings | |
| 12910 // that are the print-out of the matcher's parameters. | |
| 12911 GTEST_API_ std::string FormatMatcherDescription(bool negation, | |
| 12912 const char* matcher_name, | |
| 12913 const Strings& param_values) { | |
| 12914 std::string result = ConvertIdentifierNameToWords(matcher_name); | |
| 12915 if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values); | |
| 12916 return negation ? "not (" + result + ")" : result; | |
| 12917 } | |
| 12918 | |
| 12919 // FindMaxBipartiteMatching and its helper class. | |
| 12920 // | |
| 12921 // Uses the well-known Ford-Fulkerson max flow method to find a maximum | |
| 12922 // bipartite matching. Flow is considered to be from left to right. | |
| 12923 // There is an implicit source node that is connected to all of the left | |
| 12924 // nodes, and an implicit sink node that is connected to all of the | |
| 12925 // right nodes. All edges have unit capacity. | |
| 12926 // | |
| 12927 // Neither the flow graph nor the residual flow graph are represented | |
| 12928 // explicitly. Instead, they are implied by the information in 'graph' and | |
| 12929 // a vector<int> called 'left_' whose elements are initialized to the | |
| 12930 // value kUnused. This represents the initial state of the algorithm, | |
| 12931 // where the flow graph is empty, and the residual flow graph has the | |
| 12932 // following edges: | |
| 12933 // - An edge from source to each left_ node | |
| 12934 // - An edge from each right_ node to sink | |
| 12935 // - An edge from each left_ node to each right_ node, if the | |
| 12936 // corresponding edge exists in 'graph'. | |
| 12937 // | |
| 12938 // When the TryAugment() method adds a flow, it sets left_[l] = r for some | |
| 12939 // nodes l and r. This induces the following changes: | |
| 12940 // - The edges (source, l), (l, r), and (r, sink) are added to the | |
| 12941 // flow graph. | |
| 12942 // - The same three edges are removed from the residual flow graph. | |
| 12943 // - The reverse edges (l, source), (r, l), and (sink, r) are added | |
| 12944 // to the residual flow graph, which is a directional graph | |
| 12945 // representing unused flow capacity. | |
| 12946 // | |
| 12947 // When the method augments a flow (moving left_[l] from some r1 to some | |
| 12948 // other r2), this can be thought of as "undoing" the above steps with | |
| 12949 // respect to r1 and "redoing" them with respect to r2. | |
| 12950 // | |
| 12951 // It bears repeating that the flow graph and residual flow graph are | |
| 12952 // never represented explicitly, but can be derived by looking at the | |
| 12953 // information in 'graph' and in left_. | |
| 12954 // | |
| 12955 // As an optimization, there is a second vector<int> called right_ which | |
| 12956 // does not provide any new information. Instead, it enables more | |
| 12957 // efficient queries about edges entering or leaving the right-side nodes | |
| 12958 // of the flow or residual flow graphs. The following invariants are | |
| 12959 // maintained: | |
| 12960 // | |
| 12961 // left[l] == kUnused or right[left[l]] == l | |
| 12962 // right[r] == kUnused or left[right[r]] == r | |
| 12963 // | |
| 12964 // . [ source ] . | |
| 12965 // . ||| . | |
| 12966 // . ||| . | |
| 12967 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ . | |
| 12968 // . || | | . | |
| 12969 // . |\---> left[1]=-1 \--> right[1]=0 ---\| . | |
| 12970 // . | || . | |
| 12971 // . \----> left[2]=2 ------> right[2]=2 --\|| . | |
| 12972 // . ||| . | |
| 12973 // . elements matchers vvv . | |
| 12974 // . [ sink ] . | |
| 12975 // | |
| 12976 // See Also: | |
| 12977 // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". | |
| 12978 // "Introduction to Algorithms (Second ed.)", pp. 651-664. | |
| 12979 // [2] "Ford-Fulkerson algorithm", Wikipedia, | |
| 12980 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' | |
| 12981 class MaxBipartiteMatchState { | |
| 12982 public: | |
| 12983 explicit MaxBipartiteMatchState(const MatchMatrix& graph) | |
| 12984 : graph_(&graph), | |
| 12985 left_(graph_->LhsSize(), kUnused), | |
| 12986 right_(graph_->RhsSize(), kUnused) {} | |
| 12987 | |
| 12988 // Returns the edges of a maximal match, each in the form {left, right}. | |
| 12989 ElementMatcherPairs Compute() { | |
| 12990 // 'seen' is used for path finding { 0: unseen, 1: seen }. | |
| 12991 ::std::vector<char> seen; | |
| 12992 // Searches the residual flow graph for a path from each left node to | |
| 12993 // the sink in the residual flow graph, and if one is found, add flow | |
| 12994 // to the graph. It's okay to search through the left nodes once. The | |
| 12995 // edge from the implicit source node to each previously-visited left | |
| 12996 // node will have flow if that left node has any path to the sink | |
| 12997 // whatsoever. Subsequent augmentations can only add flow to the | |
| 12998 // network, and cannot take away that previous flow unit from the source. | |
| 12999 // Since the source-to-left edge can only carry one flow unit (or, | |
| 13000 // each element can be matched to only one matcher), there is no need | |
| 13001 // to visit the left nodes more than once looking for augmented paths. | |
| 13002 // The flow is known to be possible or impossible by looking at the | |
| 13003 // node once. | |
| 13004 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { | |
| 13005 // Reset the path-marking vector and try to find a path from | |
| 13006 // source to sink starting at the left_[ilhs] node. | |
| 13007 GTEST_CHECK_(left_[ilhs] == kUnused) | |
| 13008 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs]; | |
| 13009 // 'seen' initialized to 'graph_->RhsSize()' copies of 0. | |
| 13010 seen.assign(graph_->RhsSize(), 0); | |
| 13011 TryAugment(ilhs, &seen); | |
| 13012 } | |
| 13013 ElementMatcherPairs result; | |
| 13014 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) { | |
| 13015 size_t irhs = left_[ilhs]; | |
| 13016 if (irhs == kUnused) continue; | |
| 13017 result.push_back(ElementMatcherPair(ilhs, irhs)); | |
| 13018 } | |
| 13019 return result; | |
| 13020 } | |
| 13021 | |
| 13022 private: | |
| 13023 static const size_t kUnused = static_cast<size_t>(-1); | |
| 13024 | |
| 13025 // Perform a depth-first search from left node ilhs to the sink. If a | |
| 13026 // path is found, flow is added to the network by linking the left and | |
| 13027 // right vector elements corresponding each segment of the path. | |
| 13028 // Returns true if a path to sink was found, which means that a unit of | |
| 13029 // flow was added to the network. The 'seen' vector elements correspond | |
| 13030 // to right nodes and are marked to eliminate cycles from the search. | |
| 13031 // | |
| 13032 // Left nodes will only be explored at most once because they | |
| 13033 // are accessible from at most one right node in the residual flow | |
| 13034 // graph. | |
| 13035 // | |
| 13036 // Note that left_[ilhs] is the only element of left_ that TryAugment will | |
| 13037 // potentially transition from kUnused to another value. Any other | |
| 13038 // left_ element holding kUnused before TryAugment will be holding it | |
| 13039 // when TryAugment returns. | |
| 13040 // | |
| 13041 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) { | |
| 13042 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { | |
| 13043 if ((*seen)[irhs]) continue; | |
| 13044 if (!graph_->HasEdge(ilhs, irhs)) continue; | |
| 13045 // There's an available edge from ilhs to irhs. | |
| 13046 (*seen)[irhs] = 1; | |
| 13047 // Next a search is performed to determine whether | |
| 13048 // this edge is a dead end or leads to the sink. | |
| 13049 // | |
| 13050 // right_[irhs] == kUnused means that there is residual flow from | |
| 13051 // right node irhs to the sink, so we can use that to finish this | |
| 13052 // flow path and return success. | |
| 13053 // | |
| 13054 // Otherwise there is residual flow to some ilhs. We push flow | |
| 13055 // along that path and call ourselves recursively to see if this | |
| 13056 // ultimately leads to sink. | |
| 13057 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) { | |
| 13058 // Add flow from left_[ilhs] to right_[irhs]. | |
| 13059 left_[ilhs] = irhs; | |
| 13060 right_[irhs] = ilhs; | |
| 13061 return true; | |
| 13062 } | |
| 13063 } | |
| 13064 return false; | |
| 13065 } | |
| 13066 | |
| 13067 const MatchMatrix* graph_; // not owned | |
| 13068 // Each element of the left_ vector represents a left hand side node | |
| 13069 // (i.e. an element) and each element of right_ is a right hand side | |
| 13070 // node (i.e. a matcher). The values in the left_ vector indicate | |
| 13071 // outflow from that node to a node on the right_ side. The values | |
| 13072 // in the right_ indicate inflow, and specify which left_ node is | |
| 13073 // feeding that right_ node, if any. For example, left_[3] == 1 means | |
| 13074 // there's a flow from element #3 to matcher #1. Such a flow would also | |
| 13075 // be redundantly represented in the right_ vector as right_[1] == 3. | |
| 13076 // Elements of left_ and right_ are either kUnused or mutually | |
| 13077 // referent. Mutually referent means that left_[right_[i]] = i and | |
| 13078 // right_[left_[i]] = i. | |
| 13079 ::std::vector<size_t> left_; | |
| 13080 ::std::vector<size_t> right_; | |
| 13081 }; | |
| 13082 | |
| 13083 const size_t MaxBipartiteMatchState::kUnused; | |
| 13084 | |
| 13085 GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) { | |
| 13086 return MaxBipartiteMatchState(g).Compute(); | |
| 13087 } | |
| 13088 | |
| 13089 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, | |
| 13090 ::std::ostream* stream) { | |
| 13091 typedef ElementMatcherPairs::const_iterator Iter; | |
| 13092 ::std::ostream& os = *stream; | |
| 13093 os << "{"; | |
| 13094 const char* sep = ""; | |
| 13095 for (Iter it = pairs.begin(); it != pairs.end(); ++it) { | |
| 13096 os << sep << "\n (" | |
| 13097 << "element #" << it->first << ", " | |
| 13098 << "matcher #" << it->second << ")"; | |
| 13099 sep = ","; | |
| 13100 } | |
| 13101 os << "\n}"; | |
| 13102 } | |
| 13103 | |
| 13104 bool MatchMatrix::NextGraph() { | |
| 13105 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { | |
| 13106 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { | |
| 13107 char& b = matched_[SpaceIndex(ilhs, irhs)]; | |
| 13108 if (!b) { | |
| 13109 b = 1; | |
| 13110 return true; | |
| 13111 } | |
| 13112 b = 0; | |
| 13113 } | |
| 13114 } | |
| 13115 return false; | |
| 13116 } | |
| 13117 | |
| 13118 void MatchMatrix::Randomize() { | |
| 13119 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { | |
| 13120 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { | |
| 13121 char& b = matched_[SpaceIndex(ilhs, irhs)]; | |
| 13122 b = static_cast<char>(rand() & 1); // NOLINT | |
| 13123 } | |
| 13124 } | |
| 13125 } | |
| 13126 | |
| 13127 std::string MatchMatrix::DebugString() const { | |
| 13128 ::std::stringstream ss; | |
| 13129 const char* sep = ""; | |
| 13130 for (size_t i = 0; i < LhsSize(); ++i) { | |
| 13131 ss << sep; | |
| 13132 for (size_t j = 0; j < RhsSize(); ++j) { | |
| 13133 ss << HasEdge(i, j); | |
| 13134 } | |
| 13135 sep = ";"; | |
| 13136 } | |
| 13137 return ss.str(); | |
| 13138 } | |
| 13139 | |
| 13140 void UnorderedElementsAreMatcherImplBase::DescribeToImpl( | |
| 13141 ::std::ostream* os) const { | |
| 13142 switch (match_flags()) { | |
| 13143 case UnorderedMatcherRequire::ExactMatch: | |
| 13144 if (matcher_describers_.empty()) { | |
| 13145 *os << "is empty"; | |
| 13146 return; | |
| 13147 } | |
| 13148 if (matcher_describers_.size() == 1) { | |
| 13149 *os << "has " << Elements(1) << " and that element "; | |
| 13150 matcher_describers_[0]->DescribeTo(os); | |
| 13151 return; | |
| 13152 } | |
| 13153 *os << "has " << Elements(matcher_describers_.size()) | |
| 13154 << " and there exists some permutation of elements such that:\n"; | |
| 13155 break; | |
| 13156 case UnorderedMatcherRequire::Superset: | |
| 13157 *os << "a surjection from elements to requirements exists such that:\n"; | |
| 13158 break; | |
| 13159 case UnorderedMatcherRequire::Subset: | |
| 13160 *os << "an injection from elements to requirements exists such that:\n"; | |
| 13161 break; | |
| 13162 } | |
| 13163 | |
| 13164 const char* sep = ""; | |
| 13165 for (size_t i = 0; i != matcher_describers_.size(); ++i) { | |
| 13166 *os << sep; | |
| 13167 if (match_flags() == UnorderedMatcherRequire::ExactMatch) { | |
| 13168 *os << " - element #" << i << " "; | |
| 13169 } else { | |
| 13170 *os << " - an element "; | |
| 13171 } | |
| 13172 matcher_describers_[i]->DescribeTo(os); | |
| 13173 if (match_flags() == UnorderedMatcherRequire::ExactMatch) { | |
| 13174 sep = ", and\n"; | |
| 13175 } else { | |
| 13176 sep = "\n"; | |
| 13177 } | |
| 13178 } | |
| 13179 } | |
| 13180 | |
| 13181 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( | |
| 13182 ::std::ostream* os) const { | |
| 13183 switch (match_flags()) { | |
| 13184 case UnorderedMatcherRequire::ExactMatch: | |
| 13185 if (matcher_describers_.empty()) { | |
| 13186 *os << "isn't empty"; | |
| 13187 return; | |
| 13188 } | |
| 13189 if (matcher_describers_.size() == 1) { | |
| 13190 *os << "doesn't have " << Elements(1) << ", or has " << Elements(1) | |
| 13191 << " that "; | |
| 13192 matcher_describers_[0]->DescribeNegationTo(os); | |
| 13193 return; | |
| 13194 } | |
| 13195 *os << "doesn't have " << Elements(matcher_describers_.size()) | |
| 13196 << ", or there exists no permutation of elements such that:\n"; | |
| 13197 break; | |
| 13198 case UnorderedMatcherRequire::Superset: | |
| 13199 *os << "no surjection from elements to requirements exists such that:\n"; | |
| 13200 break; | |
| 13201 case UnorderedMatcherRequire::Subset: | |
| 13202 *os << "no injection from elements to requirements exists such that:\n"; | |
| 13203 break; | |
| 13204 } | |
| 13205 const char* sep = ""; | |
| 13206 for (size_t i = 0; i != matcher_describers_.size(); ++i) { | |
| 13207 *os << sep; | |
| 13208 if (match_flags() == UnorderedMatcherRequire::ExactMatch) { | |
| 13209 *os << " - element #" << i << " "; | |
| 13210 } else { | |
| 13211 *os << " - an element "; | |
| 13212 } | |
| 13213 matcher_describers_[i]->DescribeTo(os); | |
| 13214 if (match_flags() == UnorderedMatcherRequire::ExactMatch) { | |
| 13215 sep = ", and\n"; | |
| 13216 } else { | |
| 13217 sep = "\n"; | |
| 13218 } | |
| 13219 } | |
| 13220 } | |
| 13221 | |
| 13222 // Checks that all matchers match at least one element, and that all | |
| 13223 // elements match at least one matcher. This enables faster matching | |
| 13224 // and better error reporting. | |
| 13225 // Returns false, writing an explanation to 'listener', if and only | |
| 13226 // if the success criteria are not met. | |
| 13227 bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix( | |
| 13228 const ::std::vector<std::string>& element_printouts, | |
| 13229 const MatchMatrix& matrix, MatchResultListener* listener) const { | |
| 13230 bool result = true; | |
| 13231 ::std::vector<char> element_matched(matrix.LhsSize(), 0); | |
| 13232 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0); | |
| 13233 | |
| 13234 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) { | |
| 13235 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) { | |
| 13236 char matched = matrix.HasEdge(ilhs, irhs); | |
| 13237 element_matched[ilhs] |= matched; | |
| 13238 matcher_matched[irhs] |= matched; | |
| 13239 } | |
| 13240 } | |
| 13241 | |
| 13242 if (match_flags() & UnorderedMatcherRequire::Superset) { | |
| 13243 const char* sep = | |
| 13244 "where the following matchers don't match any elements:\n"; | |
| 13245 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) { | |
| 13246 if (matcher_matched[mi]) continue; | |
| 13247 result = false; | |
| 13248 if (listener->IsInterested()) { | |
| 13249 *listener << sep << "matcher #" << mi << ": "; | |
| 13250 matcher_describers_[mi]->DescribeTo(listener->stream()); | |
| 13251 sep = ",\n"; | |
| 13252 } | |
| 13253 } | |
| 13254 } | |
| 13255 | |
| 13256 if (match_flags() & UnorderedMatcherRequire::Subset) { | |
| 13257 const char* sep = | |
| 13258 "where the following elements don't match any matchers:\n"; | |
| 13259 const char* outer_sep = ""; | |
| 13260 if (!result) { | |
| 13261 outer_sep = "\nand "; | |
| 13262 } | |
| 13263 for (size_t ei = 0; ei < element_matched.size(); ++ei) { | |
| 13264 if (element_matched[ei]) continue; | |
| 13265 result = false; | |
| 13266 if (listener->IsInterested()) { | |
| 13267 *listener << outer_sep << sep << "element #" << ei << ": " | |
| 13268 << element_printouts[ei]; | |
| 13269 sep = ",\n"; | |
| 13270 outer_sep = ""; | |
| 13271 } | |
| 13272 } | |
| 13273 } | |
| 13274 return result; | |
| 13275 } | |
| 13276 | |
| 13277 bool UnorderedElementsAreMatcherImplBase::FindPairing( | |
| 13278 const MatchMatrix& matrix, MatchResultListener* listener) const { | |
| 13279 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); | |
| 13280 | |
| 13281 size_t max_flow = matches.size(); | |
| 13282 if ((match_flags() & UnorderedMatcherRequire::Superset) && | |
| 13283 max_flow < matrix.RhsSize()) { | |
| 13284 if (listener->IsInterested()) { | |
| 13285 *listener << "where no permutation of the elements can satisfy all " | |
| 13286 "matchers, and the closest match is " | |
| 13287 << max_flow << " of " << matrix.RhsSize() | |
| 13288 << " matchers with the pairings:\n"; | |
| 13289 LogElementMatcherPairVec(matches, listener->stream()); | |
| 13290 } | |
| 13291 return false; | |
| 13292 } | |
| 13293 if ((match_flags() & UnorderedMatcherRequire::Subset) && | |
| 13294 max_flow < matrix.LhsSize()) { | |
| 13295 if (listener->IsInterested()) { | |
| 13296 *listener | |
| 13297 << "where not all elements can be matched, and the closest match is " | |
| 13298 << max_flow << " of " << matrix.RhsSize() | |
| 13299 << " matchers with the pairings:\n"; | |
| 13300 LogElementMatcherPairVec(matches, listener->stream()); | |
| 13301 } | |
| 13302 return false; | |
| 13303 } | |
| 13304 | |
| 13305 if (matches.size() > 1) { | |
| 13306 if (listener->IsInterested()) { | |
| 13307 const char* sep = "where:\n"; | |
| 13308 for (size_t mi = 0; mi < matches.size(); ++mi) { | |
| 13309 *listener << sep << " - element #" << matches[mi].first | |
| 13310 << " is matched by matcher #" << matches[mi].second; | |
| 13311 sep = ",\n"; | |
| 13312 } | |
| 13313 } | |
| 13314 } | |
| 13315 return true; | |
| 13316 } | |
| 13317 | |
| 13318 } // namespace internal | |
| 13319 } // namespace testing | |
| 13320 // Copyright 2007, Google Inc. | |
| 13321 // All rights reserved. | |
| 13322 // | |
| 13323 // Redistribution and use in source and binary forms, with or without | |
| 13324 // modification, are permitted provided that the following conditions are | |
| 13325 // met: | |
| 13326 // | |
| 13327 // * Redistributions of source code must retain the above copyright | |
| 13328 // notice, this list of conditions and the following disclaimer. | |
| 13329 // * Redistributions in binary form must reproduce the above | |
| 13330 // copyright notice, this list of conditions and the following disclaimer | |
| 13331 // in the documentation and/or other materials provided with the | |
| 13332 // distribution. | |
| 13333 // * Neither the name of Google Inc. nor the names of its | |
| 13334 // contributors may be used to endorse or promote products derived from | |
| 13335 // this software without specific prior written permission. | |
| 13336 // | |
| 13337 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 13338 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 13339 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 13340 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 13341 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 13342 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 13343 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 13344 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 13345 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 13346 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 13347 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 13348 | |
| 13349 | |
| 13350 // Google Mock - a framework for writing C++ mock classes. | |
| 13351 // | |
| 13352 // This file implements the spec builder syntax (ON_CALL and | |
| 13353 // EXPECT_CALL). | |
| 13354 | |
| 13355 | |
| 13356 #include <stdlib.h> | |
| 13357 | |
| 13358 #include <iostream> // NOLINT | |
| 13359 #include <map> | |
| 13360 #include <memory> | |
| 13361 #include <set> | |
| 13362 #include <string> | |
| 13363 #include <vector> | |
| 13364 | |
| 13365 | |
| 13366 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC | |
| 13367 # include <unistd.h> // NOLINT | |
| 13368 #endif | |
| 13369 | |
| 13370 // Silence C4800 (C4800: 'int *const ': forcing value | |
| 13371 // to bool 'true' or 'false') for MSVC 15 | |
| 13372 #ifdef _MSC_VER | |
| 13373 #if _MSC_VER == 1900 | |
| 13374 # pragma warning(push) | |
| 13375 # pragma warning(disable:4800) | |
| 13376 #endif | |
| 13377 #endif | |
| 13378 | |
| 13379 namespace testing { | |
| 13380 namespace internal { | |
| 13381 | |
| 13382 // Protects the mock object registry (in class Mock), all function | |
| 13383 // mockers, and all expectations. | |
| 13384 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); | |
| 13385 | |
| 13386 // Logs a message including file and line number information. | |
| 13387 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, | |
| 13388 const char* file, int line, | |
| 13389 const std::string& message) { | |
| 13390 ::std::ostringstream s; | |
| 13391 s << internal::FormatFileLocation(file, line) << " " << message | |
| 13392 << ::std::endl; | |
| 13393 Log(severity, s.str(), 0); | |
| 13394 } | |
| 13395 | |
| 13396 // Constructs an ExpectationBase object. | |
| 13397 ExpectationBase::ExpectationBase(const char* a_file, int a_line, | |
| 13398 const std::string& a_source_text) | |
| 13399 : file_(a_file), | |
| 13400 line_(a_line), | |
| 13401 source_text_(a_source_text), | |
| 13402 cardinality_specified_(false), | |
| 13403 cardinality_(Exactly(1)), | |
| 13404 call_count_(0), | |
| 13405 retired_(false), | |
| 13406 extra_matcher_specified_(false), | |
| 13407 repeated_action_specified_(false), | |
| 13408 retires_on_saturation_(false), | |
| 13409 last_clause_(kNone), | |
| 13410 action_count_checked_(false) {} | |
| 13411 | |
| 13412 // Destructs an ExpectationBase object. | |
| 13413 ExpectationBase::~ExpectationBase() {} | |
| 13414 | |
| 13415 // Explicitly specifies the cardinality of this expectation. Used by | |
| 13416 // the subclasses to implement the .Times() clause. | |
| 13417 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { | |
| 13418 cardinality_specified_ = true; | |
| 13419 cardinality_ = a_cardinality; | |
| 13420 } | |
| 13421 | |
| 13422 // Retires all pre-requisites of this expectation. | |
| 13423 void ExpectationBase::RetireAllPreRequisites() | |
| 13424 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { | |
| 13425 if (is_retired()) { | |
| 13426 // We can take this short-cut as we never retire an expectation | |
| 13427 // until we have retired all its pre-requisites. | |
| 13428 return; | |
| 13429 } | |
| 13430 | |
| 13431 ::std::vector<ExpectationBase*> expectations(1, this); | |
| 13432 while (!expectations.empty()) { | |
| 13433 ExpectationBase* exp = expectations.back(); | |
| 13434 expectations.pop_back(); | |
| 13435 | |
| 13436 for (ExpectationSet::const_iterator it = | |
| 13437 exp->immediate_prerequisites_.begin(); | |
| 13438 it != exp->immediate_prerequisites_.end(); ++it) { | |
| 13439 ExpectationBase* next = it->expectation_base().get(); | |
| 13440 if (!next->is_retired()) { | |
| 13441 next->Retire(); | |
| 13442 expectations.push_back(next); | |
| 13443 } | |
| 13444 } | |
| 13445 } | |
| 13446 } | |
| 13447 | |
| 13448 // Returns true if and only if all pre-requisites of this expectation | |
| 13449 // have been satisfied. | |
| 13450 bool ExpectationBase::AllPrerequisitesAreSatisfied() const | |
| 13451 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { | |
| 13452 g_gmock_mutex.AssertHeld(); | |
| 13453 ::std::vector<const ExpectationBase*> expectations(1, this); | |
| 13454 while (!expectations.empty()) { | |
| 13455 const ExpectationBase* exp = expectations.back(); | |
| 13456 expectations.pop_back(); | |
| 13457 | |
| 13458 for (ExpectationSet::const_iterator it = | |
| 13459 exp->immediate_prerequisites_.begin(); | |
| 13460 it != exp->immediate_prerequisites_.end(); ++it) { | |
| 13461 const ExpectationBase* next = it->expectation_base().get(); | |
| 13462 if (!next->IsSatisfied()) return false; | |
| 13463 expectations.push_back(next); | |
| 13464 } | |
| 13465 } | |
| 13466 return true; | |
| 13467 } | |
| 13468 | |
| 13469 // Adds unsatisfied pre-requisites of this expectation to 'result'. | |
| 13470 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const | |
| 13471 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { | |
| 13472 g_gmock_mutex.AssertHeld(); | |
| 13473 ::std::vector<const ExpectationBase*> expectations(1, this); | |
| 13474 while (!expectations.empty()) { | |
| 13475 const ExpectationBase* exp = expectations.back(); | |
| 13476 expectations.pop_back(); | |
| 13477 | |
| 13478 for (ExpectationSet::const_iterator it = | |
| 13479 exp->immediate_prerequisites_.begin(); | |
| 13480 it != exp->immediate_prerequisites_.end(); ++it) { | |
| 13481 const ExpectationBase* next = it->expectation_base().get(); | |
| 13482 | |
| 13483 if (next->IsSatisfied()) { | |
| 13484 // If *it is satisfied and has a call count of 0, some of its | |
| 13485 // pre-requisites may not be satisfied yet. | |
| 13486 if (next->call_count_ == 0) { | |
| 13487 expectations.push_back(next); | |
| 13488 } | |
| 13489 } else { | |
| 13490 // Now that we know next is unsatisfied, we are not so interested | |
| 13491 // in whether its pre-requisites are satisfied. Therefore we | |
| 13492 // don't iterate into it here. | |
| 13493 *result += *it; | |
| 13494 } | |
| 13495 } | |
| 13496 } | |
| 13497 } | |
| 13498 | |
| 13499 // Describes how many times a function call matching this | |
| 13500 // expectation has occurred. | |
| 13501 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const | |
| 13502 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { | |
| 13503 g_gmock_mutex.AssertHeld(); | |
| 13504 | |
| 13505 // Describes how many times the function is expected to be called. | |
| 13506 *os << " Expected: to be "; | |
| 13507 cardinality().DescribeTo(os); | |
| 13508 *os << "\n Actual: "; | |
| 13509 Cardinality::DescribeActualCallCountTo(call_count(), os); | |
| 13510 | |
| 13511 // Describes the state of the expectation (e.g. is it satisfied? | |
| 13512 // is it active?). | |
| 13513 *os << " - " << (IsOverSaturated() ? "over-saturated" : | |
| 13514 IsSaturated() ? "saturated" : | |
| 13515 IsSatisfied() ? "satisfied" : "unsatisfied") | |
| 13516 << " and " | |
| 13517 << (is_retired() ? "retired" : "active"); | |
| 13518 } | |
| 13519 | |
| 13520 // Checks the action count (i.e. the number of WillOnce() and | |
| 13521 // WillRepeatedly() clauses) against the cardinality if this hasn't | |
| 13522 // been done before. Prints a warning if there are too many or too | |
| 13523 // few actions. | |
| 13524 void ExpectationBase::CheckActionCountIfNotDone() const | |
| 13525 GTEST_LOCK_EXCLUDED_(mutex_) { | |
| 13526 bool should_check = false; | |
| 13527 { | |
| 13528 MutexLock l(&mutex_); | |
| 13529 if (!action_count_checked_) { | |
| 13530 action_count_checked_ = true; | |
| 13531 should_check = true; | |
| 13532 } | |
| 13533 } | |
| 13534 | |
| 13535 if (should_check) { | |
| 13536 if (!cardinality_specified_) { | |
| 13537 // The cardinality was inferred - no need to check the action | |
| 13538 // count against it. | |
| 13539 return; | |
| 13540 } | |
| 13541 | |
| 13542 // The cardinality was explicitly specified. | |
| 13543 const int action_count = static_cast<int>(untyped_actions_.size()); | |
| 13544 const int upper_bound = cardinality().ConservativeUpperBound(); | |
| 13545 const int lower_bound = cardinality().ConservativeLowerBound(); | |
| 13546 bool too_many; // True if there are too many actions, or false | |
| 13547 // if there are too few. | |
| 13548 if (action_count > upper_bound || | |
| 13549 (action_count == upper_bound && repeated_action_specified_)) { | |
| 13550 too_many = true; | |
| 13551 } else if (0 < action_count && action_count < lower_bound && | |
| 13552 !repeated_action_specified_) { | |
| 13553 too_many = false; | |
| 13554 } else { | |
| 13555 return; | |
| 13556 } | |
| 13557 | |
| 13558 ::std::stringstream ss; | |
| 13559 DescribeLocationTo(&ss); | |
| 13560 ss << "Too " << (too_many ? "many" : "few") | |
| 13561 << " actions specified in " << source_text() << "...\n" | |
| 13562 << "Expected to be "; | |
| 13563 cardinality().DescribeTo(&ss); | |
| 13564 ss << ", but has " << (too_many ? "" : "only ") | |
| 13565 << action_count << " WillOnce()" | |
| 13566 << (action_count == 1 ? "" : "s"); | |
| 13567 if (repeated_action_specified_) { | |
| 13568 ss << " and a WillRepeatedly()"; | |
| 13569 } | |
| 13570 ss << "."; | |
| 13571 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace". | |
| 13572 } | |
| 13573 } | |
| 13574 | |
| 13575 // Implements the .Times() clause. | |
| 13576 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { | |
| 13577 if (last_clause_ == kTimes) { | |
| 13578 ExpectSpecProperty(false, | |
| 13579 ".Times() cannot appear " | |
| 13580 "more than once in an EXPECT_CALL()."); | |
| 13581 } else { | |
| 13582 ExpectSpecProperty(last_clause_ < kTimes, | |
| 13583 ".Times() cannot appear after " | |
| 13584 ".InSequence(), .WillOnce(), .WillRepeatedly(), " | |
| 13585 "or .RetiresOnSaturation()."); | |
| 13586 } | |
| 13587 last_clause_ = kTimes; | |
| 13588 | |
| 13589 SpecifyCardinality(a_cardinality); | |
| 13590 } | |
| 13591 | |
| 13592 // Points to the implicit sequence introduced by a living InSequence | |
| 13593 // object (if any) in the current thread or NULL. | |
| 13594 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; | |
| 13595 | |
| 13596 // Reports an uninteresting call (whose description is in msg) in the | |
| 13597 // manner specified by 'reaction'. | |
| 13598 void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { | |
| 13599 // Include a stack trace only if --gmock_verbose=info is specified. | |
| 13600 const int stack_frames_to_skip = | |
| 13601 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; | |
| 13602 switch (reaction) { | |
| 13603 case kAllow: | |
| 13604 Log(kInfo, msg, stack_frames_to_skip); | |
| 13605 break; | |
| 13606 case kWarn: | |
| 13607 Log(kWarning, | |
| 13608 msg + | |
| 13609 "\nNOTE: You can safely ignore the above warning unless this " | |
| 13610 "call should not happen. Do not suppress it by blindly adding " | |
| 13611 "an EXPECT_CALL() if you don't mean to enforce the call. " | |
| 13612 "See " | |
| 13613 "https://github.com/google/googletest/blob/master/docs/" | |
| 13614 "gmock_cook_book.md#" | |
| 13615 "knowing-when-to-expect for details.\n", | |
| 13616 stack_frames_to_skip); | |
| 13617 break; | |
| 13618 default: // FAIL | |
| 13619 Expect(false, nullptr, -1, msg); | |
| 13620 } | |
| 13621 } | |
| 13622 | |
| 13623 UntypedFunctionMockerBase::UntypedFunctionMockerBase() | |
| 13624 : mock_obj_(nullptr), name_("") {} | |
| 13625 | |
| 13626 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} | |
| 13627 | |
| 13628 // Sets the mock object this mock method belongs to, and registers | |
| 13629 // this information in the global mock registry. Will be called | |
| 13630 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock | |
| 13631 // method. | |
| 13632 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) | |
| 13633 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { | |
| 13634 { | |
| 13635 MutexLock l(&g_gmock_mutex); | |
| 13636 mock_obj_ = mock_obj; | |
| 13637 } | |
| 13638 Mock::Register(mock_obj, this); | |
| 13639 } | |
| 13640 | |
| 13641 // Sets the mock object this mock method belongs to, and sets the name | |
| 13642 // of the mock function. Will be called upon each invocation of this | |
| 13643 // mock function. | |
| 13644 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, | |
| 13645 const char* name) | |
| 13646 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { | |
| 13647 // We protect name_ under g_gmock_mutex in case this mock function | |
| 13648 // is called from two threads concurrently. | |
| 13649 MutexLock l(&g_gmock_mutex); | |
| 13650 mock_obj_ = mock_obj; | |
| 13651 name_ = name; | |
| 13652 } | |
| 13653 | |
| 13654 // Returns the name of the function being mocked. Must be called | |
| 13655 // after RegisterOwner() or SetOwnerAndName() has been called. | |
| 13656 const void* UntypedFunctionMockerBase::MockObject() const | |
| 13657 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { | |
| 13658 const void* mock_obj; | |
| 13659 { | |
| 13660 // We protect mock_obj_ under g_gmock_mutex in case this mock | |
| 13661 // function is called from two threads concurrently. | |
| 13662 MutexLock l(&g_gmock_mutex); | |
| 13663 Assert(mock_obj_ != nullptr, __FILE__, __LINE__, | |
| 13664 "MockObject() must not be called before RegisterOwner() or " | |
| 13665 "SetOwnerAndName() has been called."); | |
| 13666 mock_obj = mock_obj_; | |
| 13667 } | |
| 13668 return mock_obj; | |
| 13669 } | |
| 13670 | |
| 13671 // Returns the name of this mock method. Must be called after | |
| 13672 // SetOwnerAndName() has been called. | |
| 13673 const char* UntypedFunctionMockerBase::Name() const | |
| 13674 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { | |
| 13675 const char* name; | |
| 13676 { | |
| 13677 // We protect name_ under g_gmock_mutex in case this mock | |
| 13678 // function is called from two threads concurrently. | |
| 13679 MutexLock l(&g_gmock_mutex); | |
| 13680 Assert(name_ != nullptr, __FILE__, __LINE__, | |
| 13681 "Name() must not be called before SetOwnerAndName() has " | |
| 13682 "been called."); | |
| 13683 name = name_; | |
| 13684 } | |
| 13685 return name; | |
| 13686 } | |
| 13687 | |
| 13688 // Calculates the result of invoking this mock function with the given | |
| 13689 // arguments, prints it, and returns it. The caller is responsible | |
| 13690 // for deleting the result. | |
| 13691 UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( | |
| 13692 void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { | |
| 13693 // See the definition of untyped_expectations_ for why access to it | |
| 13694 // is unprotected here. | |
| 13695 if (untyped_expectations_.size() == 0) { | |
| 13696 // No expectation is set on this mock method - we have an | |
| 13697 // uninteresting call. | |
| 13698 | |
| 13699 // We must get Google Mock's reaction on uninteresting calls | |
| 13700 // made on this mock object BEFORE performing the action, | |
| 13701 // because the action may DELETE the mock object and make the | |
| 13702 // following expression meaningless. | |
| 13703 const CallReaction reaction = | |
| 13704 Mock::GetReactionOnUninterestingCalls(MockObject()); | |
| 13705 | |
| 13706 // True if and only if we need to print this call's arguments and return | |
| 13707 // value. This definition must be kept in sync with | |
| 13708 // the behavior of ReportUninterestingCall(). | |
| 13709 const bool need_to_report_uninteresting_call = | |
| 13710 // If the user allows this uninteresting call, we print it | |
| 13711 // only when they want informational messages. | |
| 13712 reaction == kAllow ? LogIsVisible(kInfo) : | |
| 13713 // If the user wants this to be a warning, we print | |
| 13714 // it only when they want to see warnings. | |
| 13715 reaction == kWarn | |
| 13716 ? LogIsVisible(kWarning) | |
| 13717 : | |
| 13718 // Otherwise, the user wants this to be an error, and we | |
| 13719 // should always print detailed information in the error. | |
| 13720 true; | |
| 13721 | |
| 13722 if (!need_to_report_uninteresting_call) { | |
| 13723 // Perform the action without printing the call information. | |
| 13724 return this->UntypedPerformDefaultAction( | |
| 13725 untyped_args, "Function call: " + std::string(Name())); | |
| 13726 } | |
| 13727 | |
| 13728 // Warns about the uninteresting call. | |
| 13729 ::std::stringstream ss; | |
| 13730 this->UntypedDescribeUninterestingCall(untyped_args, &ss); | |
| 13731 | |
| 13732 // Calculates the function result. | |
| 13733 UntypedActionResultHolderBase* const result = | |
| 13734 this->UntypedPerformDefaultAction(untyped_args, ss.str()); | |
| 13735 | |
| 13736 // Prints the function result. | |
| 13737 if (result != nullptr) result->PrintAsActionResult(&ss); | |
| 13738 | |
| 13739 ReportUninterestingCall(reaction, ss.str()); | |
| 13740 return result; | |
| 13741 } | |
| 13742 | |
| 13743 bool is_excessive = false; | |
| 13744 ::std::stringstream ss; | |
| 13745 ::std::stringstream why; | |
| 13746 ::std::stringstream loc; | |
| 13747 const void* untyped_action = nullptr; | |
| 13748 | |
| 13749 // The UntypedFindMatchingExpectation() function acquires and | |
| 13750 // releases g_gmock_mutex. | |
| 13751 | |
| 13752 const ExpectationBase* const untyped_expectation = | |
| 13753 this->UntypedFindMatchingExpectation(untyped_args, &untyped_action, | |
| 13754 &is_excessive, &ss, &why); | |
| 13755 const bool found = untyped_expectation != nullptr; | |
| 13756 | |
| 13757 // True if and only if we need to print the call's arguments | |
| 13758 // and return value. | |
| 13759 // This definition must be kept in sync with the uses of Expect() | |
| 13760 // and Log() in this function. | |
| 13761 const bool need_to_report_call = | |
| 13762 !found || is_excessive || LogIsVisible(kInfo); | |
| 13763 if (!need_to_report_call) { | |
| 13764 // Perform the action without printing the call information. | |
| 13765 return untyped_action == nullptr | |
| 13766 ? this->UntypedPerformDefaultAction(untyped_args, "") | |
| 13767 : this->UntypedPerformAction(untyped_action, untyped_args); | |
| 13768 } | |
| 13769 | |
| 13770 ss << " Function call: " << Name(); | |
| 13771 this->UntypedPrintArgs(untyped_args, &ss); | |
| 13772 | |
| 13773 // In case the action deletes a piece of the expectation, we | |
| 13774 // generate the message beforehand. | |
| 13775 if (found && !is_excessive) { | |
| 13776 untyped_expectation->DescribeLocationTo(&loc); | |
| 13777 } | |
| 13778 | |
| 13779 UntypedActionResultHolderBase* result = nullptr; | |
| 13780 | |
| 13781 auto perform_action = [&, this] { | |
| 13782 return untyped_action == nullptr | |
| 13783 ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) | |
| 13784 : this->UntypedPerformAction(untyped_action, untyped_args); | |
| 13785 }; | |
| 13786 auto handle_failures = [&] { | |
| 13787 ss << "\n" << why.str(); | |
| 13788 | |
| 13789 if (!found) { | |
| 13790 // No expectation matches this call - reports a failure. | |
| 13791 Expect(false, nullptr, -1, ss.str()); | |
| 13792 } else if (is_excessive) { | |
| 13793 // We had an upper-bound violation and the failure message is in ss. | |
| 13794 Expect(false, untyped_expectation->file(), untyped_expectation->line(), | |
| 13795 ss.str()); | |
| 13796 } else { | |
| 13797 // We had an expected call and the matching expectation is | |
| 13798 // described in ss. | |
| 13799 Log(kInfo, loc.str() + ss.str(), 2); | |
| 13800 } | |
| 13801 }; | |
| 13802 #if GTEST_HAS_EXCEPTIONS | |
| 13803 try { | |
| 13804 result = perform_action(); | |
| 13805 } catch (...) { | |
| 13806 handle_failures(); | |
| 13807 throw; | |
| 13808 } | |
| 13809 #else | |
| 13810 result = perform_action(); | |
| 13811 #endif | |
| 13812 | |
| 13813 if (result != nullptr) result->PrintAsActionResult(&ss); | |
| 13814 handle_failures(); | |
| 13815 return result; | |
| 13816 } | |
| 13817 | |
| 13818 // Returns an Expectation object that references and co-owns exp, | |
| 13819 // which must be an expectation on this mock function. | |
| 13820 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { | |
| 13821 // See the definition of untyped_expectations_ for why access to it | |
| 13822 // is unprotected here. | |
| 13823 for (UntypedExpectations::const_iterator it = | |
| 13824 untyped_expectations_.begin(); | |
| 13825 it != untyped_expectations_.end(); ++it) { | |
| 13826 if (it->get() == exp) { | |
| 13827 return Expectation(*it); | |
| 13828 } | |
| 13829 } | |
| 13830 | |
| 13831 Assert(false, __FILE__, __LINE__, "Cannot find expectation."); | |
| 13832 return Expectation(); | |
| 13833 // The above statement is just to make the code compile, and will | |
| 13834 // never be executed. | |
| 13835 } | |
| 13836 | |
| 13837 // Verifies that all expectations on this mock function have been | |
| 13838 // satisfied. Reports one or more Google Test non-fatal failures | |
| 13839 // and returns false if not. | |
| 13840 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() | |
| 13841 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { | |
| 13842 g_gmock_mutex.AssertHeld(); | |
| 13843 bool expectations_met = true; | |
| 13844 for (UntypedExpectations::const_iterator it = | |
| 13845 untyped_expectations_.begin(); | |
| 13846 it != untyped_expectations_.end(); ++it) { | |
| 13847 ExpectationBase* const untyped_expectation = it->get(); | |
| 13848 if (untyped_expectation->IsOverSaturated()) { | |
| 13849 // There was an upper-bound violation. Since the error was | |
| 13850 // already reported when it occurred, there is no need to do | |
| 13851 // anything here. | |
| 13852 expectations_met = false; | |
| 13853 } else if (!untyped_expectation->IsSatisfied()) { | |
| 13854 expectations_met = false; | |
| 13855 ::std::stringstream ss; | |
| 13856 ss << "Actual function call count doesn't match " | |
| 13857 << untyped_expectation->source_text() << "...\n"; | |
| 13858 // No need to show the source file location of the expectation | |
| 13859 // in the description, as the Expect() call that follows already | |
| 13860 // takes care of it. | |
| 13861 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); | |
| 13862 untyped_expectation->DescribeCallCountTo(&ss); | |
| 13863 Expect(false, untyped_expectation->file(), | |
| 13864 untyped_expectation->line(), ss.str()); | |
| 13865 } | |
| 13866 } | |
| 13867 | |
| 13868 // Deleting our expectations may trigger other mock objects to be deleted, for | |
| 13869 // example if an action contains a reference counted smart pointer to that | |
| 13870 // mock object, and that is the last reference. So if we delete our | |
| 13871 // expectations within the context of the global mutex we may deadlock when | |
| 13872 // this method is called again. Instead, make a copy of the set of | |
| 13873 // expectations to delete, clear our set within the mutex, and then clear the | |
| 13874 // copied set outside of it. | |
| 13875 UntypedExpectations expectations_to_delete; | |
| 13876 untyped_expectations_.swap(expectations_to_delete); | |
| 13877 | |
| 13878 g_gmock_mutex.Unlock(); | |
| 13879 expectations_to_delete.clear(); | |
| 13880 g_gmock_mutex.Lock(); | |
| 13881 | |
| 13882 return expectations_met; | |
| 13883 } | |
| 13884 | |
| 13885 CallReaction intToCallReaction(int mock_behavior) { | |
| 13886 if (mock_behavior >= kAllow && mock_behavior <= kFail) { | |
| 13887 return static_cast<internal::CallReaction>(mock_behavior); | |
| 13888 } | |
| 13889 return kWarn; | |
| 13890 } | |
| 13891 | |
| 13892 } // namespace internal | |
| 13893 | |
| 13894 // Class Mock. | |
| 13895 | |
| 13896 namespace { | |
| 13897 | |
| 13898 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; | |
| 13899 | |
| 13900 // The current state of a mock object. Such information is needed for | |
| 13901 // detecting leaked mock objects and explicitly verifying a mock's | |
| 13902 // expectations. | |
| 13903 struct MockObjectState { | |
| 13904 MockObjectState() | |
| 13905 : first_used_file(nullptr), first_used_line(-1), leakable(false) {} | |
| 13906 | |
| 13907 // Where in the source file an ON_CALL or EXPECT_CALL is first | |
| 13908 // invoked on this mock object. | |
| 13909 const char* first_used_file; | |
| 13910 int first_used_line; | |
| 13911 ::std::string first_used_test_suite; | |
| 13912 ::std::string first_used_test; | |
| 13913 bool leakable; // true if and only if it's OK to leak the object. | |
| 13914 FunctionMockers function_mockers; // All registered methods of the object. | |
| 13915 }; | |
| 13916 | |
| 13917 // A global registry holding the state of all mock objects that are | |
| 13918 // alive. A mock object is added to this registry the first time | |
| 13919 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It | |
| 13920 // is removed from the registry in the mock object's destructor. | |
| 13921 class MockObjectRegistry { | |
| 13922 public: | |
| 13923 // Maps a mock object (identified by its address) to its state. | |
| 13924 typedef std::map<const void*, MockObjectState> StateMap; | |
| 13925 | |
| 13926 // This destructor will be called when a program exits, after all | |
| 13927 // tests in it have been run. By then, there should be no mock | |
| 13928 // object alive. Therefore we report any living object as test | |
| 13929 // failure, unless the user explicitly asked us to ignore it. | |
| 13930 ~MockObjectRegistry() { | |
| 13931 if (!GMOCK_FLAG(catch_leaked_mocks)) | |
| 13932 return; | |
| 13933 | |
| 13934 int leaked_count = 0; | |
| 13935 for (StateMap::const_iterator it = states_.begin(); it != states_.end(); | |
| 13936 ++it) { | |
| 13937 if (it->second.leakable) // The user said it's fine to leak this object. | |
| 13938 continue; | |
| 13939 | |
| 13940 // FIXME: Print the type of the leaked object. | |
| 13941 // This can help the user identify the leaked object. | |
| 13942 std::cout << "\n"; | |
| 13943 const MockObjectState& state = it->second; | |
| 13944 std::cout << internal::FormatFileLocation(state.first_used_file, | |
| 13945 state.first_used_line); | |
| 13946 std::cout << " ERROR: this mock object"; | |
| 13947 if (state.first_used_test != "") { | |
| 13948 std::cout << " (used in test " << state.first_used_test_suite << "." | |
| 13949 << state.first_used_test << ")"; | |
| 13950 } | |
| 13951 std::cout << " should be deleted but never is. Its address is @" | |
| 13952 << it->first << "."; | |
| 13953 leaked_count++; | |
| 13954 } | |
| 13955 if (leaked_count > 0) { | |
| 13956 std::cout << "\nERROR: " << leaked_count << " leaked mock " | |
| 13957 << (leaked_count == 1 ? "object" : "objects") | |
| 13958 << " found at program exit. Expectations on a mock object are " | |
| 13959 "verified when the object is destructed. Leaking a mock " | |
| 13960 "means that its expectations aren't verified, which is " | |
| 13961 "usually a test bug. If you really intend to leak a mock, " | |
| 13962 "you can suppress this error using " | |
| 13963 "testing::Mock::AllowLeak(mock_object), or you may use a " | |
| 13964 "fake or stub instead of a mock.\n"; | |
| 13965 std::cout.flush(); | |
| 13966 ::std::cerr.flush(); | |
| 13967 // RUN_ALL_TESTS() has already returned when this destructor is | |
| 13968 // called. Therefore we cannot use the normal Google Test | |
| 13969 // failure reporting mechanism. | |
| 13970 _exit(1); // We cannot call exit() as it is not reentrant and | |
| 13971 // may already have been called. | |
| 13972 } | |
| 13973 } | |
| 13974 | |
| 13975 StateMap& states() { return states_; } | |
| 13976 | |
| 13977 private: | |
| 13978 StateMap states_; | |
| 13979 }; | |
| 13980 | |
| 13981 // Protected by g_gmock_mutex. | |
| 13982 MockObjectRegistry g_mock_object_registry; | |
| 13983 | |
| 13984 // Maps a mock object to the reaction Google Mock should have when an | |
| 13985 // uninteresting method is called. Protected by g_gmock_mutex. | |
| 13986 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction; | |
| 13987 | |
| 13988 // Sets the reaction Google Mock should have when an uninteresting | |
| 13989 // method of the given mock object is called. | |
| 13990 void SetReactionOnUninterestingCalls(const void* mock_obj, | |
| 13991 internal::CallReaction reaction) | |
| 13992 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 13993 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 13994 g_uninteresting_call_reaction[mock_obj] = reaction; | |
| 13995 } | |
| 13996 | |
| 13997 } // namespace | |
| 13998 | |
| 13999 // Tells Google Mock to allow uninteresting calls on the given mock | |
| 14000 // object. | |
| 14001 void Mock::AllowUninterestingCalls(const void* mock_obj) | |
| 14002 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14003 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); | |
| 14004 } | |
| 14005 | |
| 14006 // Tells Google Mock to warn the user about uninteresting calls on the | |
| 14007 // given mock object. | |
| 14008 void Mock::WarnUninterestingCalls(const void* mock_obj) | |
| 14009 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14010 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); | |
| 14011 } | |
| 14012 | |
| 14013 // Tells Google Mock to fail uninteresting calls on the given mock | |
| 14014 // object. | |
| 14015 void Mock::FailUninterestingCalls(const void* mock_obj) | |
| 14016 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14017 SetReactionOnUninterestingCalls(mock_obj, internal::kFail); | |
| 14018 } | |
| 14019 | |
| 14020 // Tells Google Mock the given mock object is being destroyed and its | |
| 14021 // entry in the call-reaction table should be removed. | |
| 14022 void Mock::UnregisterCallReaction(const void* mock_obj) | |
| 14023 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14024 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14025 g_uninteresting_call_reaction.erase(mock_obj); | |
| 14026 } | |
| 14027 | |
| 14028 // Returns the reaction Google Mock will have on uninteresting calls | |
| 14029 // made on the given mock object. | |
| 14030 internal::CallReaction Mock::GetReactionOnUninterestingCalls( | |
| 14031 const void* mock_obj) | |
| 14032 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14033 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14034 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? | |
| 14035 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) : | |
| 14036 g_uninteresting_call_reaction[mock_obj]; | |
| 14037 } | |
| 14038 | |
| 14039 // Tells Google Mock to ignore mock_obj when checking for leaked mock | |
| 14040 // objects. | |
| 14041 void Mock::AllowLeak(const void* mock_obj) | |
| 14042 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14043 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14044 g_mock_object_registry.states()[mock_obj].leakable = true; | |
| 14045 } | |
| 14046 | |
| 14047 // Verifies and clears all expectations on the given mock object. If | |
| 14048 // the expectations aren't satisfied, generates one or more Google | |
| 14049 // Test non-fatal failures and returns false. | |
| 14050 bool Mock::VerifyAndClearExpectations(void* mock_obj) | |
| 14051 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14052 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14053 return VerifyAndClearExpectationsLocked(mock_obj); | |
| 14054 } | |
| 14055 | |
| 14056 // Verifies all expectations on the given mock object and clears its | |
| 14057 // default actions and expectations. Returns true if and only if the | |
| 14058 // verification was successful. | |
| 14059 bool Mock::VerifyAndClear(void* mock_obj) | |
| 14060 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14061 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14062 ClearDefaultActionsLocked(mock_obj); | |
| 14063 return VerifyAndClearExpectationsLocked(mock_obj); | |
| 14064 } | |
| 14065 | |
| 14066 // Verifies and clears all expectations on the given mock object. If | |
| 14067 // the expectations aren't satisfied, generates one or more Google | |
| 14068 // Test non-fatal failures and returns false. | |
| 14069 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) | |
| 14070 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { | |
| 14071 internal::g_gmock_mutex.AssertHeld(); | |
| 14072 if (g_mock_object_registry.states().count(mock_obj) == 0) { | |
| 14073 // No EXPECT_CALL() was set on the given mock object. | |
| 14074 return true; | |
| 14075 } | |
| 14076 | |
| 14077 // Verifies and clears the expectations on each mock method in the | |
| 14078 // given mock object. | |
| 14079 bool expectations_met = true; | |
| 14080 FunctionMockers& mockers = | |
| 14081 g_mock_object_registry.states()[mock_obj].function_mockers; | |
| 14082 for (FunctionMockers::const_iterator it = mockers.begin(); | |
| 14083 it != mockers.end(); ++it) { | |
| 14084 if (!(*it)->VerifyAndClearExpectationsLocked()) { | |
| 14085 expectations_met = false; | |
| 14086 } | |
| 14087 } | |
| 14088 | |
| 14089 // We don't clear the content of mockers, as they may still be | |
| 14090 // needed by ClearDefaultActionsLocked(). | |
| 14091 return expectations_met; | |
| 14092 } | |
| 14093 | |
| 14094 bool Mock::IsNaggy(void* mock_obj) | |
| 14095 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14096 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn; | |
| 14097 } | |
| 14098 bool Mock::IsNice(void* mock_obj) | |
| 14099 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14100 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow; | |
| 14101 } | |
| 14102 bool Mock::IsStrict(void* mock_obj) | |
| 14103 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14104 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail; | |
| 14105 } | |
| 14106 | |
| 14107 // Registers a mock object and a mock method it owns. | |
| 14108 void Mock::Register(const void* mock_obj, | |
| 14109 internal::UntypedFunctionMockerBase* mocker) | |
| 14110 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14111 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14112 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); | |
| 14113 } | |
| 14114 | |
| 14115 // Tells Google Mock where in the source code mock_obj is used in an | |
| 14116 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this | |
| 14117 // information helps the user identify which object it is. | |
| 14118 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, | |
| 14119 const char* file, int line) | |
| 14120 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { | |
| 14121 internal::MutexLock l(&internal::g_gmock_mutex); | |
| 14122 MockObjectState& state = g_mock_object_registry.states()[mock_obj]; | |
| 14123 if (state.first_used_file == nullptr) { | |
| 14124 state.first_used_file = file; | |
| 14125 state.first_used_line = line; | |
| 14126 const TestInfo* const test_info = | |
| 14127 UnitTest::GetInstance()->current_test_info(); | |
| 14128 if (test_info != nullptr) { | |
| 14129 state.first_used_test_suite = test_info->test_suite_name(); | |
| 14130 state.first_used_test = test_info->name(); | |
| 14131 } | |
| 14132 } | |
| 14133 } | |
| 14134 | |
| 14135 // Unregisters a mock method; removes the owning mock object from the | |
| 14136 // registry when the last mock method associated with it has been | |
| 14137 // unregistered. This is called only in the destructor of | |
| 14138 // FunctionMockerBase. | |
| 14139 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) | |
| 14140 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { | |
| 14141 internal::g_gmock_mutex.AssertHeld(); | |
| 14142 for (MockObjectRegistry::StateMap::iterator it = | |
| 14143 g_mock_object_registry.states().begin(); | |
| 14144 it != g_mock_object_registry.states().end(); ++it) { | |
| 14145 FunctionMockers& mockers = it->second.function_mockers; | |
| 14146 if (mockers.erase(mocker) > 0) { | |
| 14147 // mocker was in mockers and has been just removed. | |
| 14148 if (mockers.empty()) { | |
| 14149 g_mock_object_registry.states().erase(it); | |
| 14150 } | |
| 14151 return; | |
| 14152 } | |
| 14153 } | |
| 14154 } | |
| 14155 | |
| 14156 // Clears all ON_CALL()s set on the given mock object. | |
| 14157 void Mock::ClearDefaultActionsLocked(void* mock_obj) | |
| 14158 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { | |
| 14159 internal::g_gmock_mutex.AssertHeld(); | |
| 14160 | |
| 14161 if (g_mock_object_registry.states().count(mock_obj) == 0) { | |
| 14162 // No ON_CALL() was set on the given mock object. | |
| 14163 return; | |
| 14164 } | |
| 14165 | |
| 14166 // Clears the default actions for each mock method in the given mock | |
| 14167 // object. | |
| 14168 FunctionMockers& mockers = | |
| 14169 g_mock_object_registry.states()[mock_obj].function_mockers; | |
| 14170 for (FunctionMockers::const_iterator it = mockers.begin(); | |
| 14171 it != mockers.end(); ++it) { | |
| 14172 (*it)->ClearDefaultActionsLocked(); | |
| 14173 } | |
| 14174 | |
| 14175 // We don't clear the content of mockers, as they may still be | |
| 14176 // needed by VerifyAndClearExpectationsLocked(). | |
| 14177 } | |
| 14178 | |
| 14179 Expectation::Expectation() {} | |
| 14180 | |
| 14181 Expectation::Expectation( | |
| 14182 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) | |
| 14183 : expectation_base_(an_expectation_base) {} | |
| 14184 | |
| 14185 Expectation::~Expectation() {} | |
| 14186 | |
| 14187 // Adds an expectation to a sequence. | |
| 14188 void Sequence::AddExpectation(const Expectation& expectation) const { | |
| 14189 if (*last_expectation_ != expectation) { | |
| 14190 if (last_expectation_->expectation_base() != nullptr) { | |
| 14191 expectation.expectation_base()->immediate_prerequisites_ | |
| 14192 += *last_expectation_; | |
| 14193 } | |
| 14194 *last_expectation_ = expectation; | |
| 14195 } | |
| 14196 } | |
| 14197 | |
| 14198 // Creates the implicit sequence if there isn't one. | |
| 14199 InSequence::InSequence() { | |
| 14200 if (internal::g_gmock_implicit_sequence.get() == nullptr) { | |
| 14201 internal::g_gmock_implicit_sequence.set(new Sequence); | |
| 14202 sequence_created_ = true; | |
| 14203 } else { | |
| 14204 sequence_created_ = false; | |
| 14205 } | |
| 14206 } | |
| 14207 | |
| 14208 // Deletes the implicit sequence if it was created by the constructor | |
| 14209 // of this object. | |
| 14210 InSequence::~InSequence() { | |
| 14211 if (sequence_created_) { | |
| 14212 delete internal::g_gmock_implicit_sequence.get(); | |
| 14213 internal::g_gmock_implicit_sequence.set(nullptr); | |
| 14214 } | |
| 14215 } | |
| 14216 | |
| 14217 } // namespace testing | |
| 14218 | |
| 14219 #ifdef _MSC_VER | |
| 14220 #if _MSC_VER == 1900 | |
| 14221 # pragma warning(pop) | |
| 14222 #endif | |
| 14223 #endif | |
| 14224 // Copyright 2008, Google Inc. | |
| 14225 // All rights reserved. | |
| 14226 // | |
| 14227 // Redistribution and use in source and binary forms, with or without | |
| 14228 // modification, are permitted provided that the following conditions are | |
| 14229 // met: | |
| 14230 // | |
| 14231 // * Redistributions of source code must retain the above copyright | |
| 14232 // notice, this list of conditions and the following disclaimer. | |
| 14233 // * Redistributions in binary form must reproduce the above | |
| 14234 // copyright notice, this list of conditions and the following disclaimer | |
| 14235 // in the documentation and/or other materials provided with the | |
| 14236 // distribution. | |
| 14237 // * Neither the name of Google Inc. nor the names of its | |
| 14238 // contributors may be used to endorse or promote products derived from | |
| 14239 // this software without specific prior written permission. | |
| 14240 // | |
| 14241 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 14242 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 14243 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 14244 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 14245 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 14246 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
| 14247 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
| 14248 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
| 14249 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 14250 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 14251 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 14252 | |
| 14253 | |
| 14254 | |
| 14255 namespace testing { | |
| 14256 | |
| 14257 GMOCK_DEFINE_bool_(catch_leaked_mocks, true, | |
| 14258 "true if and only if Google Mock should report leaked " | |
| 14259 "mock objects as failures."); | |
| 14260 | |
| 14261 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, | |
| 14262 "Controls how verbose Google Mock's output is." | |
| 14263 " Valid values:\n" | |
| 14264 " info - prints all messages.\n" | |
| 14265 " warning - prints warnings and errors.\n" | |
| 14266 " error - prints errors only."); | |
| 14267 | |
| 14268 GMOCK_DEFINE_int32_(default_mock_behavior, 1, | |
| 14269 "Controls the default behavior of mocks." | |
| 14270 " Valid values:\n" | |
| 14271 " 0 - by default, mocks act as NiceMocks.\n" | |
| 14272 " 1 - by default, mocks act as NaggyMocks.\n" | |
| 14273 " 2 - by default, mocks act as StrictMocks."); | |
| 14274 | |
| 14275 namespace internal { | |
| 14276 | |
| 14277 // Parses a string as a command line flag. The string should have the | |
| 14278 // format "--gmock_flag=value". When def_optional is true, the | |
| 14279 // "=value" part can be omitted. | |
| 14280 // | |
| 14281 // Returns the value of the flag, or NULL if the parsing failed. | |
| 14282 static const char* ParseGoogleMockFlagValue(const char* str, | |
| 14283 const char* flag, | |
| 14284 bool def_optional) { | |
| 14285 // str and flag must not be NULL. | |
| 14286 if (str == nullptr || flag == nullptr) return nullptr; | |
| 14287 | |
| 14288 // The flag must start with "--gmock_". | |
| 14289 const std::string flag_str = std::string("--gmock_") + flag; | |
| 14290 const size_t flag_len = flag_str.length(); | |
| 14291 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; | |
| 14292 | |
| 14293 // Skips the flag name. | |
| 14294 const char* flag_end = str + flag_len; | |
| 14295 | |
| 14296 // When def_optional is true, it's OK to not have a "=value" part. | |
| 14297 if (def_optional && (flag_end[0] == '\0')) { | |
| 14298 return flag_end; | |
| 14299 } | |
| 14300 | |
| 14301 // If def_optional is true and there are more characters after the | |
| 14302 // flag name, or if def_optional is false, there must be a '=' after | |
| 14303 // the flag name. | |
| 14304 if (flag_end[0] != '=') return nullptr; | |
| 14305 | |
| 14306 // Returns the string after "=". | |
| 14307 return flag_end + 1; | |
| 14308 } | |
| 14309 | |
| 14310 // Parses a string for a Google Mock bool flag, in the form of | |
| 14311 // "--gmock_flag=value". | |
| 14312 // | |
| 14313 // On success, stores the value of the flag in *value, and returns | |
| 14314 // true. On failure, returns false without changing *value. | |
| 14315 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, | |
| 14316 bool* value) { | |
| 14317 // Gets the value of the flag as a string. | |
| 14318 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); | |
| 14319 | |
| 14320 // Aborts if the parsing failed. | |
| 14321 if (value_str == nullptr) return false; | |
| 14322 | |
| 14323 // Converts the string value to a bool. | |
| 14324 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); | |
| 14325 return true; | |
| 14326 } | |
| 14327 | |
| 14328 // Parses a string for a Google Mock string flag, in the form of | |
| 14329 // "--gmock_flag=value". | |
| 14330 // | |
| 14331 // On success, stores the value of the flag in *value, and returns | |
| 14332 // true. On failure, returns false without changing *value. | |
| 14333 template <typename String> | |
| 14334 static bool ParseGoogleMockStringFlag(const char* str, const char* flag, | |
| 14335 String* value) { | |
| 14336 // Gets the value of the flag as a string. | |
| 14337 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); | |
| 14338 | |
| 14339 // Aborts if the parsing failed. | |
| 14340 if (value_str == nullptr) return false; | |
| 14341 | |
| 14342 // Sets *value to the value of the flag. | |
| 14343 *value = value_str; | |
| 14344 return true; | |
| 14345 } | |
| 14346 | |
| 14347 static bool ParseGoogleMockIntFlag(const char* str, const char* flag, | |
| 14348 int32_t* value) { | |
| 14349 // Gets the value of the flag as a string. | |
| 14350 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); | |
| 14351 | |
| 14352 // Aborts if the parsing failed. | |
| 14353 if (value_str == nullptr) return false; | |
| 14354 | |
| 14355 // Sets *value to the value of the flag. | |
| 14356 return ParseInt32(Message() << "The value of flag --" << flag, | |
| 14357 value_str, value); | |
| 14358 } | |
| 14359 | |
| 14360 // The internal implementation of InitGoogleMock(). | |
| 14361 // | |
| 14362 // The type parameter CharType can be instantiated to either char or | |
| 14363 // wchar_t. | |
| 14364 template <typename CharType> | |
| 14365 void InitGoogleMockImpl(int* argc, CharType** argv) { | |
| 14366 // Makes sure Google Test is initialized. InitGoogleTest() is | |
| 14367 // idempotent, so it's fine if the user has already called it. | |
| 14368 InitGoogleTest(argc, argv); | |
| 14369 if (*argc <= 0) return; | |
| 14370 | |
| 14371 for (int i = 1; i != *argc; i++) { | |
| 14372 const std::string arg_string = StreamableToString(argv[i]); | |
| 14373 const char* const arg = arg_string.c_str(); | |
| 14374 | |
| 14375 // Do we see a Google Mock flag? | |
| 14376 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", | |
| 14377 &GMOCK_FLAG(catch_leaked_mocks)) || | |
| 14378 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) || | |
| 14379 ParseGoogleMockIntFlag(arg, "default_mock_behavior", | |
| 14380 &GMOCK_FLAG(default_mock_behavior))) { | |
| 14381 // Yes. Shift the remainder of the argv list left by one. Note | |
| 14382 // that argv has (*argc + 1) elements, the last one always being | |
| 14383 // NULL. The following loop moves the trailing NULL element as | |
| 14384 // well. | |
| 14385 for (int j = i; j != *argc; j++) { | |
| 14386 argv[j] = argv[j + 1]; | |
| 14387 } | |
| 14388 | |
| 14389 // Decrements the argument count. | |
| 14390 (*argc)--; | |
| 14391 | |
| 14392 // We also need to decrement the iterator as we just removed | |
| 14393 // an element. | |
| 14394 i--; | |
| 14395 } | |
| 14396 } | |
| 14397 } | |
| 14398 | |
| 14399 } // namespace internal | |
| 14400 | |
| 14401 // Initializes Google Mock. This must be called before running the | |
| 14402 // tests. In particular, it parses a command line for the flags that | |
| 14403 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is | |
| 14404 // removed from argv, and *argc is decremented. | |
| 14405 // | |
| 14406 // No value is returned. Instead, the Google Mock flag variables are | |
| 14407 // updated. | |
| 14408 // | |
| 14409 // Since Google Test is needed for Google Mock to work, this function | |
| 14410 // also initializes Google Test and parses its flags, if that hasn't | |
| 14411 // been done. | |
| 14412 GTEST_API_ void InitGoogleMock(int* argc, char** argv) { | |
| 14413 internal::InitGoogleMockImpl(argc, argv); | |
| 14414 } | |
| 14415 | |
| 14416 // This overloaded version can be used in Windows programs compiled in | |
| 14417 // UNICODE mode. | |
| 14418 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { | |
| 14419 internal::InitGoogleMockImpl(argc, argv); | |
| 14420 } | |
| 14421 | |
| 14422 // This overloaded version can be used on Arduino/embedded platforms where | |
| 14423 // there is no argc/argv. | |
| 14424 GTEST_API_ void InitGoogleMock() { | |
| 14425 // Since Arduino doesn't have a command line, fake out the argc/argv arguments | |
| 14426 int argc = 1; | |
| 14427 const auto arg0 = "dummy"; | |
| 14428 char* argv0 = const_cast<char*>(arg0); | |
| 14429 char** argv = &argv0; | |
| 14430 | |
| 14431 internal::InitGoogleMockImpl(&argc, argv); | |
| 14432 } | |
| 14433 | |
| 14434 } // namespace testing |
