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