Sacado Package Browser (Single Doxygen Collection) Version of the Day
Loading...
Searching...
No Matches
gmock-internal-utils.h
Go to the documentation of this file.
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// GOOGLETEST_CM0002 DO NOT DELETE
38
39#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
41
42#include <stdio.h>
43#include <ostream> // NOLINT
44#include <string>
45#include <type_traits>
47#include "gtest/gtest.h"
48
49namespace testing {
50
51template <typename>
52class Matcher;
53
54namespace internal {
55
56// Silence MSVC C4100 (unreferenced formal parameter) and
57// C4805('==': unsafe mix of type 'const int' and type 'const bool')
58#ifdef _MSC_VER
59# pragma warning(push)
60# pragma warning(disable:4100)
61# pragma warning(disable:4805)
62#endif
63
64// Joins a vector of strings as if they are fields of a tuple; returns
65// the joined string.
66GTEST_API_ std::string JoinAsTuple(const Strings& fields);
67
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".
72GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
73
74// PointeeOf<Pointer>::type is the type of a value pointed to by a
75// Pointer, which can be either a smart pointer or a raw pointer. The
76// following default implementation is for the case where Pointer is a
77// smart pointer.
78template <typename Pointer>
79struct PointeeOf {
80 // Smart pointer classes define type element_type as the type of
81 // their pointees.
82 typedef typename Pointer::element_type type;
83};
84// This specialization is for the raw pointer case.
85template <typename T>
86struct PointeeOf<T*> { typedef T type; }; // NOLINT
87
88// GetRawPointer(p) returns the raw pointer underlying p when p is a
89// smart pointer, or returns p itself when p is already a raw pointer.
90// The following default implementation is for the smart pointer case.
91template <typename Pointer>
92inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
93 return p.get();
94}
95// This overloaded version is for the raw pointer case.
96template <typename Element>
97inline Element* GetRawPointer(Element* p) { return p; }
98
99// MSVC treats wchar_t as a native type usually, but treats it as the
100// same as unsigned short when the compiler option /Zc:wchar_t- is
101// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
102// is a native type.
103#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
104// wchar_t is a typedef.
105#else
106# define GMOCK_WCHAR_T_IS_NATIVE_ 1
107#endif
108
109// In what follows, we use the term "kind" to indicate whether a type
110// is bool, an integer type (excluding bool), a floating-point type,
111// or none of them. This categorization is useful for determining
112// when a matcher argument type can be safely converted to another
113// type in the implementation of SafeMatcherCast.
117
118// KindOf<T>::value is the kind of type T.
119template <typename T> struct KindOf {
120 enum { value = kOther }; // The default kind.
121};
122
123// This macro declares that the kind of 'type' is 'kind'.
124#define GMOCK_DECLARE_KIND_(type, kind) \
125 template <> struct KindOf<type> { enum { value = kind }; }
126
128
129// All standard integer types.
134GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
138GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
139GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
140GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
141
142#if GMOCK_WCHAR_T_IS_NATIVE_
144#endif
145
146// All standard floating-point types.
150
151#undef GMOCK_DECLARE_KIND_
152
153// Evaluates to the kind of 'type'.
154#define GMOCK_KIND_OF_(type) \
155 static_cast< ::testing::internal::TypeKind>( \
156 ::testing::internal::KindOf<type>::value)
157
158// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
159// is true if and only if arithmetic type From can be losslessly converted to
160// arithmetic type To.
161//
162// It's the user's responsibility to ensure that both From and To are
163// raw (i.e. has no CV modifier, is not a pointer, and is not a
164// reference) built-in arithmetic types, kFromKind is the kind of
165// From, and kToKind is the kind of To; the value is
166// implementation-defined when the above pre-condition is violated.
167template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
168using LosslessArithmeticConvertibleImpl = std::integral_constant<
169 bool,
170 // clang-format off
171 // Converting from bool is always lossless
172 (kFromKind == kBool) ? true
173 // Converting between any other type kinds will be lossy if the type
174 // kinds are not the same.
175 : (kFromKind != kToKind) ? false
176 : (kFromKind == kInteger &&
177 // Converting between integers of different widths is allowed so long
178 // as the conversion does not go from signed to unsigned.
179 (((sizeof(From) < sizeof(To)) &&
180 !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
181 // Converting between integers of the same width only requires the
182 // two types to have the same signedness.
183 ((sizeof(From) == sizeof(To)) &&
184 (std::is_signed<From>::value == std::is_signed<To>::value)))
185 ) ? true
186 // Floating point conversions are lossless if and only if `To` is at least
187 // as wide as `From`.
188 : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
189 : false
190 // clang-format on
191 >;
192
193// LosslessArithmeticConvertible<From, To>::value is true if and only if
194// arithmetic type From can be losslessly converted to arithmetic type To.
195//
196// It's the user's responsibility to ensure that both From and To are
197// raw (i.e. has no CV modifier, is not a pointer, and is not a
198// reference) built-in arithmetic types; the value is
199// implementation-defined when the above pre-condition is violated.
200template <typename From, typename To>
204
205// This interface knows how to report a Google Mock failure (either
206// non-fatal or fatal).
208 public:
209 // The type of a failure (either non-fatal or fatal).
212 };
213
215
216 // Reports a failure that occurred at the given source file location.
217 virtual void ReportFailure(FailureType type, const char* file, int line,
218 const std::string& message) = 0;
219};
220
221// Returns the failure reporter used by Google Mock.
223
224// Asserts that condition is true; aborts the process with the given
225// message if condition is false. We cannot use LOG(FATAL) or CHECK()
226// as Google Mock might be used to mock the log sink itself. We
227// inline this function to prevent it from showing up in the stack
228// trace.
229inline void Assert(bool condition, const char* file, int line,
230 const std::string& msg) {
231 if (!condition) {
233 file, line, msg);
234 }
235}
236inline void Assert(bool condition, const char* file, int line) {
237 Assert(condition, file, line, "Assertion failed.");
238}
239
240// Verifies that condition is true; generates a non-fatal failure if
241// condition is false.
242inline void Expect(bool condition, const char* file, int line,
243 const std::string& msg) {
244 if (!condition) {
246 file, line, msg);
247 }
248}
249inline void Expect(bool condition, const char* file, int line) {
250 Expect(condition, file, line, "Expectation failed.");
251}
252
253// Severity level of a log.
255 kInfo = 0,
256 kWarning = 1
258
259// Valid values for the --gmock_verbose flag.
260
261// All logs (informational and warnings) are printed.
262const char kInfoVerbosity[] = "info";
263// Only warnings are printed.
264const char kWarningVerbosity[] = "warning";
265// No logs are printed.
266const char kErrorVerbosity[] = "error";
267
268// Returns true if and only if a log with the given severity is visible
269// according to the --gmock_verbose flag.
270GTEST_API_ bool LogIsVisible(LogSeverity severity);
271
272// Prints the given message to stdout if and only if 'severity' >= the level
273// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
274// 0, also prints the stack trace excluding the top
275// stack_frames_to_skip frames. In opt mode, any positive
276// stack_frames_to_skip is treated as 0, since we don't know which
277// function calls will be inlined by the compiler and need to be
278// conservative.
279GTEST_API_ void Log(LogSeverity severity, const std::string& message,
280 int stack_frames_to_skip);
281
282// A marker class that is used to resolve parameterless expectations to the
283// correct overload. This must not be instantiable, to prevent client code from
284// accidentally resolving to the overload; for example:
285//
286// ON_CALL(mock, Method({}, nullptr))...
287//
289 private:
292};
293
294// Internal use only: access the singleton instance of WithoutMatchers.
295GTEST_API_ WithoutMatchers GetWithoutMatchers();
296
297// Disable MSVC warnings for infinite recursion, since in this case the
298// the recursion is unreachable.
299#ifdef _MSC_VER
300# pragma warning(push)
301# pragma warning(disable:4717)
302#endif
303
304// Invalid<T>() is usable as an expression of type T, but will terminate
305// the program with an assertion failure if actually run. This is useful
306// when a value of type T is needed for compilation, but the statement
307// will not really be executed (or we don't care if the statement
308// crashes).
309template <typename T>
310inline T Invalid() {
311 Assert(false, "", -1, "Internal error: attempt to return invalid value");
312 // This statement is unreachable, and would never terminate even if it
313 // could be reached. It is provided only to placate compiler warnings
314 // about missing return statements.
315 return Invalid<T>();
316}
317
318#ifdef _MSC_VER
319# pragma warning(pop)
320#endif
321
322// Given a raw type (i.e. having no top-level reference or const
323// modifier) RawContainer that's either an STL-style container or a
324// native array, class StlContainerView<RawContainer> has the
325// following members:
326//
327// - type is a type that provides an STL-style container view to
328// (i.e. implements the STL container concept for) RawContainer;
329// - const_reference is a type that provides a reference to a const
330// RawContainer;
331// - ConstReference(raw_container) returns a const reference to an STL-style
332// container view to raw_container, which is a RawContainer.
333// - Copy(raw_container) returns an STL-style container view of a
334// copy of raw_container, which is a RawContainer.
335//
336// This generic version is used when RawContainer itself is already an
337// STL-style container.
338template <class RawContainer>
340 public:
341 typedef RawContainer type;
342 typedef const type& const_reference;
343
344 static const_reference ConstReference(const RawContainer& container) {
345 static_assert(!std::is_const<RawContainer>::value,
346 "RawContainer type must not be const");
347 return container;
348 }
349 static type Copy(const RawContainer& container) { return container; }
350};
351
352// This specialization is used when RawContainer is a native array type.
353template <typename Element, size_t N>
354class StlContainerView<Element[N]> {
355 public:
356 typedef typename std::remove_const<Element>::type RawElement;
358 // NativeArray<T> can represent a native array either by value or by
359 // reference (selected by a constructor argument), so 'const type'
360 // can be used to reference a const native array. We cannot
361 // 'typedef const type& const_reference' here, as that would mean
362 // ConstReference() has to return a reference to a local variable.
363 typedef const type const_reference;
364
365 static const_reference ConstReference(const Element (&array)[N]) {
366 static_assert(std::is_same<Element, RawElement>::value,
367 "Element type must not be const");
368 return type(array, N, RelationToSourceReference());
369 }
370 static type Copy(const Element (&array)[N]) {
371 return type(array, N, RelationToSourceCopy());
372 }
373};
374
375// This specialization is used when RawContainer is a native array
376// represented as a (pointer, size) tuple.
377template <typename ElementPointer, typename Size>
378class StlContainerView< ::std::tuple<ElementPointer, Size> > {
379 public:
380 typedef typename std::remove_const<
383 typedef const type const_reference;
384
386 const ::std::tuple<ElementPointer, Size>& array) {
387 return type(std::get<0>(array), std::get<1>(array),
389 }
390 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
391 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
392 }
393};
394
395// The following specialization prevents the user from instantiating
396// StlContainer with a reference type.
397template <typename T> class StlContainerView<T&>;
398
399// A type transform to remove constness from the first part of a pair.
400// Pairs like that are used as the value_type of associative containers,
401// and this transform produces a similar but assignable pair.
402template <typename T>
404 typedef T type;
405};
406
407// Partially specialized to remove constness from std::pair<const K, V>.
408template <typename K, typename V>
409struct RemoveConstFromKey<std::pair<const K, V> > {
410 typedef std::pair<K, V> type;
411};
412
413// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
414// reduce code size.
415GTEST_API_ void IllegalDoDefault(const char* file, int line);
416
417template <typename F, typename Tuple, size_t... Idx>
418auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
419 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
420 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
421}
422
423// Apply the function to a tuple of arguments.
424template <typename F, typename Tuple>
425auto Apply(F&& f, Tuple&& args) -> decltype(
426 ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
427 MakeIndexSequence<std::tuple_size<
428 typename std::remove_reference<Tuple>::type>::value>())) {
429 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
430 MakeIndexSequence<std::tuple_size<
431 typename std::remove_reference<Tuple>::type>::value>());
432}
433
434// Template struct Function<F>, where F must be a function type, contains
435// the following typedefs:
436//
437// Result: the function's return type.
438// Arg<N>: the type of the N-th argument, where N starts with 0.
439// ArgumentTuple: the tuple type consisting of all parameters of F.
440// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
441// parameters of F.
442// MakeResultVoid: the function type obtained by substituting void
443// for the return type of F.
444// MakeResultIgnoredValue:
445// the function type obtained by substituting Something
446// for the return type of F.
447template <typename T>
448struct Function;
449
450template <typename R, typename... Args>
451struct Function<R(Args...)> {
452 using Result = R;
453 static constexpr size_t ArgumentCount = sizeof...(Args);
454 template <size_t I>
455 using Arg = ElemFromList<I, Args...>;
456 using ArgumentTuple = std::tuple<Args...>;
457 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
458 using MakeResultVoid = void(Args...);
460};
461
462template <typename R, typename... Args>
463constexpr size_t Function<R(Args...)>::ArgumentCount;
464
465#ifdef _MSC_VER
466# pragma warning(pop)
467#endif
468
469} // namespace internal
470} // namespace testing
471
472#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
expr expr expr bar false
expr true
#define T
Definition: Sacado_rad.hpp:573
#define F
Definition: Sacado_rad.hpp:574
#define R
Definition: Sacado_rad.hpp:181
const int N
virtual void ReportFailure(FailureType type, const char *file, int line, const std::string &message)=0
static const_reference ConstReference(const Element(&array)[N])
static type Copy(const Element(&array)[N])
std::remove_const< typenameinternal::PointeeOf< ElementPointer >::type >::type RawElement
static type Copy(const ::std::tuple< ElementPointer, Size > &array)
static const_reference ConstReference(const ::std::tuple< ElementPointer, Size > &array)
static const_reference ConstReference(const RawContainer &container)
static type Copy(const RawContainer &container)
friend GTEST_API_ WithoutMatchers GetWithoutMatchers()
#define GMOCK_KIND_OF_(type)
#define GMOCK_DECLARE_KIND_(type, kind)
int value
const char * p
#define GTEST_API_
Definition: gtest-port.h:775
GTEST_API_ std::string ConvertIdentifierNameToWords(const char *id_name)
const char kErrorVerbosity[]
auto Apply(F &&f, Tuple &&args) -> decltype(ApplyImpl(std::forward< F >(f), std::forward< Tuple >(args), MakeIndexSequence< std::tuple_size< typename std::remove_reference< Tuple >::type >::value >()))
GTEST_API_ std::string JoinAsTuple(const Strings &fields)
::std::vector< ::std::string > Strings
GTEST_API_ bool LogIsVisible(LogSeverity severity)
auto ApplyImpl(F &&f, Tuple &&args, IndexSequence< Idx... >) -> decltype(std::forward< F >(f)(std::get< Idx >(std::forward< Tuple >(args))...))
GTEST_API_ void Log(LogSeverity severity, const std::string &message, int stack_frames_to_skip)
GTEST_API_ FailureReporterInterface * GetFailureReporter()
void Assert(bool condition, const char *file, int line, const std::string &msg)
GTEST_API_ void IllegalDoDefault(const char *file, int line)
LosslessArithmeticConvertibleImpl< GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To > LosslessArithmeticConvertible
std::integral_constant< bool,(kFromKind==kBool) ? true :(kFromKind !=kToKind) ? false :(kFromKind==kInteger &&(((sizeof(From)< sizeof(To)) &&!(std::is_signed< From >::value &&!std::is_signed< To >::value))||((sizeof(From)==sizeof(To)) &&(std::is_signed< From >::value==std::is_signed< To >::value)))) ? true :(kFromKind==kFloatingPoint &&(sizeof(From)<=sizeof(To))) ? true :false > LosslessArithmeticConvertibleImpl
GTEST_API_ WithoutMatchers GetWithoutMatchers()
const Pointer::element_type * GetRawPointer(const Pointer &p)
void Expect(bool condition, const char *file, int line, const std::string &msg)
const char kWarningVerbosity[]
std::tuple< Matcher< Args >... > ArgumentMatcherTuple