blob: bdc8288295daf376f08be046c43e1fb0c687bef2 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file defines some utilities useful for implementing Google
35// Mock. They are subject to change without notice, so please DO NOT
36// USE THEM IN USER CODE.
37
38#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
39#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40
41#include <stdio.h>
42#include <ostream> // NOLINT
43#include <string>
44
45#include <gmock/internal/gmock-generated-internal-utils.h>
46#include <gmock/internal/gmock-port.h>
47#include <gtest/gtest.h>
48
49// Concatenates two pre-processor symbols; works for concatenating
50// built-in macros like __FILE__ and __LINE__.
51#define GMOCK_CONCAT_TOKEN_IMPL(foo, bar) foo##bar
52#define GMOCK_CONCAT_TOKEN(foo, bar) GMOCK_CONCAT_TOKEN_IMPL(foo, bar)
53
54#ifdef __GNUC__
55#define GMOCK_ATTRIBUTE_UNUSED __attribute__ ((unused))
56#else
57#define GMOCK_ATTRIBUTE_UNUSED
58#endif // __GNUC__
59
60class ProtocolMessage;
61namespace proto2 { class Message; }
62
63namespace testing {
64namespace internal {
65
66// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
67// compiler error iff T1 and T2 are different types.
68template <typename T1, typename T2>
69struct CompileAssertTypesEqual;
70
71template <typename T>
72struct CompileAssertTypesEqual<T, T> {
73};
74
75// Removes the reference from a type if it is a reference type,
76// otherwise leaves it unchanged. This is the same as
77// tr1::remove_reference, which is not widely available yet.
78template <typename T>
79struct RemoveReference { typedef T type; }; // NOLINT
80template <typename T>
81struct RemoveReference<T&> { typedef T type; }; // NOLINT
82
83// A handy wrapper around RemoveReference that works when the argument
84// T depends on template parameters.
85#define GMOCK_REMOVE_REFERENCE(T) \
86 typename ::testing::internal::RemoveReference<T>::type
87
88// Removes const from a type if it is a const type, otherwise leaves
89// it unchanged. This is the same as tr1::remove_const, which is not
90// widely available yet.
91template <typename T>
92struct RemoveConst { typedef T type; }; // NOLINT
93template <typename T>
94struct RemoveConst<const T> { typedef T type; }; // NOLINT
95
96// A handy wrapper around RemoveConst that works when the argument
97// T depends on template parameters.
98#define GMOCK_REMOVE_CONST(T) \
99 typename ::testing::internal::RemoveConst<T>::type
100
101// Adds reference to a type if it is not a reference type,
102// otherwise leaves it unchanged. This is the same as
103// tr1::add_reference, which is not widely available yet.
104template <typename T>
105struct AddReference { typedef T& type; }; // NOLINT
106template <typename T>
107struct AddReference<T&> { typedef T& type; }; // NOLINT
108
109// A handy wrapper around AddReference that works when the argument T
110// depends on template parameters.
111#define GMOCK_ADD_REFERENCE(T) \
112 typename ::testing::internal::AddReference<T>::type
113
114// Adds a reference to const on top of T as necessary. For example,
115// it transforms
116//
117// char ==> const char&
118// const char ==> const char&
119// char& ==> const char&
120// const char& ==> const char&
121//
122// The argument T must depend on some template parameters.
123#define GMOCK_REFERENCE_TO_CONST(T) \
124 GMOCK_ADD_REFERENCE(const GMOCK_REMOVE_REFERENCE(T))
125
126// PointeeOf<Pointer>::type is the type of a value pointed to by a
127// Pointer, which can be either a smart pointer or a raw pointer. The
128// following default implementation is for the case where Pointer is a
129// smart pointer.
130template <typename Pointer>
131struct PointeeOf {
132 // Smart pointer classes define type element_type as the type of
133 // their pointees.
134 typedef typename Pointer::element_type type;
135};
136// This specialization is for the raw pointer case.
137template <typename T>
138struct PointeeOf<T*> { typedef T type; }; // NOLINT
139
140// GetRawPointer(p) returns the raw pointer underlying p when p is a
141// smart pointer, or returns p itself when p is already a raw pointer.
142// The following default implementation is for the smart pointer case.
143template <typename Pointer>
144inline typename Pointer::element_type* GetRawPointer(const Pointer& p) {
145 return p.get();
146}
147// This overloaded version is for the raw pointer case.
148template <typename Element>
149inline Element* GetRawPointer(Element* p) { return p; }
150
151// This comparator allows linked_ptr to be stored in sets.
152template <typename T>
153struct LinkedPtrLessThan {
154 bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
155 const ::testing::internal::linked_ptr<T>& rhs) const {
156 return lhs.get() < rhs.get();
157 }
158};
159
160// ImplicitlyConvertible<From, To>::value is a compile-time bool
161// constant that's true iff type From can be implicitly converted to
162// type To.
163template <typename From, typename To>
164class ImplicitlyConvertible {
165 private:
166 // We need the following helper functions only for their types.
167 // They have no implementations.
168
169 // MakeFrom() is an expression whose type is From. We cannot simply
170 // use From(), as the type From may not have a public default
171 // constructor.
172 static From MakeFrom();
173
174 // These two functions are overloaded. Given an expression
175 // Helper(x), the compiler will pick the first version if x can be
176 // implicitly converted to type To; otherwise it will pick the
177 // second version.
178 //
179 // The first version returns a value of size 1, and the second
180 // version returns a value of size 2. Therefore, by checking the
181 // size of Helper(x), which can be done at compile time, we can tell
182 // which version of Helper() is used, and hence whether x can be
183 // implicitly converted to type To.
184 static char Helper(To);
185 static char (&Helper(...))[2]; // NOLINT
186
187 // We have to put the 'public' section after the 'private' section,
188 // or MSVC refuses to compile the code.
189 public:
190 // MSVC warns about implicitly converting from double to int for
191 // possible loss of data, so we need to temporarily disable the
192 // warning.
193#ifdef _MSC_VER
194#pragma warning(push) // Saves the current warning state.
195#pragma warning(disable:4244) // Temporarily disables warning 4244.
196 static const bool value =
197 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
198#pragma warning(pop) // Restores the warning state.
199#else
200 static const bool value =
201 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
202#endif // _MSV_VER
203};
204template <typename From, typename To>
205const bool ImplicitlyConvertible<From, To>::value;
206
207// IsAProtocolMessage<T>::value is a compile-time bool constant that's
208// true iff T is type ProtocolMessage, proto2::Message, or a subclass
209// of those.
210template <typename T>
211struct IsAProtocolMessage {
212 static const bool value =
213 ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
214 ImplicitlyConvertible<const T*, const ::proto2::Message*>::value;
215};
216template <typename T>
217const bool IsAProtocolMessage<T>::value;
218
219// When the compiler sees expression IsContainerTest<C>(0), the first
220// overload of IsContainerTest will be picked if C is an STL-style
221// container class (since C::const_iterator* is a valid type and 0 can
222// be converted to it), while the second overload will be picked
223// otherwise (since C::const_iterator will be an invalid type in this
224// case). Therefore, we can determine whether C is a container class
225// by checking the type of IsContainerTest<C>(0). The value of the
226// expression is insignificant.
227typedef int IsContainer;
228template <class C>
229IsContainer IsContainerTest(typename C::const_iterator*) { return 0; }
230
231typedef char IsNotContainer;
232template <class C>
233IsNotContainer IsContainerTest(...) { return '\0'; }
234
235// This interface knows how to report a Google Mock failure (either
236// non-fatal or fatal).
237class FailureReporterInterface {
238 public:
239 // The type of a failure (either non-fatal or fatal).
240 enum FailureType {
241 NONFATAL, FATAL
242 };
243
244 virtual ~FailureReporterInterface() {}
245
246 // Reports a failure that occurred at the given source file location.
247 virtual void ReportFailure(FailureType type, const char* file, int line,
248 const string& message) = 0;
249};
250
251// Returns the failure reporter used by Google Mock.
252FailureReporterInterface* GetFailureReporter();
253
254// Asserts that condition is true; aborts the process with the given
255// message if condition is false. We cannot use LOG(FATAL) or CHECK()
256// as Google Mock might be used to mock the log sink itself. We
257// inline this function to prevent it from showing up in the stack
258// trace.
259inline void Assert(bool condition, const char* file, int line,
260 const string& msg) {
261 if (!condition) {
262 GetFailureReporter()->ReportFailure(FailureReporterInterface::FATAL,
263 file, line, msg);
264 }
265}
266inline void Assert(bool condition, const char* file, int line) {
267 Assert(condition, file, line, "Assertion failed.");
268}
269
270// Verifies that condition is true; generates a non-fatal failure if
271// condition is false.
272inline void Expect(bool condition, const char* file, int line,
273 const string& msg) {
274 if (!condition) {
275 GetFailureReporter()->ReportFailure(FailureReporterInterface::NONFATAL,
276 file, line, msg);
277 }
278}
279inline void Expect(bool condition, const char* file, int line) {
280 Expect(condition, file, line, "Expectation failed.");
281}
282
283// Severity level of a log.
284enum LogSeverity {
285 INFO = 0,
286 WARNING = 1,
287};
288
289// Valid values for the --gmock_verbose flag.
290
291// All logs (informational and warnings) are printed.
292const char kInfoVerbosity[] = "info";
293// Only warnings are printed.
294const char kWarningVerbosity[] = "warning";
295// No logs are printed.
296const char kErrorVerbosity[] = "error";
297
298// Prints the given message to stdout iff 'severity' >= the level
299// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
300// 0, also prints the stack trace excluding the top
301// stack_frames_to_skip frames. In opt mode, any positive
302// stack_frames_to_skip is treated as 0, since we don't know which
303// function calls will be inlined by the compiler and need to be
304// conservative.
305void Log(LogSeverity severity, const string& message, int stack_frames_to_skip);
306
307// The universal value printer (public/gmock-printers.h) needs this
308// to declare an unused << operator in the global namespace.
309struct Unused {};
310
311// Type traits.
312
313// is_reference<T>::value is non-zero iff T is a reference type.
314template <typename T> struct is_reference : public false_type {};
315template <typename T> struct is_reference<T&> : public true_type {};
316
317// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
318template <typename T1, typename T2> struct type_equals : public false_type {};
319template <typename T> struct type_equals<T, T> : public true_type {};
320
321// remove_reference<T>::type removes the reference from type T, if any.
322template <typename T> struct remove_reference { typedef T type; };
323template <typename T> struct remove_reference<T&> { typedef T type; };
324
325// Invalid<T>() returns an invalid value of type T. This is useful
326// when a value of type T is needed for compilation, but the statement
327// will not really be executed (or we don't care if the statement
328// crashes).
329template <typename T>
330inline T Invalid() {
331 return *static_cast<typename remove_reference<T>::type*>(NULL);
332}
333template <>
334inline void Invalid<void>() {}
335
336} // namespace internal
337} // namespace testing
338
339#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_