1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Google Mock - a framework for writing C++ mock classes.
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.
37 // GOOGLETEST_CM0002 DO NOT DELETE
39 #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40 #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
43 #include <ostream> // NOLINT
45 #include <type_traits>
46 #include "gmock/internal/gmock-port.h"
47 #include "gtest/gtest.h"
56 // Silence MSVC C4100 (unreferenced formal parameter) and
57 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
59 # pragma warning(push)
60 # pragma warning(disable:4100)
61 # pragma warning(disable:4805)
64 // Joins a vector of strings as if they are fields of a tuple; returns
66 GTEST_API_
std::string
JoinAsTuple(const Strings
& fields
);
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
);
74 // GetRawPointer(p) returns the raw pointer underlying p when p is a
75 // smart pointer, or returns p itself when p is already a raw pointer.
76 // The following default implementation is for the smart pointer case.
77 template <typename Pointer
>
78 inline const typename
Pointer::element_type
* GetRawPointer(const Pointer
& p
) {
81 // This overloaded version is for the raw pointer case.
82 template <typename Element
>
83 inline Element
* GetRawPointer(Element
* p
) { return p
; }
85 // MSVC treats wchar_t as a native type usually, but treats it as the
86 // same as unsigned short when the compiler option /Zc:wchar_t- is
87 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
89 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
90 // wchar_t is a typedef.
92 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
95 // In what follows, we use the term "kind" to indicate whether a type
96 // is bool, an integer type (excluding bool), a floating-point type,
97 // or none of them. This categorization is useful for determining
98 // when a matcher argument type can be safely converted to another
99 // type in the implementation of SafeMatcherCast.
101 kBool
, kInteger
, kFloatingPoint
, kOther
104 // KindOf<T>::value is the kind of type T.
105 template <typename T
> struct KindOf
{
106 enum { value
= kOther
}; // The default kind.
109 // This macro declares that the kind of 'type' is 'kind'.
110 #define GMOCK_DECLARE_KIND_(type, kind) \
111 template <> struct KindOf<type> { enum { value = kind }; }
113 GMOCK_DECLARE_KIND_(bool, kBool
);
115 // All standard integer types.
116 GMOCK_DECLARE_KIND_(char, kInteger
);
117 GMOCK_DECLARE_KIND_(signed char, kInteger
);
118 GMOCK_DECLARE_KIND_(unsigned char, kInteger
);
119 GMOCK_DECLARE_KIND_(short, kInteger
); // NOLINT
120 GMOCK_DECLARE_KIND_(unsigned short, kInteger
); // NOLINT
121 GMOCK_DECLARE_KIND_(int, kInteger
);
122 GMOCK_DECLARE_KIND_(unsigned int, kInteger
);
123 GMOCK_DECLARE_KIND_(long, kInteger
); // NOLINT
124 GMOCK_DECLARE_KIND_(unsigned long, kInteger
); // NOLINT
125 GMOCK_DECLARE_KIND_(long long, kInteger
); // NOLINT
126 GMOCK_DECLARE_KIND_(unsigned long long, kInteger
); // NOLINT
128 #if GMOCK_WCHAR_T_IS_NATIVE_
129 GMOCK_DECLARE_KIND_(wchar_t, kInteger
);
132 // All standard floating-point types.
133 GMOCK_DECLARE_KIND_(float, kFloatingPoint
);
134 GMOCK_DECLARE_KIND_(double, kFloatingPoint
);
135 GMOCK_DECLARE_KIND_(long double, kFloatingPoint
);
137 #undef GMOCK_DECLARE_KIND_
139 // Evaluates to the kind of 'type'.
140 #define GMOCK_KIND_OF_(type) \
141 static_cast< ::testing::internal::TypeKind>( \
142 ::testing::internal::KindOf<type>::value)
144 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
145 // is true if and only if arithmetic type From can be losslessly converted to
146 // arithmetic type To.
148 // It's the user's responsibility to ensure that both From and To are
149 // raw (i.e. has no CV modifier, is not a pointer, and is not a
150 // reference) built-in arithmetic types, kFromKind is the kind of
151 // From, and kToKind is the kind of To; the value is
152 // implementation-defined when the above pre-condition is violated.
153 template <TypeKind kFromKind
, typename From
, TypeKind kToKind
, typename To
>
154 using LosslessArithmeticConvertibleImpl
= std::integral_constant
<
157 // Converting from bool is always lossless
158 (kFromKind
== kBool
) ? true
159 // Converting between any other type kinds will be lossy if the type
160 // kinds are not the same.
161 : (kFromKind
!= kToKind
) ? false
162 : (kFromKind
== kInteger
&&
163 // Converting between integers of different widths is allowed so long
164 // as the conversion does not go from signed to unsigned.
165 (((sizeof(From
) < sizeof(To
)) &&
166 !(std::is_signed
<From
>::value
&& !std::is_signed
<To
>::value
)) ||
167 // Converting between integers of the same width only requires the
168 // two types to have the same signedness.
169 ((sizeof(From
) == sizeof(To
)) &&
170 (std::is_signed
<From
>::value
== std::is_signed
<To
>::value
)))
172 // Floating point conversions are lossless if and only if `To` is at least
173 // as wide as `From`.
174 : (kFromKind
== kFloatingPoint
&& (sizeof(From
) <= sizeof(To
))) ? true
179 // LosslessArithmeticConvertible<From, To>::value is true if and only if
180 // arithmetic type From can be losslessly converted to arithmetic type To.
182 // It's the user's responsibility to ensure that both From and To are
183 // raw (i.e. has no CV modifier, is not a pointer, and is not a
184 // reference) built-in arithmetic types; the value is
185 // implementation-defined when the above pre-condition is violated.
186 template <typename From
, typename To
>
187 using LosslessArithmeticConvertible
=
188 LosslessArithmeticConvertibleImpl
<GMOCK_KIND_OF_(From
), From
,
189 GMOCK_KIND_OF_(To
), To
>;
191 // This interface knows how to report a Google Mock failure (either
192 // non-fatal or fatal).
193 class FailureReporterInterface
{
195 // The type of a failure (either non-fatal or fatal).
200 virtual ~FailureReporterInterface() {}
202 // Reports a failure that occurred at the given source file location.
203 virtual void ReportFailure(FailureType type
, const char* file
, int line
,
204 const std::string
& message
) = 0;
207 // Returns the failure reporter used by Google Mock.
208 GTEST_API_ FailureReporterInterface
* GetFailureReporter();
210 // Asserts that condition is true; aborts the process with the given
211 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
212 // as Google Mock might be used to mock the log sink itself. We
213 // inline this function to prevent it from showing up in the stack
215 inline void Assert(bool condition
, const char* file
, int line
,
216 const std::string
& msg
) {
218 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal
,
222 inline void Assert(bool condition
, const char* file
, int line
) {
223 Assert(condition
, file
, line
, "Assertion failed.");
226 // Verifies that condition is true; generates a non-fatal failure if
227 // condition is false.
228 inline void Expect(bool condition
, const char* file
, int line
,
229 const std::string
& msg
) {
231 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal
,
235 inline void Expect(bool condition
, const char* file
, int line
) {
236 Expect(condition
, file
, line
, "Expectation failed.");
239 // Severity level of a log.
245 // Valid values for the --gmock_verbose flag.
247 // All logs (informational and warnings) are printed.
248 const char kInfoVerbosity
[] = "info";
249 // Only warnings are printed.
250 const char kWarningVerbosity
[] = "warning";
251 // No logs are printed.
252 const char kErrorVerbosity
[] = "error";
254 // Returns true if and only if a log with the given severity is visible
255 // according to the --gmock_verbose flag.
256 GTEST_API_
bool LogIsVisible(LogSeverity severity
);
258 // Prints the given message to stdout if and only if 'severity' >= the level
259 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
260 // 0, also prints the stack trace excluding the top
261 // stack_frames_to_skip frames. In opt mode, any positive
262 // stack_frames_to_skip is treated as 0, since we don't know which
263 // function calls will be inlined by the compiler and need to be
265 GTEST_API_
void Log(LogSeverity severity
, const std::string
& message
,
266 int stack_frames_to_skip
);
268 // A marker class that is used to resolve parameterless expectations to the
269 // correct overload. This must not be instantiable, to prevent client code from
270 // accidentally resolving to the overload; for example:
272 // ON_CALL(mock, Method({}, nullptr))...
274 class WithoutMatchers
{
277 friend GTEST_API_ WithoutMatchers
GetWithoutMatchers();
280 // Internal use only: access the singleton instance of WithoutMatchers.
281 GTEST_API_ WithoutMatchers
GetWithoutMatchers();
283 // Disable MSVC warnings for infinite recursion, since in this case the
284 // the recursion is unreachable.
286 # pragma warning(push)
287 # pragma warning(disable:4717)
290 // Invalid<T>() is usable as an expression of type T, but will terminate
291 // the program with an assertion failure if actually run. This is useful
292 // when a value of type T is needed for compilation, but the statement
293 // will not really be executed (or we don't care if the statement
295 template <typename T
>
297 Assert(false, "", -1, "Internal error: attempt to return invalid value");
298 // This statement is unreachable, and would never terminate even if it
299 // could be reached. It is provided only to placate compiler warnings
300 // about missing return statements.
305 # pragma warning(pop)
308 // Given a raw type (i.e. having no top-level reference or const
309 // modifier) RawContainer that's either an STL-style container or a
310 // native array, class StlContainerView<RawContainer> has the
311 // following members:
313 // - type is a type that provides an STL-style container view to
314 // (i.e. implements the STL container concept for) RawContainer;
315 // - const_reference is a type that provides a reference to a const
317 // - ConstReference(raw_container) returns a const reference to an STL-style
318 // container view to raw_container, which is a RawContainer.
319 // - Copy(raw_container) returns an STL-style container view of a
320 // copy of raw_container, which is a RawContainer.
322 // This generic version is used when RawContainer itself is already an
323 // STL-style container.
324 template <class RawContainer
>
325 class StlContainerView
{
327 typedef RawContainer type
;
328 typedef const type
& const_reference
;
330 static const_reference
ConstReference(const RawContainer
& container
) {
331 static_assert(!std::is_const
<RawContainer
>::value
,
332 "RawContainer type must not be const");
335 static type
Copy(const RawContainer
& container
) { return container
; }
338 // This specialization is used when RawContainer is a native array type.
339 template <typename Element
, size_t N
>
340 class StlContainerView
<Element
[N
]> {
342 typedef typename
std::remove_const
<Element
>::type RawElement
;
343 typedef internal::NativeArray
<RawElement
> type
;
344 // NativeArray<T> can represent a native array either by value or by
345 // reference (selected by a constructor argument), so 'const type'
346 // can be used to reference a const native array. We cannot
347 // 'typedef const type& const_reference' here, as that would mean
348 // ConstReference() has to return a reference to a local variable.
349 typedef const type const_reference
;
351 static const_reference
ConstReference(const Element (&array
)[N
]) {
352 static_assert(std::is_same
<Element
, RawElement
>::value
,
353 "Element type must not be const");
354 return type(array
, N
, RelationToSourceReference());
356 static type
Copy(const Element (&array
)[N
]) {
357 return type(array
, N
, RelationToSourceCopy());
361 // This specialization is used when RawContainer is a native array
362 // represented as a (pointer, size) tuple.
363 template <typename ElementPointer
, typename Size
>
364 class StlContainerView
< ::std::tuple
<ElementPointer
, Size
> > {
366 typedef typename
std::remove_const
<
367 typename
std::pointer_traits
<ElementPointer
>::element_type
>::type
369 typedef internal::NativeArray
<RawElement
> type
;
370 typedef const type const_reference
;
372 static const_reference
ConstReference(
373 const ::std::tuple
<ElementPointer
, Size
>& array
) {
374 return type(std::get
<0>(array
), std::get
<1>(array
),
375 RelationToSourceReference());
377 static type
Copy(const ::std::tuple
<ElementPointer
, Size
>& array
) {
378 return type(std::get
<0>(array
), std::get
<1>(array
), RelationToSourceCopy());
382 // The following specialization prevents the user from instantiating
383 // StlContainer with a reference type.
384 template <typename T
> class StlContainerView
<T
&>;
386 // A type transform to remove constness from the first part of a pair.
387 // Pairs like that are used as the value_type of associative containers,
388 // and this transform produces a similar but assignable pair.
389 template <typename T
>
390 struct RemoveConstFromKey
{
394 // Partially specialized to remove constness from std::pair<const K, V>.
395 template <typename K
, typename V
>
396 struct RemoveConstFromKey
<std::pair
<const K
, V
> > {
397 typedef std::pair
<K
, V
> type
;
400 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
402 GTEST_API_
void IllegalDoDefault(const char* file
, int line
);
404 template <typename F
, typename Tuple
, size_t... Idx
>
405 auto ApplyImpl(F
&& f
, Tuple
&& args
, IndexSequence
<Idx
...>) -> decltype(
406 std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...)) {
407 return std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...);
410 // Apply the function to a tuple of arguments.
411 template <typename F
, typename Tuple
>
412 auto Apply(F
&& f
, Tuple
&& args
) -> decltype(
413 ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
414 MakeIndexSequence
<std::tuple_size
<
415 typename
std::remove_reference
<Tuple
>::type
>::value
>())) {
416 return ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
417 MakeIndexSequence
<std::tuple_size
<
418 typename
std::remove_reference
<Tuple
>::type
>::value
>());
421 // Template struct Function<F>, where F must be a function type, contains
422 // the following typedefs:
424 // Result: the function's return type.
425 // Arg<N>: the type of the N-th argument, where N starts with 0.
426 // ArgumentTuple: the tuple type consisting of all parameters of F.
427 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
429 // MakeResultVoid: the function type obtained by substituting void
430 // for the return type of F.
431 // MakeResultIgnoredValue:
432 // the function type obtained by substituting Something
433 // for the return type of F.
434 template <typename T
>
437 template <typename R
, typename
... Args
>
438 struct Function
<R(Args
...)> {
440 static constexpr size_t ArgumentCount
= sizeof...(Args
);
442 using Arg
= ElemFromList
<I
, Args
...>;
443 using ArgumentTuple
= std::tuple
<Args
...>;
444 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
445 using MakeResultVoid
= void(Args
...);
446 using MakeResultIgnoredValue
= IgnoredValue(Args
...);
449 template <typename R
, typename
... Args
>
450 constexpr size_t Function
<R(Args
...)>::ArgumentCount
;
453 # pragma warning(pop)
456 } // namespace internal
457 } // namespace testing
459 #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_