gmock-internal-utils.cc 9.05 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

30
31
32
33
34
35
36

// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
// Mock.  They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.

37
#include "gmock/internal/gmock-internal-utils.h"
38

zhanyong.wan's avatar
zhanyong.wan committed
39
#include <ctype.h>
Abseil Team's avatar
Abseil Team committed
40
41
42
43
44

#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
45
46
#include <ostream>  // NOLINT
#include <string>
47
#include <vector>
Abseil Team's avatar
Abseil Team committed
48

49
50
51
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
52
53
54
55

namespace testing {
namespace internal {

56
57
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
58
59
60
61
62
GTEST_API_ std::string JoinAsKeyValueTuple(
    const std::vector<const char*>& names, const Strings& values) {
  GTEST_CHECK_(names.size() == values.size());
  if (values.empty()) {
    return "";
63
  }
64
65
66
67
68
69
70
71
72
73
  const auto build_one = [&](const size_t i) {
    return std::string(names[i]) + ": " + values[i];
  };
  std::string result = "(" + build_one(0);
  for (size_t i = 1; i < values.size(); i++) {
    result += ", ";
    result += build_one(i);
  }
  result += ")";
  return result;
74
75
}

zhanyong.wan's avatar
zhanyong.wan committed
76
77
78
79
// Converts an identifier name to a space-separated list of lower-case
// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word.  For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
Gennadiy Civil's avatar
 
Gennadiy Civil committed
80
81
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  std::string result;
zhanyong.wan's avatar
zhanyong.wan committed
82
83
84
85
  char prev_char = '\0';
  for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
    // We don't care about the current locale as the input is
    // guaranteed to be a valid C++ identifier name.
86
87
88
    const bool starts_new_word = IsUpper(*p) ||
        (!IsAlpha(prev_char) && IsLower(*p)) ||
        (!IsDigit(prev_char) && IsDigit(*p));
zhanyong.wan's avatar
zhanyong.wan committed
89

90
    if (IsAlNum(*p)) {
zhanyong.wan's avatar
zhanyong.wan committed
91
92
      if (starts_new_word && result != "")
        result += ' ';
93
      result += ToLower(*p);
zhanyong.wan's avatar
zhanyong.wan committed
94
95
96
97
98
    }
  }
  return result;
}

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
102
103
// use Google Mock with a testing framework other than Google Test.
class GoogleTestFailureReporter : public FailureReporterInterface {
 public:
Abseil Team's avatar
Abseil Team committed
104
105
  void ReportFailure(FailureType type, const char* file, int line,
                     const std::string& message) override {
zhanyong.wan's avatar
zhanyong.wan committed
106
    AssertHelper(type == kFatal ?
zhanyong.wan's avatar
zhanyong.wan committed
107
108
109
110
111
                 TestPartResult::kFatalFailure :
                 TestPartResult::kNonFatalFailure,
                 file,
                 line,
                 message.c_str()) = Message();
zhanyong.wan's avatar
zhanyong.wan committed
112
    if (type == kFatal) {
113
      posix::Abort();
114
115
116
117
118
119
    }
  }
};

// Returns the global failure reporter.  Will create a
// GoogleTestFailureReporter and return it the first time called.
120
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
121
122
123
124
125
126
127
128
129
130
131
  // Points to the global failure reporter used by Google Mock.  gcc
  // guarantees that the following use of failure_reporter is
  // thread-safe.  We may need to add additional synchronization to
  // protect failure_reporter if we port Google Mock to other
  // compilers.
  static FailureReporterInterface* const failure_reporter =
      new GoogleTestFailureReporter();
  return failure_reporter;
}

// Protects global resources (stdout in particular) used by Log().
132
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
133

134
135
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
136
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
Abseil Team's avatar
Abseil Team committed
137
  if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
138
139
    // Always show the log if --gmock_verbose=info.
    return true;
Abseil Team's avatar
Abseil Team committed
140
  } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
141
142
143
144
145
    // Always hide it if --gmock_verbose=error.
    return false;
  } else {
    // If --gmock_verbose is neither "info" nor "error", we treat it
    // as "warning" (its default value).
zhanyong.wan's avatar
zhanyong.wan committed
146
    return severity == kWarning;
147
148
149
  }
}

150
// Prints the given message to stdout if and only if 'severity' >= the level
151
152
153
154
155
156
// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames.  In opt mode, any positive
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
157
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
158
                    int stack_frames_to_skip) {
159
  if (!LogIsVisible(severity))
160
161
162
163
    return;

  // Ensures that logs from different threads don't interleave.
  MutexLock l(&g_log_mutex);
164

zhanyong.wan's avatar
zhanyong.wan committed
165
  if (severity == kWarning) {
166
    // Prints a GMOCK WARNING marker to make the warnings easily searchable.
167
    std::cout << "\nGMOCK WARNING:";
168
169
170
  }
  // Pre-pends a new-line to message if it doesn't start with one.
  if (message.empty() || message[0] != '\n') {
171
    std::cout << "\n";
172
  }
173
  std::cout << message;
174
175
176
177
178
179
180
181
182
183
184
185
  if (stack_frames_to_skip >= 0) {
#ifdef NDEBUG
    // In opt mode, we have to be conservative and skip no stack frame.
    const int actual_to_skip = 0;
#else
    // In dbg mode, we can do what the caller tell us to do (plus one
    // for skipping this function's stack frame).
    const int actual_to_skip = stack_frames_to_skip + 1;
#endif  // NDEBUG

    // Appends a new-line to message if it doesn't end with one.
    if (!message.empty() && *message.rbegin() != '\n') {
186
      std::cout << "\n";
187
    }
188
    std::cout << "Stack trace:\n"
189
190
191
         << ::testing::internal::GetCurrentOsStackTraceExceptTop(
             ::testing::UnitTest::GetInstance(), actual_to_skip);
  }
192
  std::cout << ::std::flush;
193
194
}

195
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
196

Gennadiy Civil's avatar
 
Gennadiy Civil committed
197
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
Gennadiy Civil's avatar
 
Gennadiy Civil committed
198
199
200
201
202
203
204
205
206
  internal::Assert(
      false, file, line,
      "You are using DoDefault() inside a composite action like "
      "DoAll() or WithArgs().  This is not supported for technical "
      "reasons.  Please instead spell out the default action, or "
      "assign the default action to an Action variable and use "
      "the variable in various places.");
}

Abseil Team's avatar
Abseil Team committed
207
208
209
210
211
212
213
214
215
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
  return *base64 == 0   ? static_cast<char>(65)
         : *base64 == c ? carry
                        : UnBase64Impl(c, base64 + 1, carry + 1);
}

template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
                                             const char* const base64) {
Abseil Team's avatar
Abseil Team committed
216
  return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
Abseil Team's avatar
Abseil Team committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
}

constexpr std::array<char, 256> UnBase64(const char* const base64) {
  return UnBase64Impl(MakeIndexSequence<256>{}, base64);
}

static constexpr char kBase64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);

bool Base64Unescape(const std::string& encoded, std::string* decoded) {
  decoded->clear();
  size_t encoded_len = encoded.size();
  decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
  int bit_pos = 0;
  char dst = 0;
  for (int src : encoded) {
    if (std::isspace(src) || src == '=') {
      continue;
    }
Abseil Team's avatar
Abseil Team committed
237
    char src_bin = kUnBase64[static_cast<size_t>(src)];
Abseil Team's avatar
Abseil Team committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    if (src_bin >= 64) {
      decoded->clear();
      return false;
    }
    if (bit_pos == 0) {
      dst |= src_bin << 2;
      bit_pos = 6;
    } else {
      dst |= static_cast<char>(src_bin >> (bit_pos - 2));
      decoded->push_back(dst);
      dst = static_cast<char>(src_bin << (10 - bit_pos));
      bit_pos = (bit_pos + 6) % 8;
    }
  }
  return true;
}

255
256
}  // namespace internal
}  // namespace testing