gmock-internal-utils.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 <utility>
  44. #include <vector>
  45. #include "gmock/gmock.h"
  46. #include "gmock/internal/gmock-port.h"
  47. #include "gtest/gtest.h"
  48. namespace testing {
  49. namespace internal {
  50. // Joins a vector of strings as if they are fields of a tuple; returns
  51. // the joined string.
  52. GTEST_API_ std::string JoinAsKeyValueTuple(
  53. const std::vector<const char*>& names, const Strings& values) {
  54. GTEST_CHECK_(names.size() == values.size());
  55. if (values.empty()) {
  56. return "";
  57. }
  58. const auto build_one = [&](const size_t i) {
  59. return std::string(names[i]) + ": " + values[i];
  60. };
  61. std::string result = "(" + build_one(0);
  62. for (size_t i = 1; i < values.size(); i++) {
  63. result += ", ";
  64. result += build_one(i);
  65. }
  66. result += ")";
  67. return result;
  68. }
  69. // Converts an identifier name to a space-separated list of lower-case
  70. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  71. // treated as one word. For example, both "FooBar123" and
  72. // "foo_bar_123" are converted to "foo bar 123".
  73. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  74. std::string result;
  75. char prev_char = '\0';
  76. for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
  77. // We don't care about the current locale as the input is
  78. // guaranteed to be a valid C++ identifier name.
  79. const bool starts_new_word = IsUpper(*p) ||
  80. (!IsAlpha(prev_char) && IsLower(*p)) ||
  81. (!IsDigit(prev_char) && IsDigit(*p));
  82. if (IsAlNum(*p)) {
  83. if (starts_new_word && !result.empty()) result += ' ';
  84. result += ToLower(*p);
  85. }
  86. }
  87. return result;
  88. }
  89. // This class reports Google Mock failures as Google Test failures. A
  90. // user can define another class in a similar fashion if they intend to
  91. // use Google Mock with a testing framework other than Google Test.
  92. class GoogleTestFailureReporter : public FailureReporterInterface {
  93. public:
  94. void ReportFailure(FailureType type, const char* file, int line,
  95. const std::string& message) override {
  96. AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
  97. : TestPartResult::kNonFatalFailure,
  98. file, line, message.c_str()) = Message();
  99. if (type == kFatal) {
  100. posix::Abort();
  101. }
  102. }
  103. };
  104. // Returns the global failure reporter. Will create a
  105. // GoogleTestFailureReporter and return it the first time called.
  106. GTEST_API_ FailureReporterInterface* GetFailureReporter() {
  107. // Points to the global failure reporter used by Google Mock. gcc
  108. // guarantees that the following use of failure_reporter is
  109. // thread-safe. We may need to add additional synchronization to
  110. // protect failure_reporter if we port Google Mock to other
  111. // compilers.
  112. static FailureReporterInterface* const failure_reporter =
  113. new GoogleTestFailureReporter();
  114. return failure_reporter;
  115. }
  116. // Protects global resources (stdout in particular) used by Log().
  117. static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
  118. // Returns true if and only if a log with the given severity is visible
  119. // according to the --gmock_verbose flag.
  120. GTEST_API_ bool LogIsVisible(LogSeverity severity) {
  121. if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
  122. // Always show the log if --gmock_verbose=info.
  123. return true;
  124. } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
  125. // Always hide it if --gmock_verbose=error.
  126. return false;
  127. } else {
  128. // If --gmock_verbose is neither "info" nor "error", we treat it
  129. // as "warning" (its default value).
  130. return severity == kWarning;
  131. }
  132. }
  133. // Prints the given message to stdout if and only if 'severity' >= the level
  134. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  135. // 0, also prints the stack trace excluding the top
  136. // stack_frames_to_skip frames. In opt mode, any positive
  137. // stack_frames_to_skip is treated as 0, since we don't know which
  138. // function calls will be inlined by the compiler and need to be
  139. // conservative.
  140. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  141. int stack_frames_to_skip) {
  142. if (!LogIsVisible(severity)) return;
  143. // Ensures that logs from different threads don't interleave.
  144. MutexLock l(&g_log_mutex);
  145. if (severity == kWarning) {
  146. // Prints a GMOCK WARNING marker to make the warnings easily searchable.
  147. std::cout << "\nGMOCK WARNING:";
  148. }
  149. // Pre-pends a new-line to message if it doesn't start with one.
  150. if (message.empty() || message[0] != '\n') {
  151. std::cout << "\n";
  152. }
  153. std::cout << message;
  154. if (stack_frames_to_skip >= 0) {
  155. #ifdef NDEBUG
  156. // In opt mode, we have to be conservative and skip no stack frame.
  157. const int actual_to_skip = 0;
  158. #else
  159. // In dbg mode, we can do what the caller tell us to do (plus one
  160. // for skipping this function's stack frame).
  161. const int actual_to_skip = stack_frames_to_skip + 1;
  162. #endif // NDEBUG
  163. // Appends a new-line to message if it doesn't end with one.
  164. if (!message.empty() && *message.rbegin() != '\n') {
  165. std::cout << "\n";
  166. }
  167. std::cout << "Stack trace:\n"
  168. << ::testing::internal::GetCurrentOsStackTraceExceptTop(
  169. actual_to_skip);
  170. }
  171. std::cout << ::std::flush;
  172. }
  173. GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
  174. GTEST_API_ void IllegalDoDefault(const char* file, int line) {
  175. internal::Assert(
  176. false, file, line,
  177. "You are using DoDefault() inside a composite action like "
  178. "DoAll() or WithArgs(). This is not supported for technical "
  179. "reasons. Please instead spell out the default action, or "
  180. "assign the default action to an Action variable and use "
  181. "the variable in various places.");
  182. }
  183. constexpr char UndoWebSafeEncoding(char c) {
  184. return c == '-' ? '+' : c == '_' ? '/' : c;
  185. }
  186. constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
  187. return *base64 == 0 ? static_cast<char>(65)
  188. : *base64 == c
  189. ? carry
  190. : UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
  191. }
  192. template <size_t... I>
  193. constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>,
  194. const char* const base64) {
  195. return {
  196. {UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
  197. }
  198. constexpr std::array<char, 256> UnBase64(const char* const base64) {
  199. return UnBase64Impl(std::make_index_sequence<256>{}, base64);
  200. }
  201. static constexpr char kBase64[] =
  202. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  203. static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
  204. bool Base64Unescape(const std::string& encoded, std::string* decoded) {
  205. decoded->clear();
  206. size_t encoded_len = encoded.size();
  207. decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
  208. int bit_pos = 0;
  209. char dst = 0;
  210. for (int src : encoded) {
  211. if (std::isspace(src) || src == '=') {
  212. continue;
  213. }
  214. char src_bin = kUnBase64[static_cast<size_t>(src)];
  215. if (src_bin >= 64) {
  216. decoded->clear();
  217. return false;
  218. }
  219. if (bit_pos == 0) {
  220. dst |= static_cast<char>(src_bin << 2);
  221. bit_pos = 6;
  222. } else {
  223. dst |= static_cast<char>(src_bin >> (bit_pos - 2));
  224. decoded->push_back(dst);
  225. dst = static_cast<char>(src_bin << (10 - bit_pos));
  226. bit_pos = (bit_pos + 6) % 8;
  227. }
  228. }
  229. return true;
  230. }
  231. } // namespace internal
  232. } // namespace testing