gmock-internal-utils.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 <array>
  37. #include <cctype>
  38. #include <cstdint>
  39. #include <cstring>
  40. #include <iostream>
  41. #include <ostream> // NOLINT
  42. #include <string>
  43. #include <vector>
  44. #include "gmock/gmock.h"
  45. #include "gmock/internal/gmock-port.h"
  46. #include "gtest/gtest.h"
  47. namespace testing {
  48. namespace internal {
  49. // Joins a vector of strings as if they are fields of a tuple; returns
  50. // the joined string.
  51. GTEST_API_ std::string JoinAsKeyValueTuple(
  52. const std::vector<const char*>& names, const Strings& values) {
  53. GTEST_CHECK_(names.size() == values.size());
  54. if (values.empty()) {
  55. return "";
  56. }
  57. const auto build_one = [&](const size_t i) {
  58. return std::string(names[i]) + ": " + values[i];
  59. };
  60. std::string result = "(" + build_one(0);
  61. for (size_t i = 1; i < values.size(); i++) {
  62. result += ", ";
  63. result += build_one(i);
  64. }
  65. result += ")";
  66. return result;
  67. }
  68. // Converts an identifier name to a space-separated list of lower-case
  69. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  70. // treated as one word. For example, both "FooBar123" and
  71. // "foo_bar_123" are converted to "foo bar 123".
  72. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  73. std::string result;
  74. char prev_char = '\0';
  75. for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
  76. // We don't care about the current locale as the input is
  77. // guaranteed to be a valid C++ identifier name.
  78. const bool starts_new_word = IsUpper(*p) ||
  79. (!IsAlpha(prev_char) && IsLower(*p)) ||
  80. (!IsDigit(prev_char) && IsDigit(*p));
  81. if (IsAlNum(*p)) {
  82. if (starts_new_word && !result.empty()) result += ' ';
  83. result += ToLower(*p);
  84. }
  85. }
  86. return result;
  87. }
  88. // This class reports Google Mock failures as Google Test failures. A
  89. // user can define another class in a similar fashion if they intend to
  90. // use Google Mock with a testing framework other than Google Test.
  91. class GoogleTestFailureReporter : public FailureReporterInterface {
  92. public:
  93. void ReportFailure(FailureType type, const char* file, int line,
  94. const std::string& message) override {
  95. AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
  96. : TestPartResult::kNonFatalFailure,
  97. file, line, message.c_str()) = Message();
  98. if (type == kFatal) {
  99. posix::Abort();
  100. }
  101. }
  102. };
  103. // Returns the global failure reporter. Will create a
  104. // GoogleTestFailureReporter and return it the first time called.
  105. GTEST_API_ FailureReporterInterface* GetFailureReporter() {
  106. // Points to the global failure reporter used by Google Mock. gcc
  107. // guarantees that the following use of failure_reporter is
  108. // thread-safe. We may need to add additional synchronization to
  109. // protect failure_reporter if we port Google Mock to other
  110. // compilers.
  111. static FailureReporterInterface* const failure_reporter =
  112. new GoogleTestFailureReporter();
  113. return failure_reporter;
  114. }
  115. // Protects global resources (stdout in particular) used by Log().
  116. static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
  117. // Returns true if and only if a log with the given severity is visible
  118. // according to the --gmock_verbose flag.
  119. GTEST_API_ bool LogIsVisible(LogSeverity severity) {
  120. if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
  121. // Always show the log if --gmock_verbose=info.
  122. return true;
  123. } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
  124. // Always hide it if --gmock_verbose=error.
  125. return false;
  126. } else {
  127. // If --gmock_verbose is neither "info" nor "error", we treat it
  128. // as "warning" (its default value).
  129. return severity == kWarning;
  130. }
  131. }
  132. // Prints the given message to stdout if and only if 'severity' >= the level
  133. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  134. // 0, also prints the stack trace excluding the top
  135. // stack_frames_to_skip frames. In opt mode, any positive
  136. // stack_frames_to_skip is treated as 0, since we don't know which
  137. // function calls will be inlined by the compiler and need to be
  138. // conservative.
  139. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  140. int stack_frames_to_skip) {
  141. if (!LogIsVisible(severity)) return;
  142. // Ensures that logs from different threads don't interleave.
  143. MutexLock l(&g_log_mutex);
  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. 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. constexpr char UndoWebSafeEncoding(char c) {
  183. return c == '-' ? '+' : c == '_' ? '/' : c;
  184. }
  185. constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
  186. return *base64 == 0 ? static_cast<char>(65)
  187. : *base64 == c
  188. ? carry
  189. : UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
  190. }
  191. template <size_t... I>
  192. constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
  193. const char* const base64) {
  194. return {
  195. {UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
  196. }
  197. constexpr std::array<char, 256> UnBase64(const char* const base64) {
  198. return UnBase64Impl(MakeIndexSequence<256>{}, base64);
  199. }
  200. static constexpr char kBase64[] =
  201. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  202. static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
  203. bool Base64Unescape(const std::string& encoded, std::string* decoded) {
  204. decoded->clear();
  205. size_t encoded_len = encoded.size();
  206. decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
  207. int bit_pos = 0;
  208. char dst = 0;
  209. for (int src : encoded) {
  210. if (std::isspace(src) || src == '=') {
  211. continue;
  212. }
  213. char src_bin = kUnBase64[static_cast<size_t>(src)];
  214. if (src_bin >= 64) {
  215. decoded->clear();
  216. return false;
  217. }
  218. if (bit_pos == 0) {
  219. dst |= static_cast<char>(src_bin << 2);
  220. bit_pos = 6;
  221. } else {
  222. dst |= static_cast<char>(src_bin >> (bit_pos - 2));
  223. decoded->push_back(dst);
  224. dst = static_cast<char>(src_bin << (10 - bit_pos));
  225. bit_pos = (bit_pos + 6) % 8;
  226. }
  227. }
  228. return true;
  229. }
  230. } // namespace internal
  231. } // namespace testing