gmock-internal-utils.h 18 KB

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