PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/src/gtest.cc

http://github.com/tomahawk-player/tomahawk
C++ | 1800 lines | 1098 code | 259 blank | 443 comment | 191 complexity | 8de68a35c745eae12a68802b12569879 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. //
  32. // The Google C++ Testing Framework (Google Test)
  33. #include <gtest/gtest.h>
  34. #include <gtest/gtest-spi.h>
  35. #include <ctype.h>
  36. #include <math.h>
  37. #include <stdarg.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <wchar.h>
  41. #include <wctype.h>
  42. #include <algorithm>
  43. #include <ostream>
  44. #include <sstream>
  45. #include <vector>
  46. #if GTEST_OS_LINUX
  47. // TODO(kenton@google.com): Use autoconf to detect availability of
  48. // gettimeofday().
  49. #define GTEST_HAS_GETTIMEOFDAY_ 1
  50. #include <fcntl.h>
  51. #include <limits.h>
  52. #include <sched.h>
  53. // Declares vsnprintf(). This header is not available on Windows.
  54. #include <strings.h>
  55. #include <sys/mman.h>
  56. #include <sys/time.h>
  57. #include <unistd.h>
  58. #include <string>
  59. #include <vector>
  60. #elif GTEST_OS_SYMBIAN
  61. #define GTEST_HAS_GETTIMEOFDAY_ 1
  62. #include <sys/time.h> // NOLINT
  63. #elif GTEST_OS_ZOS
  64. #define GTEST_HAS_GETTIMEOFDAY_ 1
  65. #include <sys/time.h> // NOLINT
  66. // On z/OS we additionally need strings.h for strcasecmp.
  67. #include <strings.h> // NOLINT
  68. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  69. #include <windows.h> // NOLINT
  70. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  71. #include <io.h> // NOLINT
  72. #include <sys/timeb.h> // NOLINT
  73. #include <sys/types.h> // NOLINT
  74. #include <sys/stat.h> // NOLINT
  75. #if GTEST_OS_WINDOWS_MINGW
  76. // MinGW has gettimeofday() but not _ftime64().
  77. // TODO(kenton@google.com): Use autoconf to detect availability of
  78. // gettimeofday().
  79. // TODO(kenton@google.com): There are other ways to get the time on
  80. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  81. // supports these. consider using them instead.
  82. #define GTEST_HAS_GETTIMEOFDAY_ 1
  83. #include <sys/time.h> // NOLINT
  84. #endif // GTEST_OS_WINDOWS_MINGW
  85. // cpplint thinks that the header is already included, so we want to
  86. // silence it.
  87. #include <windows.h> // NOLINT
  88. #else
  89. // Assume other platforms have gettimeofday().
  90. // TODO(kenton@google.com): Use autoconf to detect availability of
  91. // gettimeofday().
  92. #define GTEST_HAS_GETTIMEOFDAY_ 1
  93. // cpplint thinks that the header is already included, so we want to
  94. // silence it.
  95. #include <sys/time.h> // NOLINT
  96. #include <unistd.h> // NOLINT
  97. #endif // GTEST_OS_LINUX
  98. #if GTEST_HAS_EXCEPTIONS
  99. #include <stdexcept>
  100. #endif
  101. // Indicates that this translation unit is part of Google Test's
  102. // implementation. It must come before gtest-internal-inl.h is
  103. // included, or there will be a compiler error. This trick is to
  104. // prevent a user from accidentally including gtest-internal-inl.h in
  105. // his code.
  106. #define GTEST_IMPLEMENTATION_ 1
  107. #include "src/gtest-internal-inl.h"
  108. #undef GTEST_IMPLEMENTATION_
  109. #if GTEST_OS_WINDOWS
  110. #define vsnprintf _vsnprintf
  111. #endif // GTEST_OS_WINDOWS
  112. namespace testing {
  113. using internal::CountIf;
  114. using internal::ForEach;
  115. using internal::GetElementOr;
  116. using internal::Shuffle;
  117. // Constants.
  118. // A test whose test case name or test name matches this filter is
  119. // disabled and not run.
  120. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  121. // A test case whose name matches this filter is considered a death
  122. // test case and will be run before test cases whose name doesn't
  123. // match this filter.
  124. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  125. // A test filter that matches everything.
  126. static const char kUniversalFilter[] = "*";
  127. // The default output file for XML output.
  128. static const char kDefaultOutputFile[] = "test_detail.xml";
  129. // The environment variable name for the test shard index.
  130. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  131. // The environment variable name for the total number of test shards.
  132. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  133. // The environment variable name for the test shard status file.
  134. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  135. namespace internal {
  136. // The text used in failure messages to indicate the start of the
  137. // stack trace.
  138. const char kStackTraceMarker[] = "\nStack trace:\n";
  139. // g_help_flag is true iff the --help flag or an equivalent form is
  140. // specified on the command line.
  141. bool g_help_flag = false;
  142. } // namespace internal
  143. GTEST_DEFINE_bool_(
  144. also_run_disabled_tests,
  145. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  146. "Run disabled tests too, in addition to the tests normally being run.");
  147. GTEST_DEFINE_bool_(
  148. break_on_failure,
  149. internal::BoolFromGTestEnv("break_on_failure", false),
  150. "True iff a failed assertion should be a debugger break-point.");
  151. GTEST_DEFINE_bool_(
  152. catch_exceptions,
  153. internal::BoolFromGTestEnv("catch_exceptions", false),
  154. "True iff " GTEST_NAME_
  155. " should catch exceptions and treat them as test failures.");
  156. GTEST_DEFINE_string_(
  157. color,
  158. internal::StringFromGTestEnv("color", "auto"),
  159. "Whether to use colors in the output. Valid values: yes, no, "
  160. "and auto. 'auto' means to use colors if the output is "
  161. "being sent to a terminal and the TERM environment variable "
  162. "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
  163. GTEST_DEFINE_string_(
  164. filter,
  165. internal::StringFromGTestEnv("filter", kUniversalFilter),
  166. "A colon-separated list of glob (not regex) patterns "
  167. "for filtering the tests to run, optionally followed by a "
  168. "'-' and a : separated list of negative patterns (tests to "
  169. "exclude). A test is run if it matches one of the positive "
  170. "patterns and does not match any of the negative patterns.");
  171. GTEST_DEFINE_bool_(list_tests, false,
  172. "List all tests without running them.");
  173. GTEST_DEFINE_string_(
  174. output,
  175. internal::StringFromGTestEnv("output", ""),
  176. "A format (currently must be \"xml\"), optionally followed "
  177. "by a colon and an output file name or directory. A directory "
  178. "is indicated by a trailing pathname separator. "
  179. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  180. "If a directory is specified, output files will be created "
  181. "within that directory, with file-names based on the test "
  182. "executable's name and, if necessary, made unique by adding "
  183. "digits.");
  184. GTEST_DEFINE_bool_(
  185. print_time,
  186. internal::BoolFromGTestEnv("print_time", true),
  187. "True iff " GTEST_NAME_
  188. " should display elapsed time in text output.");
  189. GTEST_DEFINE_int32_(
  190. random_seed,
  191. internal::Int32FromGTestEnv("random_seed", 0),
  192. "Random number seed to use when shuffling test orders. Must be in range "
  193. "[1, 99999], or 0 to use a seed based on the current time.");
  194. GTEST_DEFINE_int32_(
  195. repeat,
  196. internal::Int32FromGTestEnv("repeat", 1),
  197. "How many times to repeat each test. Specify a negative number "
  198. "for repeating forever. Useful for shaking out flaky tests.");
  199. GTEST_DEFINE_bool_(
  200. show_internal_stack_frames, false,
  201. "True iff " GTEST_NAME_ " should include internal stack frames when "
  202. "printing test failure stack traces.");
  203. GTEST_DEFINE_bool_(
  204. shuffle,
  205. internal::BoolFromGTestEnv("shuffle", false),
  206. "True iff " GTEST_NAME_
  207. " should randomize tests' order on every run.");
  208. GTEST_DEFINE_int32_(
  209. stack_trace_depth,
  210. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  211. "The maximum number of stack frames to print when an "
  212. "assertion fails. The valid range is 0 through 100, inclusive.");
  213. GTEST_DEFINE_bool_(
  214. throw_on_failure,
  215. internal::BoolFromGTestEnv("throw_on_failure", false),
  216. "When this flag is specified, a failed assertion will throw an exception "
  217. "if exceptions are enabled or exit the program with a non-zero code "
  218. "otherwise.");
  219. namespace internal {
  220. // Generates a random number from [0, range), using a Linear
  221. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  222. // than kMaxRange.
  223. UInt32 Random::Generate(UInt32 range) {
  224. // These constants are the same as are used in glibc's rand(3).
  225. state_ = (1103515245U*state_ + 12345U) % kMaxRange;
  226. GTEST_CHECK_(range > 0)
  227. << "Cannot generate a number in the range [0, 0).";
  228. GTEST_CHECK_(range <= kMaxRange)
  229. << "Generation of a number in [0, " << range << ") was requested, "
  230. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  231. // Converting via modulus introduces a bit of downward bias, but
  232. // it's simple, and a linear congruential generator isn't too good
  233. // to begin with.
  234. return state_ % range;
  235. }
  236. // GTestIsInitialized() returns true iff the user has initialized
  237. // Google Test. Useful for catching the user mistake of not initializing
  238. // Google Test before calling RUN_ALL_TESTS().
  239. //
  240. // A user must call testing::InitGoogleTest() to initialize Google
  241. // Test. g_init_gtest_count is set to the number of times
  242. // InitGoogleTest() has been called. We don't protect this variable
  243. // under a mutex as it is only accessed in the main thread.
  244. int g_init_gtest_count = 0;
  245. static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
  246. // Iterates over a vector of TestCases, keeping a running sum of the
  247. // results of calling a given int-returning method on each.
  248. // Returns the sum.
  249. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  250. int (TestCase::*method)() const) {
  251. int sum = 0;
  252. for (size_t i = 0; i < case_list.size(); i++) {
  253. sum += (case_list[i]->*method)();
  254. }
  255. return sum;
  256. }
  257. // Returns true iff the test case passed.
  258. static bool TestCasePassed(const TestCase* test_case) {
  259. return test_case->should_run() && test_case->Passed();
  260. }
  261. // Returns true iff the test case failed.
  262. static bool TestCaseFailed(const TestCase* test_case) {
  263. return test_case->should_run() && test_case->Failed();
  264. }
  265. // Returns true iff test_case contains at least one test that should
  266. // run.
  267. static bool ShouldRunTestCase(const TestCase* test_case) {
  268. return test_case->should_run();
  269. }
  270. // AssertHelper constructor.
  271. AssertHelper::AssertHelper(TestPartResult::Type type,
  272. const char* file,
  273. int line,
  274. const char* message)
  275. : data_(new AssertHelperData(type, file, line, message)) {
  276. }
  277. AssertHelper::~AssertHelper() {
  278. delete data_;
  279. }
  280. // Message assignment, for assertion streaming support.
  281. void AssertHelper::operator=(const Message& message) const {
  282. UnitTest::GetInstance()->
  283. AddTestPartResult(data_->type, data_->file, data_->line,
  284. AppendUserMessage(data_->message, message),
  285. UnitTest::GetInstance()->impl()
  286. ->CurrentOsStackTraceExceptTop(1)
  287. // Skips the stack frame for this function itself.
  288. ); // NOLINT
  289. }
  290. // Mutex for linked pointers.
  291. GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  292. // Application pathname gotten in InitGoogleTest.
  293. String g_executable_path;
  294. // Returns the current application's name, removing directory path if that
  295. // is present.
  296. FilePath GetCurrentExecutableName() {
  297. FilePath result;
  298. #if GTEST_OS_WINDOWS
  299. result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
  300. #else
  301. result.Set(FilePath(g_executable_path));
  302. #endif // GTEST_OS_WINDOWS
  303. return result.RemoveDirectoryName();
  304. }
  305. // Functions for processing the gtest_output flag.
  306. // Returns the output format, or "" for normal printed output.
  307. String UnitTestOptions::GetOutputFormat() {
  308. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  309. if (gtest_output_flag == NULL) return String("");
  310. const char* const colon = strchr(gtest_output_flag, ':');
  311. return (colon == NULL) ?
  312. String(gtest_output_flag) :
  313. String(gtest_output_flag, colon - gtest_output_flag);
  314. }
  315. // Returns the name of the requested output file, or the default if none
  316. // was explicitly specified.
  317. String UnitTestOptions::GetAbsolutePathToOutputFile() {
  318. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  319. if (gtest_output_flag == NULL)
  320. return String("");
  321. const char* const colon = strchr(gtest_output_flag, ':');
  322. if (colon == NULL)
  323. return String(internal::FilePath::ConcatPaths(
  324. internal::FilePath(
  325. UnitTest::GetInstance()->original_working_dir()),
  326. internal::FilePath(kDefaultOutputFile)).ToString() );
  327. internal::FilePath output_name(colon + 1);
  328. if (!output_name.IsAbsolutePath())
  329. // TODO(wan@google.com): on Windows \some\path is not an absolute
  330. // path (as its meaning depends on the current drive), yet the
  331. // following logic for turning it into an absolute path is wrong.
  332. // Fix it.
  333. output_name = internal::FilePath::ConcatPaths(
  334. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  335. internal::FilePath(colon + 1));
  336. if (!output_name.IsDirectory())
  337. return output_name.ToString();
  338. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  339. output_name, internal::GetCurrentExecutableName(),
  340. GetOutputFormat().c_str()));
  341. return result.ToString();
  342. }
  343. // Returns true iff the wildcard pattern matches the string. The
  344. // first ':' or '\0' character in pattern marks the end of it.
  345. //
  346. // This recursive algorithm isn't very efficient, but is clear and
  347. // works well enough for matching test names, which are short.
  348. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  349. const char *str) {
  350. switch (*pattern) {
  351. case '\0':
  352. case ':': // Either ':' or '\0' marks the end of the pattern.
  353. return *str == '\0';
  354. case '?': // Matches any single character.
  355. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  356. case '*': // Matches any string (possibly empty) of characters.
  357. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  358. PatternMatchesString(pattern + 1, str);
  359. default: // Non-special character. Matches itself.
  360. return *pattern == *str &&
  361. PatternMatchesString(pattern + 1, str + 1);
  362. }
  363. }
  364. bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
  365. const char *cur_pattern = filter;
  366. for (;;) {
  367. if (PatternMatchesString(cur_pattern, name.c_str())) {
  368. return true;
  369. }
  370. // Finds the next pattern in the filter.
  371. cur_pattern = strchr(cur_pattern, ':');
  372. // Returns if no more pattern can be found.
  373. if (cur_pattern == NULL) {
  374. return false;
  375. }
  376. // Skips the pattern separater (the ':' character).
  377. cur_pattern++;
  378. }
  379. }
  380. // TODO(keithray): move String function implementations to gtest-string.cc.
  381. // Returns true iff the user-specified filter matches the test case
  382. // name and the test name.
  383. bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
  384. const String &test_name) {
  385. const String& full_name = String::Format("%s.%s",
  386. test_case_name.c_str(),
  387. test_name.c_str());
  388. // Split --gtest_filter at '-', if there is one, to separate into
  389. // positive filter and negative filter portions
  390. const char* const p = GTEST_FLAG(filter).c_str();
  391. const char* const dash = strchr(p, '-');
  392. String positive;
  393. String negative;
  394. if (dash == NULL) {
  395. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  396. negative = String("");
  397. } else {
  398. positive = String(p, dash - p); // Everything up to the dash
  399. negative = String(dash+1); // Everything after the dash
  400. if (positive.empty()) {
  401. // Treat '-test1' as the same as '*-test1'
  402. positive = kUniversalFilter;
  403. }
  404. }
  405. // A filter is a colon-separated list of patterns. It matches a
  406. // test if any pattern in it matches the test.
  407. return (MatchesFilter(full_name, positive.c_str()) &&
  408. !MatchesFilter(full_name, negative.c_str()));
  409. }
  410. #if GTEST_OS_WINDOWS
  411. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  412. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  413. // This function is useful as an __except condition.
  414. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  415. // Google Test should handle an exception if:
  416. // 1. the user wants it to, AND
  417. // 2. this is not a breakpoint exception.
  418. return (GTEST_FLAG(catch_exceptions) &&
  419. exception_code != EXCEPTION_BREAKPOINT) ?
  420. EXCEPTION_EXECUTE_HANDLER :
  421. EXCEPTION_CONTINUE_SEARCH;
  422. }
  423. #endif // GTEST_OS_WINDOWS
  424. } // namespace internal
  425. // The c'tor sets this object as the test part result reporter used by
  426. // Google Test. The 'result' parameter specifies where to report the
  427. // results. Intercepts only failures from the current thread.
  428. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  429. TestPartResultArray* result)
  430. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  431. result_(result) {
  432. Init();
  433. }
  434. // The c'tor sets this object as the test part result reporter used by
  435. // Google Test. The 'result' parameter specifies where to report the
  436. // results.
  437. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  438. InterceptMode intercept_mode, TestPartResultArray* result)
  439. : intercept_mode_(intercept_mode),
  440. result_(result) {
  441. Init();
  442. }
  443. void ScopedFakeTestPartResultReporter::Init() {
  444. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  445. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  446. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  447. impl->SetGlobalTestPartResultReporter(this);
  448. } else {
  449. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  450. impl->SetTestPartResultReporterForCurrentThread(this);
  451. }
  452. }
  453. // The d'tor restores the test part result reporter used by Google Test
  454. // before.
  455. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  456. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  457. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  458. impl->SetGlobalTestPartResultReporter(old_reporter_);
  459. } else {
  460. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  461. }
  462. }
  463. // Increments the test part result count and remembers the result.
  464. // This method is from the TestPartResultReporterInterface interface.
  465. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  466. const TestPartResult& result) {
  467. result_->Append(result);
  468. }
  469. namespace internal {
  470. // Returns the type ID of ::testing::Test. We should always call this
  471. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  472. // testing::Test. This is to work around a suspected linker bug when
  473. // using Google Test as a framework on Mac OS X. The bug causes
  474. // GetTypeId< ::testing::Test>() to return different values depending
  475. // on whether the call is from the Google Test framework itself or
  476. // from user test code. GetTestTypeId() is guaranteed to always
  477. // return the same value, as it always calls GetTypeId<>() from the
  478. // gtest.cc, which is within the Google Test framework.
  479. TypeId GetTestTypeId() {
  480. return GetTypeId<Test>();
  481. }
  482. // The value of GetTestTypeId() as seen from within the Google Test
  483. // library. This is solely for testing GetTestTypeId().
  484. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  485. // This predicate-formatter checks that 'results' contains a test part
  486. // failure of the given type and that the failure message contains the
  487. // given substring.
  488. AssertionResult HasOneFailure(const char* /* results_expr */,
  489. const char* /* type_expr */,
  490. const char* /* substr_expr */,
  491. const TestPartResultArray& results,
  492. TestPartResult::Type type,
  493. const char* substr) {
  494. const String expected(type == TestPartResult::kFatalFailure ?
  495. "1 fatal failure" :
  496. "1 non-fatal failure");
  497. Message msg;
  498. if (results.size() != 1) {
  499. msg << "Expected: " << expected << "\n"
  500. << " Actual: " << results.size() << " failures";
  501. for (int i = 0; i < results.size(); i++) {
  502. msg << "\n" << results.GetTestPartResult(i);
  503. }
  504. return AssertionFailure(msg);
  505. }
  506. const TestPartResult& r = results.GetTestPartResult(0);
  507. if (r.type() != type) {
  508. msg << "Expected: " << expected << "\n"
  509. << " Actual:\n"
  510. << r;
  511. return AssertionFailure(msg);
  512. }
  513. if (strstr(r.message(), substr) == NULL) {
  514. msg << "Expected: " << expected << " containing \""
  515. << substr << "\"\n"
  516. << " Actual:\n"
  517. << r;
  518. return AssertionFailure(msg);
  519. }
  520. return AssertionSuccess();
  521. }
  522. // The constructor of SingleFailureChecker remembers where to look up
  523. // test part results, what type of failure we expect, and what
  524. // substring the failure message should contain.
  525. SingleFailureChecker:: SingleFailureChecker(
  526. const TestPartResultArray* results,
  527. TestPartResult::Type type,
  528. const char* substr)
  529. : results_(results),
  530. type_(type),
  531. substr_(substr) {}
  532. // The destructor of SingleFailureChecker verifies that the given
  533. // TestPartResultArray contains exactly one failure that has the given
  534. // type and contains the given substring. If that's not the case, a
  535. // non-fatal failure will be generated.
  536. SingleFailureChecker::~SingleFailureChecker() {
  537. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
  538. }
  539. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  540. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  541. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  542. const TestPartResult& result) {
  543. unit_test_->current_test_result()->AddTestPartResult(result);
  544. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  545. }
  546. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  547. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  548. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  549. const TestPartResult& result) {
  550. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  551. }
  552. // Returns the global test part result reporter.
  553. TestPartResultReporterInterface*
  554. UnitTestImpl::GetGlobalTestPartResultReporter() {
  555. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  556. return global_test_part_result_repoter_;
  557. }
  558. // Sets the global test part result reporter.
  559. void UnitTestImpl::SetGlobalTestPartResultReporter(
  560. TestPartResultReporterInterface* reporter) {
  561. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  562. global_test_part_result_repoter_ = reporter;
  563. }
  564. // Returns the test part result reporter for the current thread.
  565. TestPartResultReporterInterface*
  566. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  567. return per_thread_test_part_result_reporter_.get();
  568. }
  569. // Sets the test part result reporter for the current thread.
  570. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  571. TestPartResultReporterInterface* reporter) {
  572. per_thread_test_part_result_reporter_.set(reporter);
  573. }
  574. // Gets the number of successful test cases.
  575. int UnitTestImpl::successful_test_case_count() const {
  576. return CountIf(test_cases_, TestCasePassed);
  577. }
  578. // Gets the number of failed test cases.
  579. int UnitTestImpl::failed_test_case_count() const {
  580. return CountIf(test_cases_, TestCaseFailed);
  581. }
  582. // Gets the number of all test cases.
  583. int UnitTestImpl::total_test_case_count() const {
  584. return static_cast<int>(test_cases_.size());
  585. }
  586. // Gets the number of all test cases that contain at least one test
  587. // that should run.
  588. int UnitTestImpl::test_case_to_run_count() const {
  589. return CountIf(test_cases_, ShouldRunTestCase);
  590. }
  591. // Gets the number of successful tests.
  592. int UnitTestImpl::successful_test_count() const {
  593. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  594. }
  595. // Gets the number of failed tests.
  596. int UnitTestImpl::failed_test_count() const {
  597. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  598. }
  599. // Gets the number of disabled tests.
  600. int UnitTestImpl::disabled_test_count() const {
  601. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  602. }
  603. // Gets the number of all tests.
  604. int UnitTestImpl::total_test_count() const {
  605. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  606. }
  607. // Gets the number of tests that should run.
  608. int UnitTestImpl::test_to_run_count() const {
  609. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  610. }
  611. // Returns the current OS stack trace as a String.
  612. //
  613. // The maximum number of stack frames to be included is specified by
  614. // the gtest_stack_trace_depth flag. The skip_count parameter
  615. // specifies the number of top frames to be skipped, which doesn't
  616. // count against the number of frames to be included.
  617. //
  618. // For example, if Foo() calls Bar(), which in turn calls
  619. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  620. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  621. String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  622. (void)skip_count;
  623. return String("");
  624. }
  625. // Returns the current time in milliseconds.
  626. TimeInMillis GetTimeInMillis() {
  627. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  628. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  629. // http://analogous.blogspot.com/2005/04/epoch.html
  630. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  631. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  632. const DWORD kTenthMicrosInMilliSecond = 10000;
  633. SYSTEMTIME now_systime;
  634. FILETIME now_filetime;
  635. ULARGE_INTEGER now_int64;
  636. // TODO(kenton@google.com): Shouldn't this just use
  637. // GetSystemTimeAsFileTime()?
  638. GetSystemTime(&now_systime);
  639. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  640. now_int64.LowPart = now_filetime.dwLowDateTime;
  641. now_int64.HighPart = now_filetime.dwHighDateTime;
  642. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  643. kJavaEpochToWinFileTimeDelta;
  644. return now_int64.QuadPart;
  645. }
  646. return 0;
  647. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  648. __timeb64 now;
  649. #ifdef _MSC_VER
  650. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  651. // (deprecated function) there.
  652. // TODO(kenton@google.com): Use GetTickCount()? Or use
  653. // SystemTimeToFileTime()
  654. #pragma warning(push) // Saves the current warning state.
  655. #pragma warning(disable:4996) // Temporarily disables warning 4996.
  656. _ftime64(&now);
  657. #pragma warning(pop) // Restores the warning state.
  658. #else
  659. _ftime64(&now);
  660. #endif // _MSC_VER
  661. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  662. #elif GTEST_HAS_GETTIMEOFDAY_
  663. struct timeval now;
  664. gettimeofday(&now, NULL);
  665. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  666. #else
  667. #error "Don't know how to get the current time on your system."
  668. #endif
  669. }
  670. // Utilities
  671. // class String
  672. // Returns the input enclosed in double quotes if it's not NULL;
  673. // otherwise returns "(null)". For example, "\"Hello\"" is returned
  674. // for input "Hello".
  675. //
  676. // This is useful for printing a C string in the syntax of a literal.
  677. //
  678. // Known issue: escape sequences are not handled yet.
  679. String String::ShowCStringQuoted(const char* c_str) {
  680. return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
  681. }
  682. // Copies at most length characters from str into a newly-allocated
  683. // piece of memory of size length+1. The memory is allocated with new[].
  684. // A terminating null byte is written to the memory, and a pointer to it
  685. // is returned. If str is NULL, NULL is returned.
  686. static char* CloneString(const char* str, size_t length) {
  687. if (str == NULL) {
  688. return NULL;
  689. } else {
  690. char* const clone = new char[length + 1];
  691. posix::StrNCpy(clone, str, length);
  692. clone[length] = '\0';
  693. return clone;
  694. }
  695. }
  696. // Clones a 0-terminated C string, allocating memory using new. The
  697. // caller is responsible for deleting[] the return value. Returns the
  698. // cloned string, or NULL if the input is NULL.
  699. const char * String::CloneCString(const char* c_str) {
  700. return (c_str == NULL) ?
  701. NULL : CloneString(c_str, strlen(c_str));
  702. }
  703. #if GTEST_OS_WINDOWS_MOBILE
  704. // Creates a UTF-16 wide string from the given ANSI string, allocating
  705. // memory using new. The caller is responsible for deleting the return
  706. // value using delete[]. Returns the wide string, or NULL if the
  707. // input is NULL.
  708. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  709. if (!ansi) return NULL;
  710. const int length = strlen(ansi);
  711. const int unicode_length =
  712. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  713. NULL, 0);
  714. WCHAR* unicode = new WCHAR[unicode_length + 1];
  715. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  716. unicode, unicode_length);
  717. unicode[unicode_length] = 0;
  718. return unicode;
  719. }
  720. // Creates an ANSI string from the given wide string, allocating
  721. // memory using new. The caller is responsible for deleting the return
  722. // value using delete[]. Returns the ANSI string, or NULL if the
  723. // input is NULL.
  724. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  725. if (!utf16_str) return NULL;
  726. const int ansi_length =
  727. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  728. NULL, 0, NULL, NULL);
  729. char* ansi = new char[ansi_length + 1];
  730. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  731. ansi, ansi_length, NULL, NULL);
  732. ansi[ansi_length] = 0;
  733. return ansi;
  734. }
  735. #endif // GTEST_OS_WINDOWS_MOBILE
  736. // Compares two C strings. Returns true iff they have the same content.
  737. //
  738. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  739. // C string is considered different to any non-NULL C string,
  740. // including the empty string.
  741. bool String::CStringEquals(const char * lhs, const char * rhs) {
  742. if ( lhs == NULL ) return rhs == NULL;
  743. if ( rhs == NULL ) return false;
  744. return strcmp(lhs, rhs) == 0;
  745. }
  746. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  747. // Converts an array of wide chars to a narrow string using the UTF-8
  748. // encoding, and streams the result to the given Message object.
  749. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  750. Message* msg) {
  751. // TODO(wan): consider allowing a testing::String object to
  752. // contain '\0'. This will make it behave more like std::string,
  753. // and will allow ToUtf8String() to return the correct encoding
  754. // for '\0' s.t. we can get rid of the conditional here (and in
  755. // several other places).
  756. for (size_t i = 0; i != length; ) { // NOLINT
  757. if (wstr[i] != L'\0') {
  758. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  759. while (i != length && wstr[i] != L'\0')
  760. i++;
  761. } else {
  762. *msg << '\0';
  763. i++;
  764. }
  765. }
  766. }
  767. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  768. } // namespace internal
  769. #if GTEST_HAS_STD_WSTRING
  770. // Converts the given wide string to a narrow string using the UTF-8
  771. // encoding, and streams the result to this Message object.
  772. Message& Message::operator <<(const ::std::wstring& wstr) {
  773. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  774. return *this;
  775. }
  776. #endif // GTEST_HAS_STD_WSTRING
  777. #if GTEST_HAS_GLOBAL_WSTRING
  778. // Converts the given wide string to a narrow string using the UTF-8
  779. // encoding, and streams the result to this Message object.
  780. Message& Message::operator <<(const ::wstring& wstr) {
  781. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  782. return *this;
  783. }
  784. #endif // GTEST_HAS_GLOBAL_WSTRING
  785. namespace internal {
  786. // Formats a value to be used in a failure message.
  787. // For a char value, we print it as a C++ char literal and as an
  788. // unsigned integer (both in decimal and in hexadecimal).
  789. String FormatForFailureMessage(char ch) {
  790. const unsigned int ch_as_uint = ch;
  791. // A String object cannot contain '\0', so we print "\\0" when ch is
  792. // '\0'.
  793. return String::Format("'%s' (%u, 0x%X)",
  794. ch ? String::Format("%c", ch).c_str() : "\\0",
  795. ch_as_uint, ch_as_uint);
  796. }
  797. // For a wchar_t value, we print it as a C++ wchar_t literal and as an
  798. // unsigned integer (both in decimal and in hexidecimal).
  799. String FormatForFailureMessage(wchar_t wchar) {
  800. // The C++ standard doesn't specify the exact size of the wchar_t
  801. // type. It just says that it shall have the same size as another
  802. // integral type, called its underlying type.
  803. //
  804. // Therefore, in order to print a wchar_t value in the numeric form,
  805. // we first convert it to the largest integral type (UInt64) and
  806. // then print the converted value.
  807. //
  808. // We use streaming to print the value as "%llu" doesn't work
  809. // correctly with MSVC 7.1.
  810. const UInt64 wchar_as_uint64 = wchar;
  811. Message msg;
  812. // A String object cannot contain '\0', so we print "\\0" when wchar is
  813. // L'\0'.
  814. char buffer[32]; // CodePointToUtf8 requires a buffer that big.
  815. msg << "L'"
  816. << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
  817. << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
  818. << wchar_as_uint64 << ")";
  819. return msg.GetString();
  820. }
  821. } // namespace internal
  822. // AssertionResult constructors.
  823. // Used in EXPECT_TRUE/FALSE(assertion_result).
  824. AssertionResult::AssertionResult(const AssertionResult& other)
  825. : success_(other.success_),
  826. message_(other.message_.get() != NULL ?
  827. new internal::String(*other.message_) :
  828. static_cast<internal::String*>(NULL)) {
  829. }
  830. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  831. AssertionResult AssertionResult::operator!() const {
  832. AssertionResult negation(!success_);
  833. if (message_.get() != NULL)
  834. negation << *message_;
  835. return negation;
  836. }
  837. // Makes a successful assertion result.
  838. AssertionResult AssertionSuccess() {
  839. return AssertionResult(true);
  840. }
  841. // Makes a failed assertion result.
  842. AssertionResult AssertionFailure() {
  843. return AssertionResult(false);
  844. }
  845. // Makes a failed assertion result with the given failure message.
  846. // Deprecated; use AssertionFailure() << message.
  847. AssertionResult AssertionFailure(const Message& message) {
  848. return AssertionFailure() << message;
  849. }
  850. namespace internal {
  851. // Constructs and returns the message for an equality assertion
  852. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  853. //
  854. // The first four parameters are the expressions used in the assertion
  855. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  856. // where foo is 5 and bar is 6, we have:
  857. //
  858. // expected_expression: "foo"
  859. // actual_expression: "bar"
  860. // expected_value: "5"
  861. // actual_value: "6"
  862. //
  863. // The ignoring_case parameter is true iff the assertion is a
  864. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  865. // be inserted into the message.
  866. AssertionResult EqFailure(const char* expected_expression,
  867. const char* actual_expression,
  868. const String& expected_value,
  869. const String& actual_value,
  870. bool ignoring_case) {
  871. Message msg;
  872. msg << "Value of: " << actual_expression;
  873. if (actual_value != actual_expression) {
  874. msg << "\n Actual: " << actual_value;
  875. }
  876. msg << "\nExpected: " << expected_expression;
  877. if (ignoring_case) {
  878. msg << " (ignoring case)";
  879. }
  880. if (expected_value != expected_expression) {
  881. msg << "\nWhich is: " << expected_value;
  882. }
  883. return AssertionFailure(msg);
  884. }
  885. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  886. String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
  887. const char* expression_text,
  888. const char* actual_predicate_value,
  889. const char* expected_predicate_value) {
  890. const char* actual_message = assertion_result.message();
  891. Message msg;
  892. msg << "Value of: " << expression_text
  893. << "\n Actual: " << actual_predicate_value;
  894. if (actual_message[0] != '\0')
  895. msg << " (" << actual_message << ")";
  896. msg << "\nExpected: " << expected_predicate_value;
  897. return msg.GetString();
  898. }
  899. // Helper function for implementing ASSERT_NEAR.
  900. AssertionResult DoubleNearPredFormat(const char* expr1,
  901. const char* expr2,
  902. const char* abs_error_expr,
  903. double val1,
  904. double val2,
  905. double abs_error) {
  906. const double diff = fabs(val1 - val2);
  907. if (diff <= abs_error) return AssertionSuccess();
  908. // TODO(wan): do not print the value of an expression if it's
  909. // already a literal.
  910. Message msg;
  911. msg << "The difference between " << expr1 << " and " << expr2
  912. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  913. << expr1 << " evaluates to " << val1 << ",\n"
  914. << expr2 << " evaluates to " << val2 << ", and\n"
  915. << abs_error_expr << " evaluates to " << abs_error << ".";
  916. return AssertionFailure(msg);
  917. }
  918. // Helper template for implementing FloatLE() and DoubleLE().
  919. template <typename RawType>
  920. AssertionResult FloatingPointLE(const char* expr1,
  921. const char* expr2,
  922. RawType val1,
  923. RawType val2) {
  924. // Returns success if val1 is less than val2,
  925. if (val1 < val2) {
  926. return AssertionSuccess();
  927. }
  928. // or if val1 is almost equal to val2.
  929. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  930. if (lhs.AlmostEquals(rhs)) {
  931. return AssertionSuccess();
  932. }
  933. // Note that the above two checks will both fail if either val1 or
  934. // val2 is NaN, as the IEEE floating-point standard requires that
  935. // any predicate involving a NaN must return false.
  936. StrStream val1_ss;
  937. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  938. << val1;
  939. StrStream val2_ss;
  940. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  941. << val2;
  942. Message msg;
  943. msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  944. << " Actual: " << StrStreamToString(&val1_ss) << " vs "
  945. << StrStreamToString(&val2_ss);
  946. return AssertionFailure(msg);
  947. }
  948. } // namespace internal
  949. // Asserts that val1 is less than, or almost equal to, val2. Fails
  950. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  951. AssertionResult FloatLE(const char* expr1, const char* expr2,
  952. float val1, float val2) {
  953. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  954. }
  955. // Asserts that val1 is less than, or almost equal to, val2. Fails
  956. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  957. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  958. double val1, double val2) {
  959. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  960. }
  961. namespace internal {
  962. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  963. // arguments.
  964. AssertionResult CmpHelperEQ(const char* expected_expression,
  965. const char* actual_expression,
  966. BiggestInt expected,
  967. BiggestInt actual) {
  968. if (expected == actual) {
  969. return AssertionSuccess();
  970. }
  971. return EqFailure(expected_expression,
  972. actual_expression,
  973. FormatForComparisonFailureMessage(expected, actual),
  974. FormatForComparisonFailureMessage(actual, expected),
  975. false);
  976. }
  977. // A macro for implementing the helper functions needed to implement
  978. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  979. // just to avoid copy-and-paste of similar code.
  980. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  981. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  982. BiggestInt val1, BiggestInt val2) {\
  983. if (val1 op val2) {\
  984. return AssertionSuccess();\
  985. } else {\
  986. Message msg;\
  987. msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
  988. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  989. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  990. return AssertionFailure(msg);\
  991. }\
  992. }
  993. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  994. // enum arguments.
  995. GTEST_IMPL_CMP_HELPER_(NE, !=)
  996. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  997. // enum arguments.
  998. GTEST_IMPL_CMP_HELPER_(LE, <=)
  999. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  1000. // enum arguments.
  1001. GTEST_IMPL_CMP_HELPER_(LT, < )
  1002. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  1003. // enum arguments.
  1004. GTEST_IMPL_CMP_HELPER_(GE, >=)
  1005. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  1006. // enum arguments.
  1007. GTEST_IMPL_CMP_HELPER_(GT, > )
  1008. #undef GTEST_IMPL_CMP_HELPER_
  1009. // The helper function for {ASSERT|EXPECT}_STREQ.
  1010. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  1011. const char* actual_expression,
  1012. const char* expected,
  1013. const char* actual) {
  1014. if (String::CStringEquals(expected, actual)) {
  1015. return AssertionSuccess();
  1016. }
  1017. return EqFailure(expected_expression,
  1018. actual_expression,
  1019. String::ShowCStringQuoted(expected),
  1020. String::ShowCStringQuoted(actual),
  1021. false);
  1022. }
  1023. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1024. AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
  1025. const char* actual_expression,
  1026. const char* expected,
  1027. const char* actual) {
  1028. if (String::CaseInsensitiveCStringEquals(expected, actual)) {
  1029. return AssertionSuccess();
  1030. }
  1031. return EqFailure(expected_expression,
  1032. actual_expression,
  1033. String::ShowCStringQuoted(expected),
  1034. String::ShowCStringQuoted(actual),
  1035. true);
  1036. }
  1037. // The helper function for {ASSERT|EXPECT}_STRNE.
  1038. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1039. const char* s2_expression,
  1040. const char* s1,
  1041. const char* s2) {
  1042. if (!String::CStringEquals(s1, s2)) {
  1043. return AssertionSuccess();
  1044. } else {
  1045. Message msg;
  1046. msg << "Expected: (" << s1_expression << ") != ("
  1047. << s2_expression << "), actual: \""
  1048. << s1 << "\" vs \"" << s2 << "\"";
  1049. return AssertionFailure(msg);
  1050. }
  1051. }
  1052. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  1053. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1054. const char* s2_expression,
  1055. const char* s1,
  1056. const char* s2) {
  1057. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  1058. return AssertionSuccess();
  1059. } else {
  1060. Message msg;
  1061. msg << "Expected: (" << s1_expression << ") != ("
  1062. << s2_expression << ") (ignoring case), actual: \""
  1063. << s1 << "\" vs \"" << s2 << "\"";
  1064. return AssertionFailure(msg);
  1065. }
  1066. }
  1067. } // namespace internal
  1068. namespace {
  1069. // Helper functions for implementing IsSubString() and IsNotSubstring().
  1070. // This group of overloaded functions return true iff needle is a
  1071. // substring of haystack. NULL is considered a substring of itself
  1072. // only.
  1073. bool IsSubstringPred(const char* needle, const char* haystack) {
  1074. if (needle == NULL || haystack == NULL)
  1075. return needle == haystack;
  1076. return strstr(haystack, needle) != NULL;
  1077. }
  1078. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  1079. if (needle == NULL || haystack == NULL)
  1080. return needle == haystack;
  1081. return wcsstr(haystack, needle) != NULL;
  1082. }
  1083. // StringType here can be either ::std::string or ::std::wstring.
  1084. template <typename StringType>
  1085. bool IsSubstringPred(const StringType& needle,
  1086. const StringType& haystack) {
  1087. return haystack.find(needle) != StringType::npos;
  1088. }
  1089. // This function implements either IsSubstring() or IsNotSubstring(),
  1090. // depending on the value of the expected_to_be_substring parameter.
  1091. // StringType here can be const char*, const wchar_t*, ::std::string,
  1092. // or ::std::wstring.
  1093. template <typename StringType>
  1094. AssertionResult IsSubstringImpl(
  1095. bool expected_to_be_substring,
  1096. const char* needle_expr, const char* haystack_expr,
  1097. const StringType& needle, const StringType& haystack) {
  1098. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  1099. return AssertionSuccess();
  1100. const bool is_wide_string = sizeof(needle[0]) > 1;
  1101. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  1102. return AssertionFailure(
  1103. Message()
  1104. << "Value of: " << needle_expr << "\n"
  1105. << " Actual: " << begin_string_quote << needle << "\"\n"
  1106. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  1107. << "a substring of " << haystack_expr << "\n"
  1108. << "Which is: " << begin_string_quote << haystack << "\"");
  1109. }
  1110. } // namespace
  1111. // IsSubstring() and IsNotSubstring() check whether needle is a
  1112. // substring of haystack (NULL is considered a substring of itself
  1113. // only), and return an appropriate error message when they fail.
  1114. AssertionResult IsSubstring(
  1115. const char* needle_expr, const char* haystack_expr,
  1116. const char* needle, const char* haystack) {
  1117. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1118. }
  1119. AssertionResult IsSubstring(
  1120. const char* needle_expr, const char* haystack_expr,
  1121. const wchar_t* needle, const wchar_t* haystack) {
  1122. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1123. }
  1124. AssertionResult IsNotSubstring(
  1125. const char* needle_expr, const char* haystack_expr,
  1126. const char* needle, const char* haystack) {
  1127. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1128. }
  1129. AssertionResult IsNotSubstring(
  1130. const char* needle_expr, const char* haystack_expr,
  1131. const wchar_t* needle, const wchar_t* haystack) {
  1132. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1133. }
  1134. AssertionResult IsSubstring(
  1135. const char* needle_expr, const char* haystack_expr,
  1136. const ::std::string& needle, const ::std::string& haystack) {
  1137. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1138. }
  1139. AssertionResult IsNotSubstring(
  1140. const char* needle_expr, const char* haystack_expr,
  1141. const ::std::string& needle, const ::std::string& haystack) {
  1142. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1143. }
  1144. #if GTEST_HAS_STD_WSTRING
  1145. AssertionResult IsSubstring(
  1146. const char* needle_expr, const char* haystack_expr,
  1147. const ::std::wstring& needle, const ::std::wstring& haystack) {
  1148. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1149. }
  1150. AssertionResult IsNotSubstring(
  1151. const char* needle_expr, const char* haystack_expr,
  1152. const ::std::wstring& needle, const ::std::wstring& haystack) {
  1153. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1154. }
  1155. #endif // GTEST_HAS_STD_WSTRING
  1156. namespace internal {
  1157. #if GTEST_OS_WINDOWS
  1158. namespace {
  1159. // Helper function for IsHRESULT{SuccessFailure} predicates
  1160. AssertionResult HRESULTFailureHelper(const char* expr,
  1161. const char* expected,
  1162. long hr) { // NOLINT
  1163. #if GTEST_OS_WINDOWS_MOBILE
  1164. // Windows CE doesn't support FormatMessage.
  1165. const char error_text[] = "";
  1166. #else
  1167. // Looks up the human-readable system message for the HRESULT code
  1168. // and since we're not passing any params to FormatMessage, we don't
  1169. // want inserts expanded.
  1170. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  1171. FORMAT_MESSAGE_IGNORE_INSERTS;
  1172. const DWORD kBufSize = 4096; // String::Format can't exceed this length.
  1173. // Gets the system's human readable message string for this HRESULT.
  1174. char error_text[kBufSize] = { '\0' };
  1175. DWORD message_length = ::FormatMessageA(kFlags,
  1176. 0, // no source, we're asking system
  1177. hr, // the error
  1178. 0, // no line width restrictions
  1179. error_text, // output buffer
  1180. kBufSize, // buf size
  1181. NULL); // no arguments for inserts
  1182. // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
  1183. for (; message_length && isspace(error_text[message_length - 1]);
  1184. --message_length) {
  1185. error_text[message_length - 1] = '\0';
  1186. }
  1187. #endif // GTEST_OS_WINDOWS_MOBILE
  1188. const String error_hex(String::Format("0x%08X ", hr));
  1189. Message msg;
  1190. msg << "Expected: " << expr << " " << expected << ".\n"
  1191. << " Actual: " << error_hex << error_text << "\n";
  1192. return ::testing::AssertionFailure(msg);
  1193. }
  1194. } // namespace
  1195. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  1196. if (SUCCEEDED(hr)) {
  1197. return AssertionSuccess();
  1198. }
  1199. return HRESULTFailureHelper(expr, "succeeds", hr);
  1200. }
  1201. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  1202. if (FAILED(hr)) {
  1203. return AssertionSuccess();
  1204. }
  1205. return HRESULTFailureHelper(expr, "fails", hr);
  1206. }
  1207. #endif // GTEST_OS_WINDOWS
  1208. // Utility functions for encoding Unicode text (wide strings) in
  1209. // UTF-8.
  1210. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
  1211. // like this:
  1212. //
  1213. // Code-point length Encoding
  1214. // 0 - 7 bits 0xxxxxxx
  1215. // 8 - 11 bits 110xxxxx 10xxxxxx
  1216. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  1217. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1218. // The maximum code-point a one-byte UTF-8 sequence can represent.
  1219. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  1220. // The maximum code-point a two-byte UTF-8 sequence can represent.
  1221. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  1222. // The maximum code-point a three-byte UTF-8 sequence can represent.
  1223. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  1224. // The maximum code-point a four-byte UTF-8 sequence can represent.
  1225. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  1226. // Chops off the n lowest bits from a bit pattern. Returns the n
  1227. // lowest bits. As a side effect, the original bit pattern will be
  1228. // shifted to the right by n bits.
  1229. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  1230. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  1231. *bits >>= n;
  1232. return low_bits;
  1233. }
  1234. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  1235. // code_point parameter is of type UInt32 because wchar_t may not be
  1236. // wide enough to contain a code point.
  1237. // The output buffer str must containt at least 32 characters.
  1238. // The function returns the address of the output buffer.
  1239. // If the code_point is not a valid Unicode code point
  1240. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
  1241. // as '(Invalid Unicode 0xXXXXXXXX)'.
  1242. char* CodePointToUtf8(UInt32 code_point, char* str) {
  1243. if (code_point <= kMaxCodePoint1) {
  1244. str[1] = '\0';
  1245. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  1246. } else if (code_point <= kMaxCodePoint2) {
  1247. str[2] = '\0';
  1248. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1249. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  1250. } else if (code_point <= kMaxCodePoint3) {
  1251. str[3] = '\0';
  1252. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1253. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1254. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  1255. } else if (code_point <= kMaxCodePoint4) {
  1256. str[4] = '\0';
  1257. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1258. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1259. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1260. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  1261. } else {
  1262. // The longest string String::Format can produce when invoked
  1263. // with these parameters is 28 character long (not including
  1264. // the terminating nul character). We are asking for 32 character
  1265. // buffer just in case. This is also enough for strncpy to
  1266. // null-terminate the destination string.
  1267. posix::StrNCpy(
  1268. str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
  1269. str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
  1270. // the result unterminated.
  1271. }
  1272. return str;
  1273. }
  1274. // The following two functions only make sense if the the system
  1275. // uses UTF-16 for wide string encoding. All supported systems
  1276. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  1277. // Determines if the arguments constitute UTF-16 surrogate pair
  1278. // and thus should be combined into a single Unicode code point
  1279. // using CreateCodePointFromUtf16SurrogatePair.
  1280. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  1281. return sizeof(wchar_t) == 2 &&
  1282. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  1283. }
  1284. // Creates a Unicode code point from UTF16 surrogate pair.
  1285. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  1286. wchar_t second) {
  1287. const UInt32 mask = (1 << 10) - 1;
  1288. return (sizeof(wchar_t) == 2) ?
  1289. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  1290. // This function should not be called when the condition is
  1291. // false, but we provide a sensible default in case it is.
  1292. static_cast<UInt32>(first);
  1293. }
  1294. // Converts a wide string to a narrow string in UTF-8 encoding.
  1295. // The wide string is assumed to have the following encoding:
  1296. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  1297. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  1298. // Parameter str points to a null-terminated wide string.
  1299. // Parameter num_chars may additionally limit the number
  1300. // of wchar_t characters processed. -1 is used when the entire string
  1301. // should be processed.
  1302. // If the string contains code points that are not valid Unicode code points
  1303. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  1304. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  1305. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  1306. // will be encoded as individual Unicode characters from Basic Normal Plane.
  1307. String WideStringToUtf8(const wchar_t* str, int num_chars) {
  1308. if (num_chars == -1)
  1309. num_chars = static_cast<int>(wcslen(str));
  1310. StrStream stream;
  1311. for (int i = 0; i < num_chars; ++i) {
  1312. UInt32 unicode_code_point;
  1313. if (str[i] == L'\0') {
  1314. break;
  1315. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  1316. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  1317. str[i + 1]);
  1318. i++;
  1319. } else {
  1320. unicode_code_point = static_cast<UInt32>(str[i]);
  1321. }
  1322. char buffer[32]; // CodePointToUtf8 requires a buffer this big.
  1323. stream << CodePointToUtf8(unicode_code_point, buffer);
  1324. }
  1325. return StrStreamToString(&stream);
  1326. }
  1327. // Converts a wide C string to a String using the UTF-8 encoding.
  1328. // NULL will be converted to "(null)".
  1329. String String::ShowWideCString(const wchar_t * wide_c_str) {
  1330. if (wide_c_str == NULL) return String("(null)");
  1331. return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
  1332. }
  1333. // Similar to ShowWideCString(), except that this function encloses
  1334. // the converted string in double quotes.
  1335. String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
  1336. if (wide_c_str == NULL) return String("(null)");
  1337. return String::Format("L\"%s\"",
  1338. String::ShowWideCString(wide_c_str).c_str());
  1339. }
  1340. // Compares two wide C strings. Returns true iff they have the same
  1341. // content.
  1342. //
  1343. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  1344. // C string is considered different to any non-NULL C string,
  1345. // including the empty string.
  1346. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  1347. if (lhs == NULL) return rhs == NULL;
  1348. if (rhs == NULL) return false;
  1349. return wcscmp(lhs, rhs) == 0;
  1350. }
  1351. // Helper function for *_STREQ on wide strings.
  1352. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  1353. const char* actual_expression,
  1354. const wchar_t* expected,
  1355. const wchar_t* actual) {
  1356. if (String::WideCStringEquals(expected, actual)) {
  1357. return AssertionSuccess();
  1358. }
  1359. return EqFailure(expected_expression,
  1360. actual_expression,
  1361. String::ShowWideCStringQuoted(expected),
  1362. String::ShowWideCStringQuoted(actual),
  1363. false);
  1364. }
  1365. // Helper function for *_STRNE on wide strings.
  1366. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1367. const char* s2_expression,
  1368. const wchar_t* s1,
  1369. const wchar_t* s2) {
  1370. if (!String::WideCStringEquals(s1, s2)) {
  1371. return AssertionSuccess();
  1372. }
  1373. Message msg;
  1374. msg << "Expected: (" << s1_expression << ") != ("
  1375. << s2_expression << "), actual: "
  1376. << String::ShowWideCStringQuoted(s1)
  1377. << " vs " << String::ShowWideCStringQuoted(s2);
  1378. return AssertionFailure(msg);
  1379. }
  1380. // Compares two C strings, ignoring case. Returns true iff they have
  1381. // the same content.
  1382. //
  1383. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  1384. // NULL C string is considered different to any non-NULL C string,
  1385. // including the empty string.
  1386. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  1387. if (lhs == NULL)
  1388. return rhs == NULL;
  1389. if (rhs == NULL)
  1390. return false;
  1391. return posix::StrCaseCmp(lhs, rhs) == 0;
  1392. }
  1393. // Compares two wide C strings, ignoring case. Returns true iff they
  1394. // have the same content.
  1395. //
  1396. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  1397. // A NULL C string is considered different to any non-NULL wide C string,
  1398. // including the empty string.
  1399. // NB: The implementations on different platforms slightly differ.
  1400. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  1401. // environment variable. On GNU platform this method uses wcscasecmp
  1402. // which compares according to LC_CTYPE category of the current locale.
  1403. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  1404. // current locale.
  1405. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  1406. const wchar_t* rhs) {
  1407. if ( lhs == NULL ) return rhs == NULL;
  1408. if ( rhs == NULL ) return false;
  1409. #if GTEST_OS_WINDOWS
  1410. return _wcsicmp(lhs, rhs) == 0;
  1411. #elif GTEST_OS_LINUX
  1412. return wcscasecmp(lhs, rhs) == 0;
  1413. #else
  1414. // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
  1415. // may not define it either.
  1416. wint_t left, right;
  1417. do {
  1418. left = towlower(*lhs++);
  1419. right = towlower(*rhs++);
  1420. } while (left && left == right);
  1421. return left == right;
  1422. #endif // OS selector
  1423. }
  1424. // Compares this with another String.
  1425. // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
  1426. // if this is greater than rhs.
  1427. int String::Compare(const String & rhs) const {
  1428. const char* const lhs_c_str = c_str();
  1429. const char* const rhs_c_str = rhs.c_str();
  1430. if (lhs_c_str == NULL) {
  1431. return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
  1432. } else if (rhs_c_str == NULL) {
  1433. return 1;
  1434. }
  1435. const size_t shorter_str_len =
  1436. length() <= rhs.length() ? length() : rhs.length();
  1437. for (size_t i = 0; i != shorter_str_len; i++) {
  1438. if (lhs_c_str[i] < rhs_c_str[i]) {
  1439. return -1;
  1440. } else if (lhs_c_str[i] > rhs_c_str[i]) {
  1441. return 1;
  1442. }
  1443. }
  1444. return (length() < rhs.length()) ? -1 :
  1445. (length() > rhs.length()) ? 1 : 0;
  1446. }
  1447. // Returns true iff this String ends with the given suffix. *Any*
  1448. // String is considered to end with a NULL or empty suffix.
  1449. bool String::EndsWith(const char* suffix) const {
  1450. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1451. if (c_str() == NULL) return false;
  1452. const size_t this_len = strlen(c_str());
  1453. const size_t suffix_len = strlen(suffix);
  1454. return (this_len >= suffix_len) &&
  1455. CStringEquals(c_str() + this_len - suffix_len, suffix);
  1456. }
  1457. // Returns true iff this String ends with the given suffix, ignoring case.
  1458. // Any String is considered to end with a NULL or empty suffix.
  1459. bool String::EndsWithCaseInsensitive(const char* suffix) const {
  1460. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1461. if (c_str() == NULL) return false;
  1462. const size_t this_len = strlen(c_str());
  1463. const size_t suffix_len = strlen(suffix);
  1464. return (this_len >= suffix_len) &&
  1465. CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
  1466. }
  1467. // Formats a list of arguments to a String, using the same format
  1468. // spec string as for printf.
  1469. //
  1470. // We do not use the StringPrintf class as it is not universally
  1471. // available.
  1472. //
  1473. // The result is limited to 4096 characters (including the tailing 0).
  1474. // If 4096 characters are not enough to format the input, or if
  1475. // there's an error, "<formatting error or buffer exceeded>" is
  1476. // returned.
  1477. String String::Format(const char * format, ...) {
  1478. va_list args;
  1479. va_start(args, format);
  1480. char buffer[4096];
  1481. const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
  1482. // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
  1483. // 4996 (deprecated function) there.
  1484. #ifdef _MSC_VER // We are using MSVC.
  1485. #pragma warning(push) // Saves the current warning state.
  1486. #pragma warning(disable:4996) // Temporarily disables warning 4996.
  1487. const int size = vsnprintf(buffer, kBufferSize, format, args);
  1488. #pragma warning(pop) // Restores the warning state.
  1489. #else // We are not using MSVC.
  1490. const int size = vsnprintf(buffer, kBufferSize, format, args);
  1491. #endif // _MSC_VER
  1492. va_end(args);
  1493. // vsnprintf()'s behavior is not portable. When the buffer is not
  1494. // big enough, it returns a negative value in MSVC, and returns the
  1495. // needed buffer size on Linux. When there is an output error, it
  1496. // always returns a negative value. For simplicity, we lump the two
  1497. // error cases together.
  1498. if (size < 0 || size >= kBufferSize) {
  1499. return String("<formatting error or buffer exceeded>");
  1500. } else {
  1501. return String(buffer, size);
  1502. }
  1503. }
  1504. // Converts the buffer in a StrStream to a String, converting NUL
  1505. // bytes to "\\0" along the way.
  1506. String StrStreamToString(StrStream* ss) {
  1507. const ::std::string& str = ss->str();
  1508. const char* const start = str.c_str();
  1509. const char* const end = start + str.length();
  1510. // We need to use a helper StrStream to do this transformation
  1511. // because String doesn't support push_back().
  1512. StrStream helper;
  1513. for (const char* ch = start; ch != end; ++ch) {
  1514. if (*ch == '\0') {
  1515. helper << "\\0"; // Replaces NUL with "\\0";
  1516. } else {
  1517. helper.put(*ch);
  1518. }
  1519. }
  1520. return String(helper.str().c_str());
  1521. }
  1522. // Appends the user-supplied message to the Google-Test-generated message.
  1523. String AppendUserMessage(const String& gtest_msg,
  1524. const Message& user_msg) {
  1525. // Appends the user message if it's non-empty.
  1526. const String user_msg_string = user_msg.GetString();
  1527. if (user_msg_string.empty()) {
  1528. return gtest_msg;
  1529. }
  1530. Message msg;
  1531. msg << gtest_msg << "\n" << user_msg_string;
  1532. return msg.GetString();
  1533. }
  1534. } // namespace internal
  1535. // class TestResult
  1536. // Creates an empty TestResult.
  1537. TestResult::TestResult()
  1538. : death_test_count_(0),
  1539. elapsed_time_(0) {
  1540. }
  1541. // D'