gmock-internal-utils.cc 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2007, 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. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file defines some utilities useful for implementing Google
  32. // Mock. They are subject to change without notice, so please DO NOT
  33. // USE THEM IN USER CODE.
  34. #include "gmock/internal/gmock-internal-utils.h"
  35. #include <ctype.h>
  36. #include <ostream> // NOLINT
  37. #include <string>
  38. #include "gmock/gmock.h"
  39. #include "gmock/internal/gmock-port.h"
  40. #include "gtest/gtest.h"
  41. namespace testing {
  42. namespace internal {
  43. // Joins a vector of strings as if they are fields of a tuple; returns
  44. // the joined string.
  45. GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
  46. switch (fields.size()) {
  47. case 0:
  48. return "";
  49. case 1:
  50. return fields[0];
  51. default:
  52. std::string result = "(" + fields[0];
  53. for (size_t i = 1; i < fields.size(); i++) {
  54. result += ", ";
  55. result += fields[i];
  56. }
  57. result += ")";
  58. return result;
  59. }
  60. }
  61. // Converts an identifier name to a space-separated list of lower-case
  62. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  63. // treated as one word. For example, both "FooBar123" and
  64. // "foo_bar_123" are converted to "foo bar 123".
  65. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  66. std::string result;
  67. char prev_char = '\0';
  68. for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
  69. // We don't care about the current locale as the input is
  70. // guaranteed to be a valid C++ identifier name.
  71. const bool starts_new_word = IsUpper(*p) ||
  72. (!IsAlpha(prev_char) && IsLower(*p)) ||
  73. (!IsDigit(prev_char) && IsDigit(*p));
  74. if (IsAlNum(*p)) {
  75. if (starts_new_word && result != "")
  76. result += ' ';
  77. result += ToLower(*p);
  78. }
  79. }
  80. return result;
  81. }
  82. // This class reports Google Mock failures as Google Test failures. A
  83. // user can define another class in a similar fashion if they intend to
  84. // use Google Mock with a testing framework other than Google Test.
  85. class GoogleTestFailureReporter : public FailureReporterInterface {
  86. public:
  87. virtual void ReportFailure(FailureType type, const char* file, int line,
  88. const std::string& message) {
  89. AssertHelper(type == kFatal ?
  90. TestPartResult::kFatalFailure :
  91. TestPartResult::kNonFatalFailure,
  92. file,
  93. line,
  94. message.c_str()) = Message();
  95. if (type == kFatal) {
  96. posix::Abort();
  97. }
  98. }
  99. };
  100. // Returns the global failure reporter. Will create a
  101. // GoogleTestFailureReporter and return it the first time called.
  102. GTEST_API_ FailureReporterInterface* GetFailureReporter() {
  103. // Points to the global failure reporter used by Google Mock. gcc
  104. // guarantees that the following use of failure_reporter is
  105. // thread-safe. We may need to add additional synchronization to
  106. // protect failure_reporter if we port Google Mock to other
  107. // compilers.
  108. static FailureReporterInterface* const failure_reporter =
  109. new GoogleTestFailureReporter();
  110. return failure_reporter;
  111. }
  112. // Protects global resources (stdout in particular) used by Log().
  113. static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
  114. // Returns true iff a log with the given severity is visible according
  115. // to the --gmock_verbose flag.
  116. GTEST_API_ bool LogIsVisible(LogSeverity severity) {
  117. if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
  118. // Always show the log if --gmock_verbose=info.
  119. return true;
  120. } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
  121. // Always hide it if --gmock_verbose=error.
  122. return false;
  123. } else {
  124. // If --gmock_verbose is neither "info" nor "error", we treat it
  125. // as "warning" (its default value).
  126. return severity == kWarning;
  127. }
  128. }
  129. // Prints the given message to stdout iff 'severity' >= the level
  130. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  131. // 0, also prints the stack trace excluding the top
  132. // stack_frames_to_skip frames. In opt mode, any positive
  133. // stack_frames_to_skip is treated as 0, since we don't know which
  134. // function calls will be inlined by the compiler and need to be
  135. // conservative.
  136. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  137. int stack_frames_to_skip) {
  138. if (!LogIsVisible(severity))
  139. return;
  140. // Ensures that logs from different threads don't interleave.
  141. MutexLock l(&g_log_mutex);
  142. // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
  143. // macro.
  144. if (severity == kWarning) {
  145. // Prints a GMOCK WARNING marker to make the warnings easily searchable.
  146. std::cout << "\nGMOCK WARNING:";
  147. }
  148. // Pre-pends a new-line to message if it doesn't start with one.
  149. if (message.empty() || message[0] != '\n') {
  150. std::cout << "\n";
  151. }
  152. std::cout << message;
  153. if (stack_frames_to_skip >= 0) {
  154. #ifdef NDEBUG
  155. // In opt mode, we have to be conservative and skip no stack frame.
  156. const int actual_to_skip = 0;
  157. #else
  158. // In dbg mode, we can do what the caller tell us to do (plus one
  159. // for skipping this function's stack frame).
  160. const int actual_to_skip = stack_frames_to_skip + 1;
  161. #endif // NDEBUG
  162. // Appends a new-line to message if it doesn't end with one.
  163. if (!message.empty() && *message.rbegin() != '\n') {
  164. std::cout << "\n";
  165. }
  166. std::cout << "Stack trace:\n"
  167. << ::testing::internal::GetCurrentOsStackTraceExceptTop(
  168. ::testing::UnitTest::GetInstance(), actual_to_skip);
  169. }
  170. std::cout << ::std::flush;
  171. }
  172. GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
  173. GTEST_API_ void IllegalDoDefault(const char* file, int line) {
  174. internal::Assert(
  175. false, file, line,
  176. "You are using DoDefault() inside a composite action like "
  177. "DoAll() or WithArgs(). This is not supported for technical "
  178. "reasons. Please instead spell out the default action, or "
  179. "assign the default action to an Action variable and use "
  180. "the variable in various places.");
  181. }
  182. } // namespace internal
  183. } // namespace testing