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