gmock-internal-utils.h 18 KB

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