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