diff --git a/include/gmock/gmock-actions.h b/include/gmock/gmock-actions.h index 7e9708ec..d08152a8 100644 --- a/include/gmock/gmock-actions.h +++ b/include/gmock/gmock-actions.h @@ -1,1078 +1,1114 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used actions. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE # include <errno.h> #endif #include <algorithm> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" namespace testing { // To implement an action Foo, define: // 1. a class FooAction that implements the ActionInterface interface, and // 2. a factory function that creates an Action object from a // const FooAction*. // // The two-level delegation design follows that of Matcher, providing // consistency for extension developers. It also eases ownership // management as Action objects can now be copied like plain values. namespace internal { template <typename F1, typename F2> class ActionAdaptor; // BuiltInDefaultValue<T>::Get() returns the "built-in" default // value for type T, which is NULL when T is a pointer type, 0 when T // is a numeric type, false when T is bool, or "" when T is string or // std::string. For any other type T, this value is undefined and the // function will abort the process. template <typename T> class BuiltInDefaultValue { public: // This function returns true iff type T has a built-in default value. static bool Exists() { return false; } static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); return internal::Invalid<T>(); // The above statement will never be reached, but is required in // order for this function to compile. } }; // This partial specialization says that we use the same built-in // default value for T and const T. template <typename T> class BuiltInDefaultValue<const T> { public: static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } static T Get() { return BuiltInDefaultValue<T>::Get(); } }; // This partial specialization defines the default values for pointer // types. template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } static T* Get() { return NULL; } }; // The following specializations define the default values for // specific types we care about. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ template <> \ class BuiltInDefaultValue<type> { \ public: \ static bool Exists() { return true; } \ static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT #if GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, ""); #endif // GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); // There's no need for a default action for signed wchar_t, as that // type is the same as wchar_t for gcc, and invalid for MSVC. // // There's also no need for a default action for unsigned wchar_t, as // that type is the same as unsigned int for gcc, and invalid for // MSVC. #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT #endif GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ } // namespace internal // When an unexpected function call is encountered, Google Mock will // let it return a default value if the user has specified one for its // return type, or if the return type has a built-in default value; // otherwise Google Mock won't know what value to return and will have // to abort the process. // // The DefaultValue<T> class allows a user to specify the // default value for a type T that is both copyable and publicly // destructible (i.e. anything that can be used as a function return // type). The usage is: // // // Sets the default value for type T to be foo. // DefaultValue<T>::Set(foo); template <typename T> class DefaultValue { public: // Sets the default value for type T; requires T to be // copy-constructable and have a public destructor. static void Set(T x) { - delete value_; - value_ = new T(x); + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); } // Unsets the default value for type T. static void Clear() { - delete value_; - value_ = NULL; + delete producer_; + producer_ = NULL; } // Returns true iff the user has set the default value for type T. - static bool IsSet() { return value_ != NULL; } + static bool IsSet() { return producer_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); } // Returns the default value for type T if the user has set one; - // otherwise returns the built-in default value if there is one; - // otherwise aborts the process. + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. static T Get() { - return value_ == NULL ? - internal::BuiltInDefaultValue<T>::Get() : *value_; + return producer_ == NULL ? + internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); } private: - static const T* value_; + class ValueProducer { + public: + virtual ~ValueProducer() {} + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + virtual T Produce() { return value_; } + + private: + const T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + virtual T Produce() { return factory_(); } + + private: + const FactoryFunction factory_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); + }; + + static ValueProducer* producer_; }; // This partial specialization allows a user to set default values for // reference types. template <typename T> class DefaultValue<T&> { public: // Sets the default value for type T&. static void Set(T& x) { // NOLINT address_ = &x; } // Unsets the default value for type T&. static void Clear() { address_ = NULL; } // Returns true iff the user has set the default value for type T&. static bool IsSet() { return address_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); } // Returns the default value for type T& if the user has set one; // otherwise returns the built-in default value if there is one; // otherwise aborts the process. static T& Get() { return address_ == NULL ? internal::BuiltInDefaultValue<T&>::Get() : *address_; } private: static T* address_; }; // This specialization allows DefaultValue<void>::Get() to // compile. template <> class DefaultValue<void> { public: static bool Exists() { return true; } static void Get() {} }; // Points to the user-set default value for type T. template <typename T> -const T* DefaultValue<T>::value_ = NULL; +typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL; // Points to the user-set default value for type T&. template <typename T> T* DefaultValue<T&>::address_ = NULL; // Implement this interface to define an action for function type F. template <typename F> class ActionInterface { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; ActionInterface() {} virtual ~ActionInterface() {} // Performs the action. This method is not const, as in general an // action can have side effects and be stateful. For example, a // get-the-next-element-from-the-collection action will need to // remember the current element. virtual Result Perform(const ArgumentTuple& args) = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); }; // An Action<F> is a copyable and IMMUTABLE (except by assignment) // object that represents an action to be taken when a mock function // of type F is called. The implementation of Action<T> is just a // linked_ptr to const ActionInterface<T>, so copying is fairly cheap. // Don't inherit from Action! // // You can view an object implementing ActionInterface<F> as a // concrete action (including its current state), and an Action<F> // object as a handle to it. template <typename F> class Action { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; // Constructs a null Action. Needed for storing Action objects in // STL containers. Action() : impl_(NULL) {} // Constructs an Action from its implementation. A NULL impl is // used to represent the "do-default" action. explicit Action(ActionInterface<F>* impl) : impl_(impl) {} // Copy constructor. Action(const Action& action) : impl_(action.impl_) {} // This constructor allows us to turn an Action<Func> object into an // Action<F>, as long as F's arguments can be implicitly converted // to Func's and Func's return type can be implicitly converted to // F's. template <typename Func> explicit Action(const Action<Func>& action); // Returns true iff this is the DoDefault() action. bool IsDoDefault() const { return impl_.get() == NULL; } // Performs the action. Note that this method is const even though // the corresponding method in ActionInterface is not. The reason // is that a const Action<F> means that it cannot be re-bound to // another concrete action, not that the concrete action it binds to // cannot change state. (Think of the difference between a const // pointer and a pointer to const.) Result Perform(const ArgumentTuple& args) const { internal::Assert( !IsDoDefault(), __FILE__, __LINE__, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); return impl_->Perform(args); } private: template <typename F1, typename F2> friend class internal::ActionAdaptor; internal::linked_ptr<ActionInterface<F> > impl_; }; // The PolymorphicAction class template makes it easy to implement a // polymorphic action (i.e. an action that can be used in mock // functions of than one type, e.g. Return()). // // To define a polymorphic action, a user first provides a COPYABLE // implementation class that has a Perform() method template: // // class FooAction { // public: // template <typename Result, typename ArgumentTuple> // Result Perform(const ArgumentTuple& args) const { // // Processes the arguments and returns a result, using // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple. // } // ... // }; // // Then the user creates the polymorphic action using // MakePolymorphicAction(object) where object has type FooAction. See // the definition of Return(void) and SetArgumentPointee<N>(value) for // complete examples. template <typename Impl> class PolymorphicAction { public: explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} template <typename F> operator Action<F>() const { return Action<F>(new MonomorphicImpl<F>(impl_)); } private: template <typename F> class MonomorphicImpl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual Result Perform(const ArgumentTuple& args) { return impl_.template Perform<Result>(args); } private: Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicAction); }; // Creates an Action from its implementation and returns it. The // created Action object owns the implementation. template <typename F> Action<F> MakeAction(ActionInterface<F>* impl) { return Action<F>(impl); } // Creates a polymorphic action from its implementation. This is // easier to use than the PolymorphicAction<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicAction(foo); // vs // PolymorphicAction<TypeOfFoo>(foo); template <typename Impl> inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { return PolymorphicAction<Impl>(impl); } namespace internal { // Allows an Action<F2> object to pose as an Action<F1>, as long as F2 // and F1 are compatible. template <typename F1, typename F2> class ActionAdaptor : public ActionInterface<F1> { public: typedef typename internal::Function<F1>::Result Result; typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple; explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {} virtual Result Perform(const ArgumentTuple& args) { return impl_->Perform(args); } private: const internal::linked_ptr<ActionInterface<F2> > impl_; GTEST_DISALLOW_ASSIGN_(ActionAdaptor); }; // Implements the polymorphic Return(x) action, which can be used in // any function that returns the type of x, regardless of the argument // types. // // Note: The value passed into Return must be converted into // Function<F>::Result when this action is cast to Action<F> rather than // when that action is performed. This is important in scenarios like // // MOCK_METHOD1(Method, T(U)); // ... // { // Foo foo; // X x(&foo); // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); // } // // In the example above the variable x holds reference to foo which leaves // scope and gets destroyed. If copying X just copies a reference to foo, // that copy will be left with a hanging reference. If conversion to T // makes a copy of foo, the above code is safe. To support that scenario, we // need to make sure that the type conversion happens inside the EXPECT_CALL // statement, and conversion of the result of Return to Action<T(U)> is a // good place for that. // template <typename R> class ReturnAction { public: // Constructs a ReturnAction object from the value to be returned. // 'value' is passed by value instead of by const reference in order // to allow Return("string literal") to compile. explicit ReturnAction(R value) : value_(value) {} // This template type conversion operator allows Return(x) to be // used in ANY function that returns x's type. template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename Function<F>::Result Result; GTEST_COMPILE_ASSERT_( !internal::is_reference<Result>::value, use_ReturnRef_instead_of_Return_to_return_a_reference); return Action<F>(new Impl<F>(value_)); } private: // Implements the Return(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; // The implicit cast is necessary when Result has more than one // single-argument constructor (e.g. Result is std::vector<int>) and R // has a type conversion operator template. In that case, value_(value) // won't compile as the compiler doesn't known which constructor of // Result to call. ImplicitCast_ forces the compiler to convert R to // Result without considering explicit constructors, thus resolving the // ambiguity. value_ is then initialized using its copy constructor. explicit Impl(R value) : value_(::testing::internal::ImplicitCast_<Result>(value)) {} virtual Result Perform(const ArgumentTuple&) { return value_; } private: GTEST_COMPILE_ASSERT_(!internal::is_reference<Result>::value, Result_cannot_be_a_reference_type); Result value_; GTEST_DISALLOW_ASSIGN_(Impl); }; R value_; GTEST_DISALLOW_ASSIGN_(ReturnAction); }; // Implements the ReturnNull() action. class ReturnNullAction { public: // Allows ReturnNull() to be used in any pointer-returning function. template <typename Result, typename ArgumentTuple> static Result Perform(const ArgumentTuple&) { GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value, ReturnNull_can_be_used_to_return_a_pointer_only); return NULL; } }; // Implements the Return() action. class ReturnVoidAction { public: // Allows Return() to be used in any void-returning function. template <typename Result, typename ArgumentTuple> static void Perform(const ArgumentTuple&) { CompileAssertTypesEqual<void, Result>(); } }; // Implements the polymorphic ReturnRef(x) action, which can be used // in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefAction { public: // Constructs a ReturnRefAction object from the reference to be returned. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT // This template type conversion operator allows ReturnRef(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRef(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value, use_Return_instead_of_ReturnRef_to_return_a_value); return Action<F>(new Impl<F>(ref_)); } private: // Implements the ReturnRef(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(T& ref) : ref_(ref) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return ref_; } private: T& ref_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& ref_; GTEST_DISALLOW_ASSIGN_(ReturnRefAction); }; // Implements the polymorphic ReturnRefOfCopy(x) action, which can be // used in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefOfCopyAction { public: // Constructs a ReturnRefOfCopyAction object from the reference to // be returned. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT // This template type conversion operator allows ReturnRefOfCopy(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRefOfCopy(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_( internal::is_reference<Result>::value, use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); return Action<F>(new Impl<F>(value_)); } private: // Implements the ReturnRefOfCopy(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const T& value) : value_(value) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return value_; } private: T value_; GTEST_DISALLOW_ASSIGN_(Impl); }; const T value_; GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); }; // Implements the polymorphic DoDefault() action. class DoDefaultAction { public: // This template type conversion operator allows DoDefault() to be // used in any function. template <typename F> operator Action<F>() const { return Action<F>(NULL); } }; // Implements the Assign action to set a given pointer referent to a // particular value. template <typename T1, typename T2> class AssignAction { public: AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& /* args */) const { *ptr_ = value_; } private: T1* const ptr_; const T2 value_; GTEST_DISALLOW_ASSIGN_(AssignAction); }; #if !GTEST_OS_WINDOWS_MOBILE // Implements the SetErrnoAndReturn action to simulate return from // various system calls and libc functions. template <typename T> class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) : errno_(errno_value), result_(result) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; return result_; } private: const int errno_; const T result_; GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); }; #endif // !GTEST_OS_WINDOWS_MOBILE // Implements the SetArgumentPointee<N>(x) action for any function // whose N-th argument (0-based) is a pointer to x's type. The // template parameter kIsProto is true iff type A is ProtocolMessage, // proto2::Message, or a sub-class of those. template <size_t N, typename A, bool kIsProto> class SetArgumentPointeeAction { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'value'. explicit SetArgumentPointeeAction(const A& value) : value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); *::std::tr1::get<N>(args) = value_; } private: const A value_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; template <size_t N, typename Proto> class SetArgumentPointeeAction<N, Proto, true> { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'proto'. Both ProtocolMessage and // proto2::Message have the CopyFrom() method, so the same // implementation works for both. explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { proto_->CopyFrom(proto); } template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); ::std::tr1::get<N>(args)->CopyFrom(*proto_); } private: const internal::linked_ptr<Proto> proto_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; // Implements the InvokeWithoutArgs(f) action. The template argument // FunctionImpl is the implementation type of f, which can be either a // function pointer or a functor. InvokeWithoutArgs(f) can be used as an // Action<F> as long as f's type is compatible with F (i.e. f can be // assigned to a tr1::function<F>). template <typename FunctionImpl> class InvokeWithoutArgsAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). explicit InvokeWithoutArgsAction(FunctionImpl function_impl) : function_impl_(function_impl) {} // Allows InvokeWithoutArgs(f) to be used as any action whose type is // compatible with f. template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) { return function_impl_(); } private: FunctionImpl function_impl_; GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction); }; // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. template <class Class, typename MethodPtr> class InvokeMethodWithoutArgsAction { public: InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) const { return (obj_ptr_->*method_ptr_)(); } private: Class* const obj_ptr_; const MethodPtr method_ptr_; GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction); }; // Implements the IgnoreResult(action) action. template <typename A> class IgnoreResultAction { public: explicit IgnoreResultAction(const A& action) : action_(action) {} template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename internal::Function<F>::Result Result; // Asserts at compile time that F returns void. CompileAssertTypesEqual<void, Result>(); return Action<F>(new Impl<F>(action_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const A& action) : action_(action) {} virtual void Perform(const ArgumentTuple& args) { // Performs the action and ignores its result. action_.Perform(args); } private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. typedef typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; const Action<OriginalFunction> action_; GTEST_DISALLOW_ASSIGN_(Impl); }; const A action_; GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); }; // A ReferenceWrapper<T> object represents a reference to type T, // which can be either const or not. It can be explicitly converted // from, and implicitly converted to, a T&. Unlike a reference, // ReferenceWrapper<T> can be copied and can survive template type // inference. This is used to support by-reference arguments in the // InvokeArgument<N>(...) action. The idea was from "reference // wrappers" in tr1, which we don't have in our source tree yet. template <typename T> class ReferenceWrapper { public: // Constructs a ReferenceWrapper<T> object from a T&. explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT // Allows a ReferenceWrapper<T> object to be implicitly converted to // a T&. operator T&() const { return *pointer_; } private: T* pointer_; }; // Allows the expression ByRef(x) to be printed as a reference to x. template <typename T> void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) { T& value = ref; UniversalPrinter<T&>::Print(value, os); } // Does two actions sequentially. Used for implementing the DoAll(a1, // a2, ...) action. template <typename Action1, typename Action2> class DoBothAction { public: DoBothAction(Action1 action1, Action2 action2) : action1_(action1), action2_(action2) {} // This template type conversion operator allows DoAll(a1, ..., a_n) // to be used in ANY function of compatible type. template <typename F> operator Action<F>() const { return Action<F>(new Impl<F>(action1_, action2_)); } private: // Implements the DoAll(...) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::MakeResultVoid VoidResult; Impl(const Action<VoidResult>& action1, const Action<F>& action2) : action1_(action1), action2_(action2) {} virtual Result Perform(const ArgumentTuple& args) { action1_.Perform(args); return action2_.Perform(args); } private: const Action<VoidResult> action1_; const Action<F> action2_; GTEST_DISALLOW_ASSIGN_(Impl); }; Action1 action1_; Action2 action2_; GTEST_DISALLOW_ASSIGN_(DoBothAction); }; } // namespace internal // An Unused object can be implicitly constructed from ANY value. // This is handy when defining actions that ignore some or all of the // mock function arguments. For example, given // // MOCK_METHOD3(Foo, double(const string& label, double x, double y)); // MOCK_METHOD3(Bar, double(int index, double x, double y)); // // instead of // // double DistanceToOriginWithLabel(const string& label, double x, double y) { // return sqrt(x*x + y*y); // } // double DistanceToOriginWithIndex(int index, double x, double y) { // return sqrt(x*x + y*y); // } // ... // EXEPCT_CALL(mock, Foo("abc", _, _)) // .WillOnce(Invoke(DistanceToOriginWithLabel)); // EXEPCT_CALL(mock, Bar(5, _, _)) // .WillOnce(Invoke(DistanceToOriginWithIndex)); // // you could write // // // We can declare any uninteresting argument as Unused. // double DistanceToOrigin(Unused, double x, double y) { // return sqrt(x*x + y*y); // } // ... // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); typedef internal::IgnoredValue Unused; // This constructor allows us to turn an Action<From> object into an // Action<To>, as long as To's arguments can be implicitly converted // to From's and From's return type cann be implicitly converted to // To's. template <typename To> template <typename From> Action<To>::Action(const Action<From>& from) : impl_(new internal::ActionAdaptor<To, From>(from)) {} // Creates an action that returns 'value'. 'value' is passed by value // instead of const reference - otherwise Return("string literal") // will trigger a compiler error about using array as initializer. template <typename R> internal::ReturnAction<R> Return(R value) { return internal::ReturnAction<R>(value); } // Creates an action that returns NULL. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { return MakePolymorphicAction(internal::ReturnNullAction()); } // Creates an action that returns from a void function. inline PolymorphicAction<internal::ReturnVoidAction> Return() { return MakePolymorphicAction(internal::ReturnVoidAction()); } // Creates an action that returns the reference to a variable. template <typename R> inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT return internal::ReturnRefAction<R>(x); } // Creates an action that returns the reference to a copy of the // argument. The copy is created when the action is constructed and // lives as long as the action. template <typename R> inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { return internal::ReturnRefOfCopyAction<R>(x); } // Creates an action that does the default action for the give mock function. inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); } // Creates an action that sets the variable pointed by the N-th // (0-based) function argument to 'value'. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // This overload allows SetArgPointee() to accept a string literal. // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish // this overload from the templated version and emit a compile error. template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const char*, false> > SetArgPointee(const char* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const char*, false>(p)); } template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const wchar_t*, false> > SetArgPointee(const wchar_t* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const wchar_t*, false>(p)); } #endif // The following version is DEPRECATED. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgumentPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } // Creates an action that sets a pointer referent to a given value. template <typename T1, typename T2> PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); } #if !GTEST_OS_WINDOWS_MOBILE // Creates an action that sets errno and returns the appropriate error. template <typename T> PolymorphicAction<internal::SetErrnoAndReturnAction<T> > SetErrnoAndReturn(int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction<T>(errval, result)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Various overloads for InvokeWithoutArgs(). // Creates an action that invokes 'function_impl' with no argument. template <typename FunctionImpl> PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> > InvokeWithoutArgs(FunctionImpl function_impl) { return MakePolymorphicAction( internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl)); } // Creates an action that invokes the given method on the given object // with no argument. template <class Class, typename MethodPtr> PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> > InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) { return MakePolymorphicAction( internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>( obj_ptr, method_ptr)); } // Creates an action that performs an_action and throws away its // result. In other words, it changes the return type of an_action to // void. an_action MUST NOT return void, or the code won't compile. template <typename A> inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { return internal::IgnoreResultAction<A>(an_action); } // Creates a reference wrapper for the given L-value. If necessary, // you can explicitly specify the type of the reference. For example, // suppose 'derived' is an object of type Derived, ByRef(derived) // would wrap a Derived&. If you want to wrap a const Base& instead, // where Base is a base class of Derived, just write: // // ByRef<const Base>(derived) template <typename T> inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT return internal::ReferenceWrapper<T>(l_value); } } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/include/gmock/gmock-spec-builders.h b/include/gmock/gmock-spec-builders.h index 312fbe87..63655b91 100644 --- a/include/gmock/gmock-spec-builders.h +++ b/include/gmock/gmock-spec-builders.h @@ -1,1791 +1,1847 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements the ON_CALL() and EXPECT_CALL() macros. // // A user can use the ON_CALL() macro to specify the default action of // a mock method. The syntax is: // // ON_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matcher) // .WillByDefault(action); // // where the .With() clause is optional. // // A user can use the EXPECT_CALL() macro to specify an expectation on // a mock method. The syntax is: // // EXPECT_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matchers) // .Times(cardinality) // .InSequence(sequences) // .After(expectations) // .WillOnce(action) // .WillRepeatedly(action) // .RetiresOnSaturation(); // // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #include <map> #include <set> #include <sstream> #include <string> #include <vector> #if GTEST_HAS_EXCEPTIONS # include <stdexcept> // NOLINT #endif #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { // An abstract handle of an expectation. class Expectation; // A set of expectation handles. class ExpectationSet; // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // Implements a mock function. template <typename F> class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. template <typename F> class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; // Base class for function mockers. template <typename F> class FunctionMockerBase; // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. // // The reason we don't use more fine-grained protection is: when a // mock function Foo() is called, it needs to consult its expectations // to see which one should be picked. If another thread is allowed to // call a mock function (either Foo() or a different one) at the same // time, it could affect the "retired" attributes of Foo()'s // expectations when InSequence() is used, and thus affect which // expectation gets picked. Therefore, we sequence all mock function // calls to ensure the integrity of the mock objects' states. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); // Untyped base class for ActionResultHolder<R>. class UntypedActionResultHolderBase; // Abstract base class of FunctionMockerBase. This is the // type-agnostic part of the function mocker interface. Its pure // virtual methods are implemented by FunctionMockerBase. class GTEST_API_ UntypedFunctionMockerBase { public: UntypedFunctionMockerBase(); virtual ~UntypedFunctionMockerBase(); // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Clears the ON_CALL()s set on this mock function. virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; // In all of the following Untyped* functions, it's the caller's // responsibility to guarantee the correctness of the arguments' // types. // Performs the default action with the given arguments and returns // the action's result. The call description string will be used in // the error message to describe the call in the case the default // action fails. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( const void* untyped_args, const string& call_description) const = 0; // Performs the given action with the given arguments and returns // the action's result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( const void* untyped_action, const void* untyped_args) const = 0; // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. virtual void UntypedDescribeUninterestingCall( const void* untyped_args, ::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, // untyped_action is set to point to the action that should be // performed (or NULL if the action is "do default"), and // is_excessive is modified to indicate whether the call exceeds the // expected number. virtual const ExpectationBase* UntypedFindMatchingExpectation( const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const = 0; // Sets the mock object this mock method belongs to, and registers // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. // TODO(wan@google.com): rename to SetAndRegisterOwner(). void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Sets the mock object this mock method belongs to, and sets the // name of the mock function. Will be called upon each invocation // of this mock function. void SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the mock object this mock method belongs to. Must be // called after RegisterOwner() or SetOwnerAndName() has been // called. const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. The caller is responsible for deleting the // result. - const UntypedActionResultHolderBase* UntypedInvokeWith( + UntypedActionResultHolderBase* UntypedInvokeWith( const void* untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector<const void*> UntypedOnCallSpecs; typedef std::vector<internal::linked_ptr<ExpectationBase> > UntypedExpectations; // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation GetHandleOf(ExpectationBase* exp); // Address of the mock object this mock method belongs to. Only // valid after this mock method has been called or // ON_CALL/EXPECT_CALL has been invoked on it. const void* mock_obj_; // Protected by g_gmock_mutex. // Name of the function being mocked. Only valid after this mock // method has been called. const char* name_; // Protected by g_gmock_mutex. // All default action specs for this function mocker. UntypedOnCallSpecs untyped_on_call_specs_; // All expectations for this function mocker. UntypedExpectations untyped_expectations_; }; // class UntypedFunctionMockerBase // Untyped base class for OnCallSpec<F>. class UntypedOnCallSpecBase { public: // The arguments are the location of the ON_CALL() statement. UntypedOnCallSpecBase(const char* a_file, int a_line) : file_(a_file), line_(a_line), last_clause_(kNone) {} // Where in the source file was the default action spec defined? const char* file() const { return file_; } int line() const { return line_; } protected: // Gives each clause in the ON_CALL() statement a name. enum Clause { // Do not change the order of the enum members! The run-time // syntax checking relies on it. kNone, kWith, kWillByDefault }; // Asserts that the ON_CALL() statement has a certain property. void AssertSpecProperty(bool property, const string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the ON_CALL() statement has a certain property. void ExpectSpecProperty(bool property, const string& failure_message) const { Expect(property, file_, line_, failure_message); } const char* file_; int line_; // The last clause in the ON_CALL() statement as seen so far. // Initially kNone and changes as the statement is parsed. Clause last_clause_; }; // class UntypedOnCallSpecBase // This template class implements an ON_CALL spec. template <typename F> class OnCallSpec : public UntypedOnCallSpecBase { public: typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs an OnCallSpec object from the information inside // the parenthesis of an ON_CALL() statement. OnCallSpec(const char* a_file, int a_line, const ArgumentMatcherTuple& matchers) : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), // By default, extra_matcher_ should match anything. However, // we cannot initialize it with _ as that triggers a compiler // bug in Symbian's C++ compiler (cannot decide between two // overloaded constructors of Matcher<const ArgumentTuple&>). extra_matcher_(A<const ArgumentTuple&>()) { } // Implements the .With() clause. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { // Makes sure this is called at most once. ExpectSpecProperty(last_clause_ < kWith, ".With() cannot appear " "more than once in an ON_CALL()."); last_clause_ = kWith; extra_matcher_ = m; return *this; } // Implements the .WillByDefault() clause. OnCallSpec& WillByDefault(const Action<F>& action) { ExpectSpecProperty(last_clause_ < kWillByDefault, ".WillByDefault() must appear " "exactly once in an ON_CALL()."); last_clause_ = kWillByDefault; ExpectSpecProperty(!action.IsDoDefault(), "DoDefault() cannot be used in ON_CALL()."); action_ = action; return *this; } // Returns true iff the given arguments match the matchers. bool Matches(const ArgumentTuple& args) const { return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } // Returns the action specified by the user. const Action<F>& GetAction() const { AssertSpecProperty(last_clause_ == kWillByDefault, ".WillByDefault() must appear exactly " "once in an ON_CALL()."); return action_; } private: // The information in statement // // ON_CALL(mock_object, Method(matchers)) // .With(multi-argument-matcher) // .WillByDefault(action); // // is recorded in the data members like this: // // source file that contains the statement => file_ // line number of the statement => line_ // matchers => matchers_ // multi-argument-matcher => extra_matcher_ // action => action_ ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> action_; }; // class OnCallSpec // Possible reactions on uninteresting calls. enum CallReaction { kAllow, kWarn, kFail, kDefault = kWarn // By default, warn about uninteresting calls. }; } // namespace internal // Utilities for manipulating mock objects. class GTEST_API_ Mock { public: // The following public methods can be called concurrently. // Tells Google Mock to ignore mock_obj when checking for leaked // mock objects. static void AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies and clears all expectations on the given mock object. // If the expectations aren't satisfied, generates one or more // Google Test non-fatal failures and returns false. static bool VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); private: friend class internal::UntypedFunctionMockerBase; // Needed for a function mocker to register itself (so that we know // how to clear a mock object). template <typename F> friend class internal::FunctionMockerBase; template <typename M> friend class NiceMock; template <typename M> friend class NaggyMock; template <typename M> friend class StrictMock; // Tells Google Mock to allow uninteresting calls on the given mock // object. static void AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to warn the user about uninteresting calls on // the given mock object. static void WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to fail uninteresting calls on the given mock // object. static void FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock the given mock object is being destroyed and // its entry in the call-reaction table should be removed. static void UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. static internal::CallReaction GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies that all expectations on the given mock object have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. static bool VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Clears all ON_CALL()s set on the given mock object. static void ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Registers a mock object and a mock method it owns. static void Register( const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. static void RegisterUseByOnCallOrExpectCall( const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has // been unregistered. This is called only in the destructor of // FunctionMockerBase. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); }; // class Mock // An abstract handle of an expectation. Useful in the .After() // clause of EXPECT_CALL() for setting the (partial) order of // expectations. The syntax: // // Expectation e1 = EXPECT_CALL(...)...; // EXPECT_CALL(...).After(e1)...; // // sets two expectations where the latter can only be matched after // the former has been satisfied. // // Notes: // - This class is copyable and has value semantics. // - Constness is shallow: a const Expectation object itself cannot // be modified, but the mutable methods of the ExpectationBase // object it references can be called via expectation_base(). // - The constructors and destructor are defined out-of-line because // the Symbian WINSCW compiler wants to otherwise instantiate them // when it sees this class definition, at which point it doesn't have // ExpectationBase available yet, leading to incorrect destruction // in the linked_ptr (or compilation errors if using a checking // linked_ptr). class GTEST_API_ Expectation { public: // Constructs a null object that doesn't reference any expectation. Expectation(); ~Expectation(); // This single-argument ctor must not be explicit, in order to support the // Expectation e = EXPECT_CALL(...); // syntax. // // A TypedExpectation object stores its pre-requisites as // Expectation objects, and needs to call the non-const Retire() // method on the ExpectationBase objects they reference. Therefore // Expectation must receive a *non-const* reference to the // ExpectationBase object. Expectation(internal::ExpectationBase& exp); // NOLINT // The compiler-generated copy ctor and operator= work exactly as // intended, so we don't need to define our own. // Returns true iff rhs references the same expectation as this object does. bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } private: friend class ExpectationSet; friend class Sequence; friend class ::testing::internal::ExpectationBase; friend class ::testing::internal::UntypedFunctionMockerBase; template <typename F> friend class ::testing::internal::FunctionMockerBase; template <typename F> friend class ::testing::internal::TypedExpectation; // This comparator is needed for putting Expectation objects into a set. class Less { public: bool operator()(const Expectation& lhs, const Expectation& rhs) const { return lhs.expectation_base_.get() < rhs.expectation_base_.get(); } }; typedef ::std::set<Expectation, Less> Set; Expectation( const internal::linked_ptr<internal::ExpectationBase>& expectation_base); // Returns the expectation this object references. const internal::linked_ptr<internal::ExpectationBase>& expectation_base() const { return expectation_base_; } // A linked_ptr that co-owns the expectation this handle references. internal::linked_ptr<internal::ExpectationBase> expectation_base_; }; // A set of expectation handles. Useful in the .After() clause of // EXPECT_CALL() for setting the (partial) order of expectations. The // syntax: // // ExpectationSet es; // es += EXPECT_CALL(...)...; // es += EXPECT_CALL(...)...; // EXPECT_CALL(...).After(es)...; // // sets three expectations where the last one can only be matched // after the first two have both been satisfied. // // This class is copyable and has value semantics. class ExpectationSet { public: // A bidirectional iterator that can read a const element in the set. typedef Expectation::Set::const_iterator const_iterator; // An object stored in the set. This is an alias of Expectation. typedef Expectation::Set::value_type value_type; // Constructs an empty set. ExpectationSet() {} // This single-argument ctor must not be explicit, in order to support the // ExpectationSet es = EXPECT_CALL(...); // syntax. ExpectationSet(internal::ExpectationBase& exp) { // NOLINT *this += Expectation(exp); } // This single-argument ctor implements implicit conversion from // Expectation and thus must not be explicit. This allows either an // Expectation or an ExpectationSet to be used in .After(). ExpectationSet(const Expectation& e) { // NOLINT *this += e; } // The compiler-generator ctor and operator= works exactly as // intended, so we don't need to define our own. // Returns true iff rhs contains the same set of Expectation objects // as this does. bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } // Implements the syntax // expectation_set += EXPECT_CALL(...); ExpectationSet& operator+=(const Expectation& e) { expectations_.insert(e); return *this; } int size() const { return static_cast<int>(expectations_.size()); } const_iterator begin() const { return expectations_.begin(); } const_iterator end() const { return expectations_.end(); } private: Expectation::Set expectations_; }; // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). class GTEST_API_ Sequence { public: // Constructs an empty sequence. Sequence() : last_expectation_(new Expectation) {} // Adds an expectation to this sequence. The caller must ensure // that no other thread is accessing this Sequence object. void AddExpectation(const Expectation& expectation) const; private: // The last expectation in this sequence. We use a linked_ptr here // because Sequence objects are copyable and we want the copies to // be aliases. The linked_ptr allows the copies to co-own and share // the same Expectation object. internal::linked_ptr<Expectation> last_expectation_; }; // class Sequence // An object of this type causes all EXPECT_CALL() statements // encountered in its scope to be put in an anonymous sequence. The // work is done in the constructor and destructor. You should only // create an InSequence object on the stack. // // The sole purpose for this class is to support easy definition of // sequential expectations, e.g. // // { // InSequence dummy; // The name of the object doesn't matter. // // // The following expectations must match in the order they appear. // EXPECT_CALL(a, Bar())...; // EXPECT_CALL(a, Baz())...; // ... // EXPECT_CALL(b, Xyz())...; // } // // You can create InSequence objects in multiple threads, as long as // they are used to affect different mock objects. The idea is that // each thread can create and set up its own mocks as if it's the only // thread. However, for clarity of your tests we recommend you to set // up mocks in the main thread unless you have a good reason not to do // so. class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); private: bool sequence_created_; GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT } GTEST_ATTRIBUTE_UNUSED_; namespace internal { // Points to the implicit sequence introduced by a living InSequence // object (if any) in the current thread or NULL. GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Base class for implementing expectations. // // There are two reasons for having a type-agnostic base class for // Expectation: // // 1. We need to store collections of expectations of different // types (e.g. all pre-requisites of a particular expectation, all // expectations in a sequence). Therefore these expectation objects // must share a common base class. // // 2. We can avoid binary code bloat by moving methods not depending // on the template argument of Expectation to the base class. // // This class is internal and mustn't be used by user code directly. class GTEST_API_ ExpectationBase { public: // source_text is the EXPECT_CALL(...) source that created this Expectation. ExpectationBase(const char* file, int line, const string& source_text); virtual ~ExpectationBase(); // Where in the source file was the expectation spec defined? const char* file() const { return file_; } int line() const { return line_; } const char* source_text() const { return source_text_.c_str(); } // Returns the cardinality specified in the expectation spec. const Cardinality& cardinality() const { return cardinality_; } // Describes the source file location of this expectation. void DescribeLocationTo(::std::ostream* os) const { *os << FormatFileLocation(file(), line()) << " "; } // Describes how many times a function call matching this // expectation has occurred. void DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; protected: friend class ::testing::Expectation; friend class UntypedFunctionMockerBase; enum Clause { // Don't change the order of the enum members! kNone, kWith, kTimes, kInSequence, kAfter, kWillOnce, kWillRepeatedly, kRetiresOnSaturation }; typedef std::vector<const void*> UntypedActions; // Returns an Expectation object that references and co-owns this // expectation. virtual Expectation GetHandle() = 0; // Asserts that the EXPECT_CALL() statement has the given property. void AssertSpecProperty(bool property, const string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the EXPECT_CALL() statement has the given property. void ExpectSpecProperty(bool property, const string& failure_message) const { Expect(property, file_, line_, failure_message); } // Explicitly specifies the cardinality of this expectation. Used // by the subclasses to implement the .Times() clause. void SpecifyCardinality(const Cardinality& cardinality); // Returns true iff the user specified the cardinality explicitly // using a .Times(). bool cardinality_specified() const { return cardinality_specified_; } // Sets the cardinality of this expectation spec. void set_cardinality(const Cardinality& a_cardinality) { cardinality_ = a_cardinality; } // The following group of methods should only be called after the // EXPECT_CALL() statement, and only when g_gmock_mutex is held by // the current thread. // Retires all pre-requisites of this expectation. void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns true iff this expectation is retired. bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } // Retires this expectation. void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } // Returns true iff this expectation is satisfied. bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } // Returns true iff this expectation is saturated. bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } // Returns true iff this expectation is over-saturated. bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } // Returns true iff all pre-requisites of this expectation are satisfied. bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Adds unsatisfied pre-requisites of this expectation to 'result'. void FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns the number this expectation has been invoked. int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } // Increments the number this expectation has been invoked. void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } // Checks the action count (i.e. the number of WillOnce() and // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; template <typename Function> friend class TypedExpectation; // Implements the .Times() clause. void UntypedTimes(const Cardinality& a_cardinality); // This group of fields are part of the spec and won't change after // an EXPECT_CALL() statement finishes. const char* file_; // The file that contains the expectation. int line_; // The line number of the expectation. const string source_text_; // The EXPECT_CALL(...) source text. // True iff the cardinality is specified explicitly. bool cardinality_specified_; Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this // expectation. We use linked_ptr in the set because we want an // Expectation object to be co-owned by its FunctionMocker and its // successors. This allows multiple mock objects to be deleted at // different times. ExpectationSet immediate_prerequisites_; // This group of fields are the current state of the expectation, // and can change as the mock function is called. int call_count_; // How many times this expectation has been invoked. bool retired_; // True iff this expectation has retired. UntypedActions untyped_actions_; bool extra_matcher_specified_; bool repeated_action_specified_; // True if a WillRepeatedly() was specified. bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; // Under mutex_. mutable Mutex mutex_; // Protects action_count_checked_. GTEST_DISALLOW_ASSIGN_(ExpectationBase); }; // class ExpectationBase // Impements an expectation for the given function type. template <typename F> class TypedExpectation : public ExpectationBase { public: typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function<F>::Result Result; TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line, const string& a_source_text, const ArgumentMatcherTuple& m) : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), matchers_(m), // By default, extra_matcher_ should match anything. However, // we cannot initialize it with _ as that triggers a compiler // bug in Symbian's C++ compiler (cannot decide between two // overloaded constructors of Matcher<const ArgumentTuple&>). extra_matcher_(A<const ArgumentTuple&>()), repeated_action_(DoDefault()) {} virtual ~TypedExpectation() { // Check the validity of the action count if it hasn't been done // yet (for example, if the expectation was never used). CheckActionCountIfNotDone(); for (UntypedActions::const_iterator it = untyped_actions_.begin(); it != untyped_actions_.end(); ++it) { delete static_cast<const Action<F>*>(*it); } } // Implements the .With() clause. TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) { if (last_clause_ == kWith) { ExpectSpecProperty(false, ".With() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kWith, ".With() must be the first " "clause in an EXPECT_CALL()."); } last_clause_ = kWith; extra_matcher_ = m; extra_matcher_specified_ = true; return *this; } // Implements the .Times() clause. TypedExpectation& Times(const Cardinality& a_cardinality) { ExpectationBase::UntypedTimes(a_cardinality); return *this; } // Implements the .Times() clause. TypedExpectation& Times(int n) { return Times(Exactly(n)); } // Implements the .InSequence() clause. TypedExpectation& InSequence(const Sequence& s) { ExpectSpecProperty(last_clause_ <= kInSequence, ".InSequence() cannot appear after .After()," " .WillOnce(), .WillRepeatedly(), or " ".RetiresOnSaturation()."); last_clause_ = kInSequence; s.AddExpectation(GetHandle()); return *this; } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { return InSequence(s1).InSequence(s2); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3) { return InSequence(s1, s2).InSequence(s3); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4) { return InSequence(s1, s2, s3).InSequence(s4); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4, const Sequence& s5) { return InSequence(s1, s2, s3, s4).InSequence(s5); } // Implements that .After() clause. TypedExpectation& After(const ExpectationSet& s) { ExpectSpecProperty(last_clause_ <= kAfter, ".After() cannot appear after .WillOnce()," " .WillRepeatedly(), or " ".RetiresOnSaturation()."); last_clause_ = kAfter; for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) { immediate_prerequisites_ += *it; } return *this; } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { return After(s1).After(s2); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3) { return After(s1, s2).After(s3); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, const ExpectationSet& s4) { return After(s1, s2, s3).After(s4); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, const ExpectationSet& s4, const ExpectationSet& s5) { return After(s1, s2, s3, s4).After(s5); } // Implements the .WillOnce() clause. TypedExpectation& WillOnce(const Action<F>& action) { ExpectSpecProperty(last_clause_ <= kWillOnce, ".WillOnce() cannot appear after " ".WillRepeatedly() or .RetiresOnSaturation()."); last_clause_ = kWillOnce; untyped_actions_.push_back(new Action<F>(action)); if (!cardinality_specified()) { set_cardinality(Exactly(static_cast<int>(untyped_actions_.size()))); } return *this; } // Implements the .WillRepeatedly() clause. TypedExpectation& WillRepeatedly(const Action<F>& action) { if (last_clause_ == kWillRepeatedly) { ExpectSpecProperty(false, ".WillRepeatedly() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kWillRepeatedly, ".WillRepeatedly() cannot appear " "after .RetiresOnSaturation()."); } last_clause_ = kWillRepeatedly; repeated_action_specified_ = true; repeated_action_ = action; if (!cardinality_specified()) { set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size()))); } // Now that no more action clauses can be specified, we check // whether their count makes sense. CheckActionCountIfNotDone(); return *this; } // Implements the .RetiresOnSaturation() clause. TypedExpectation& RetiresOnSaturation() { ExpectSpecProperty(last_clause_ < kRetiresOnSaturation, ".RetiresOnSaturation() cannot appear " "more than once."); last_clause_ = kRetiresOnSaturation; retires_on_saturation_ = true; // Now that no more action clauses can be specified, we check // whether their count makes sense. CheckActionCountIfNotDone(); return *this; } // Returns the matchers for the arguments as specified inside the // EXPECT_CALL() macro. const ArgumentMatcherTuple& matchers() const { return matchers_; } // Returns the matcher specified by the .With() clause. const Matcher<const ArgumentTuple&>& extra_matcher() const { return extra_matcher_; } // Returns the action specified by the .WillRepeatedly() clause. const Action<F>& repeated_action() const { return repeated_action_; } // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) { if (extra_matcher_specified_) { *os << " Expected args: "; extra_matcher_.DescribeTo(os); *os << "\n"; } } private: template <typename Function> friend class FunctionMockerBase; // Returns an Expectation object that references and co-owns this // expectation. virtual Expectation GetHandle() { return owner_->GetHandleOf(this); } // The following methods will be called only after the EXPECT_CALL() // statement finishes and when the current thread holds // g_gmock_mutex. // Returns true iff this expectation matches the given arguments. bool Matches(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } // Returns true iff this expectation should handle the given arguments. bool ShouldHandleArguments(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // In case the action count wasn't checked when the expectation // was defined (e.g. if this expectation has no WillRepeatedly() // or RetiresOnSaturation() clause), we check it when the // expectation is used for the first time. CheckActionCountIfNotDone(); return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args); } // Describes the result of matching the arguments against this // expectation to the given ostream. void ExplainMatchResultTo( const ArgumentTuple& args, ::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (is_retired()) { *os << " Expected: the expectation is active\n" << " Actual: it is retired\n"; } else if (!Matches(args)) { if (!TupleMatches(matchers_, args)) { ExplainMatchFailureTupleTo(matchers_, args, os); } StringMatchResultListener listener; if (!extra_matcher_.MatchAndExplain(args, &listener)) { *os << " Expected args: "; extra_matcher_.DescribeTo(os); *os << "\n Actual: don't match"; internal::PrintIfNotEmpty(listener.str(), os); *os << "\n"; } } else if (!AllPrerequisitesAreSatisfied()) { *os << " Expected: all pre-requisites are satisfied\n" << " Actual: the following immediate pre-requisites " << "are not satisfied:\n"; ExpectationSet unsatisfied_prereqs; FindUnsatisfiedPrerequisites(&unsatisfied_prereqs); int i = 0; for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); it != unsatisfied_prereqs.end(); ++it) { it->expectation_base()->DescribeLocationTo(os); *os << "pre-requisite #" << i++ << "\n"; } *os << " (end of pre-requisites)\n"; } else { // This line is here just for completeness' sake. It will never // be executed as currently the ExplainMatchResultTo() function // is called only when the mock function call does NOT match the // expectation. *os << "The call matches the expectation.\n"; } } // Returns the action that should be taken for the current invocation. const Action<F>& GetCurrentAction( const FunctionMockerBase<F>* mocker, const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = call_count(); Assert(count >= 1, __FILE__, __LINE__, "call_count() is <= 0 when GetCurrentAction() is " "called - this should never happen."); const int action_count = static_cast<int>(untyped_actions_.size()); if (action_count > 0 && !repeated_action_specified_ && count > action_count) { // If there is at least one WillOnce() and no WillRepeatedly(), // we warn the user when the WillOnce() clauses ran out. ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Actions ran out in " << source_text() << "...\n" << "Called " << count << " times, but only " << action_count << " WillOnce()" << (action_count == 1 ? " is" : "s are") << " specified - "; mocker->DescribeDefaultActionTo(args, &ss); Log(kWarning, ss.str(), 1); } return count <= action_count ? *static_cast<const Action<F>*>(untyped_actions_[count - 1]) : repeated_action(); } // Given the arguments of a mock function call, if the call will // over-saturate this expectation, returns the default action; // otherwise, returns the next action in this expectation. Also // describes *what* happened to 'what', and explains *why* Google // Mock does it to 'why'. This method is not const as it calls // IncrementCallCount(). A return value of NULL means the default // action. const Action<F>* GetActionForArguments( const FunctionMockerBase<F>* mocker, const ArgumentTuple& args, ::std::ostream* what, ::std::ostream* why) GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (IsSaturated()) { // We have an excessive call. IncrementCallCount(); *what << "Mock function called more times than expected - "; mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); // TODO(wan@google.com): allow the user to control whether // unexpected calls should fail immediately or continue using a // flag --gmock_unexpected_calls_are_fatal. return NULL; } IncrementCallCount(); RetireAllPreRequisites(); if (retires_on_saturation_ && IsSaturated()) { Retire(); } // Must be done after IncrementCount()! *what << "Mock function call matches " << source_text() <<"...\n"; return &(GetCurrentAction(mocker, args)); } // All the fields below won't change once the EXPECT_CALL() // statement finishes. FunctionMockerBase<F>* const owner_; ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> repeated_action_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation); }; // class TypedExpectation // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for // specifying the default behavior of, or expectation on, a mock // function. // Note: class MockSpec really belongs to the ::testing namespace. // However if we define it in ::testing, MSVC will complain when // classes in ::testing::internal declare it as a friend class // template. To workaround this compiler bug, we define MockSpec in // ::testing::internal and import it into ::testing. // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const string& message); template <typename F> class MockSpec { public: typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; typedef typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker) : function_mocker_(function_mocker) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. internal::OnCallSpec<F>& InternalDefaultActionSetAt( const char* file, int line, const char* obj, const char* call) { LogWithLocation(internal::kInfo, file, line, string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); } // Adds a new expectation spec to the function mocker and returns // the newly created spec. internal::TypedExpectation<F>& InternalExpectedAt( const char* file, int line, const char* obj, const char* call) { const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); return function_mocker_->AddNewExpectation( file, line, source_text, matchers_); } private: template <typename Function> friend class internal::FunctionMocker; void SetMatchers(const ArgumentMatcherTuple& matchers) { matchers_ = matchers; } // The function mocker that owns this spec. internal::FunctionMockerBase<F>* const function_mocker_; // The argument matchers specified in the spec. ArgumentMatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(MockSpec); }; // class MockSpec +// Wrapper type for generically holding an ordinary value or lvalue reference. +// If T is not a reference type, it must be copyable or movable. +// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless +// T is a move-only value type (which means that it will always be copyable +// if the current platform does not support move semantics). +// +// The primary template defines handling for values, but function header +// comments describe the contract for the whole template (including +// specializations). +template <typename T> +class ReferenceOrValueWrapper { + public: + // Constructs a wrapper from the given value/reference. + explicit ReferenceOrValueWrapper(T value) + : value_(GTEST_MOVE_(value)) {} + + // Unwraps and returns the underlying value/reference, exactly as + // originally passed. The behavior of calling this more than once on + // the same object is unspecified. + T Unwrap() { + return GTEST_MOVE_(value_); + } + + // Provides nondestructive access to the underlying value/reference. + // Always returns a const reference (more precisely, + // const RemoveReference<T>&). The behavior of calling this after + // calling Unwrap on the same object is unspecified. + const T& Peek() const { + return value_; + } + + private: + T value_; +}; + +// Specialization for lvalue reference types. See primary template +// for documentation. +template <typename T> +class ReferenceOrValueWrapper<T&> { + public: + // Workaround for debatable pass-by-reference lint warning (c-library-team + // policy precludes NOLINT in this context) + typedef T& reference; + explicit ReferenceOrValueWrapper(reference ref) + : value_ptr_(&ref) {} + T& Unwrap() { return *value_ptr_; } + const T& Peek() const { return *value_ptr_; } + + private: + T* value_ptr_; +}; + // MSVC warns about using 'this' in base member initializer list, so // we need to temporarily disable the warning. We have to do it for // the entire class to suppress the warning, even though it's about // the constructor only. #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4355) // Temporarily disables warning 4355. #endif // _MSV_VER // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. // ActionResultHolder<T> holds a value of type T, where T must be a // copyable type or void (T doesn't need to be default-constructable). // It hides the syntactic difference between void and other types, and // is used to unify the code for invoking both void-returning and // non-void-returning mock functions. // Untyped base class for ActionResultHolder<T>. class UntypedActionResultHolderBase { public: virtual ~UntypedActionResultHolderBase() {} // Prints the held value as an action's result to os. virtual void PrintAsActionResult(::std::ostream* os) const = 0; }; // This generic definition is used when T is not void. template <typename T> class ActionResultHolder : public UntypedActionResultHolderBase { public: - explicit ActionResultHolder(T a_value) : value_(a_value) {} - - // The compiler-generated copy constructor and assignment operator - // are exactly what we need, so we don't need to define them. - - // Returns the held value and deletes this object. - T GetValueAndDelete() const { - T retval(value_); - delete this; - return retval; + // Returns the held value. Must not be called more than once. + T Unwrap() { + return result_.Unwrap(); } // Prints the held value as an action's result to os. virtual void PrintAsActionResult(::std::ostream* os) const { *os << "\n Returns: "; // T may be a reference type, so we don't use UniversalPrint(). - UniversalPrinter<T>::Print(value_, os); + UniversalPrinter<T>::Print(result_.Peek(), os); } // Performs the given mock function's default action and returns the // result in a new-ed ActionResultHolder. template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, const typename Function<F>::ArgumentTuple& args, const string& call_description) { - return new ActionResultHolder( - func_mocker->PerformDefaultAction(args, call_description)); + return new ActionResultHolder(Wrapper( + func_mocker->PerformDefaultAction(args, call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template <typename F> static ActionResultHolder* PerformAction(const Action<F>& action, const typename Function<F>::ArgumentTuple& args) { - return new ActionResultHolder(action.Perform(args)); + return new ActionResultHolder(Wrapper(action.Perform(args))); } private: - T value_; + typedef ReferenceOrValueWrapper<T> Wrapper; - // T could be a reference type, so = isn't supported. - GTEST_DISALLOW_ASSIGN_(ActionResultHolder); + explicit ActionResultHolder(Wrapper result) + : result_(GTEST_MOVE_(result)) {} + + Wrapper result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); }; // Specialization for T = void. template <> class ActionResultHolder<void> : public UntypedActionResultHolderBase { public: - void GetValueAndDelete() const { delete this; } + void Unwrap() { } virtual void PrintAsActionResult(::std::ostream* /* os */) const {} - // Performs the given mock function's default action and returns NULL; + // Performs the given mock function's default action and returns ownership + // of an empty ActionResultHolder*. template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, const typename Function<F>::ArgumentTuple& args, const string& call_description) { func_mocker->PerformDefaultAction(args, call_description); - return NULL; + return new ActionResultHolder; } - // Performs the given action and returns NULL. + // Performs the given action and returns ownership of an empty + // ActionResultHolder*. template <typename F> static ActionResultHolder* PerformAction( const Action<F>& action, const typename Function<F>::ArgumentTuple& args) { action.Perform(args); - return NULL; + return new ActionResultHolder; } + + private: + ActionResultHolder() {} + GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); }; // The base of the function mocker class for the given function type. // We put the methods in this class instead of its child to avoid code // bloat. template <typename F> class FunctionMockerBase : public UntypedFunctionMockerBase { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; FunctionMockerBase() : current_spec_(this) {} // The destructor verifies that all expectations on this mock // function have been satisfied. If not, it will report Google Test // non-fatal failures for the violations. virtual ~FunctionMockerBase() GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); VerifyAndClearExpectationsLocked(); Mock::UnregisterLocked(this); ClearDefaultActionsLocked(); } // Returns the ON_CALL spec that matches this mock function with the // given arguments; returns NULL if no matching ON_CALL is found. // L = * const OnCallSpec<F>* FindOnCallSpec( const ArgumentTuple& args) const { for (UntypedOnCallSpecs::const_reverse_iterator it = untyped_on_call_specs_.rbegin(); it != untyped_on_call_specs_.rend(); ++it) { const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); if (spec->Matches(args)) return spec; } return NULL; } // Performs the default action of this mock function on the given // arguments and returns the result. Asserts (or throws if // exceptions are enabled) with a helpful call descrption if there // is no valid return value. This method doesn't depend on the // mutable state of this object, and thus can be called concurrently // without locking. // L = * Result PerformDefaultAction(const ArgumentTuple& args, const string& call_description) const { const OnCallSpec<F>* const spec = this->FindOnCallSpec(args); if (spec != NULL) { return spec->GetAction().Perform(args); } const string message = call_description + "\n The mock function has no default action " "set, and its return type has no default value set."; #if GTEST_HAS_EXCEPTIONS if (!DefaultValue<Result>::Exists()) { throw std::runtime_error(message); } #else Assert(DefaultValue<Result>::Exists(), "", -1, message); #endif return DefaultValue<Result>::Get(); } // Performs the default action with the given arguments and returns // the action's result. The call description string will be used in // the error message to describe the call in the case the default // action fails. The caller is responsible for deleting the result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( const void* untyped_args, // must point to an ArgumentTuple const string& call_description) const { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); return ResultHolder::PerformDefaultAction(this, args, call_description); } // Performs the given action with the given arguments and returns // the action's result. The caller is responsible for deleting the // result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( const void* untyped_action, const void* untyped_args) const { // Make a copy of the action before performing it, in case the // action deletes the mock object (and thus deletes itself). const Action<F> action = *static_cast<const Action<F>*>(untyped_action); const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); return ResultHolder::PerformAction(action, args); } // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): // clears the ON_CALL()s set on this mock function. virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Deleting our default actions may trigger other mock objects to be // deleted, for example if an action contains a reference counted smart // pointer to that mock object, and that is the last reference. So if we // delete our actions within the context of the global mutex we may deadlock // when this method is called again. Instead, make a copy of the set of // actions to delete, clear our set within the mutex, and then delete the // actions outside of the mutex. UntypedOnCallSpecs specs_to_delete; untyped_on_call_specs_.swap(specs_to_delete); g_gmock_mutex.Unlock(); for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin(); it != specs_to_delete.end(); ++it) { delete static_cast<const OnCallSpec<F>*>(*it); } // Lock the mutex again, since the caller expects it to be locked when we // return. g_gmock_mutex.Lock(); } protected: template <typename Function> friend class MockSpec; typedef ActionResultHolder<Result> ResultHolder; // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. Result InvokeWith(const ArgumentTuple& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - return static_cast<const ResultHolder*>( - this->UntypedInvokeWith(&args))->GetValueAndDelete(); + scoped_ptr<ResultHolder> holder( + DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args))); + return holder->Unwrap(); } // Adds and returns a default action spec for this mock function. OnCallSpec<F>& AddNewOnCallSpec( const char* file, int line, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); untyped_on_call_specs_.push_back(on_call_spec); return *on_call_spec; } // Adds and returns an expectation spec for this mock function. TypedExpectation<F>& AddNewExpectation( const char* file, int line, const string& source_text, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); TypedExpectation<F>* const expectation = new TypedExpectation<F>(this, file, line, source_text, m); const linked_ptr<ExpectationBase> untyped_expectation(expectation); untyped_expectations_.push_back(untyped_expectation); // Adds this expectation into the implicit sequence if there is one. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); if (implicit_sequence != NULL) { implicit_sequence->AddExpectation(Expectation(untyped_expectation)); } return *expectation; } // The current spec (either default action spec or expectation spec) // being described on this function mocker. MockSpec<F>& current_spec() { return current_spec_; } private: template <typename Func> friend class TypedExpectation; // Some utilities needed for implementing UntypedInvokeWith(). // Describes what default action will be performed for the given // arguments. // L = * void DescribeDefaultActionTo(const ArgumentTuple& args, ::std::ostream* os) const { const OnCallSpec<F>* const spec = FindOnCallSpec(args); if (spec == NULL) { *os << (internal::type_equals<Result, void>::value ? "returning directly.\n" : "returning default value.\n"); } else { *os << "taking default action specified at:\n" << FormatFileLocation(spec->file(), spec->line()) << "\n"; } } // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. virtual void UntypedDescribeUninterestingCall( const void* untyped_args, ::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); *os << "Uninteresting mock function call - "; DescribeDefaultActionTo(args, os); *os << " Function call: " << Name(); UniversalPrint(args, os); } // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, // untyped_action is set to point to the action that should be // performed (or NULL if the action is "do default"), and // is_excessive is modified to indicate whether the call exceeds the // expected number. // // Critical section: We must find the matching expectation and the // corresponding action that needs to be taken in an ATOMIC // transaction. Otherwise another thread may call this mock // method in the middle and mess up the state. // // However, performing the action has to be left out of the critical // section. The reason is that we have no control on what the // action does (it can invoke an arbitrary user function or even a // mock function) and excessive locking could cause a dead lock. virtual const ExpectationBase* UntypedFindMatchingExpectation( const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); if (exp == NULL) { // A match wasn't found. this->FormatUnexpectedCallMessageLocked(args, what, why); return NULL; } // This line must be done before calling GetActionForArguments(), // which will increment the call count for *exp and thus affect // its saturation status. *is_excessive = exp->IsSaturated(); const Action<F>* action = exp->GetActionForArguments(this, args, what, why); if (action != NULL && action->IsDoDefault()) action = NULL; // Normalize "do default" to NULL. *untyped_action = action; return exp; } // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); UniversalPrint(args, os); } // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. TypedExpectation<F>* FindMatchingExpectationLocked( const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { TypedExpectation<F>* const exp = static_cast<TypedExpectation<F>*>(it->get()); if (exp->ShouldHandleArguments(args)) { return exp; } } return NULL; } // Returns a message that the arguments don't match any expectation. void FormatUnexpectedCallMessageLocked( const ArgumentTuple& args, ::std::ostream* os, ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << "\nUnexpected mock function call - "; DescribeDefaultActionTo(args, os); PrintTriedExpectationsLocked(args, why); } // Prints a list of expectations that have been tried against the // current mock function call. void PrintTriedExpectationsLocked( const ArgumentTuple& args, ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = static_cast<int>(untyped_expectations_.size()); *why << "Google Mock tried the following " << count << " " << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; for (int i = 0; i < count; i++) { TypedExpectation<F>* const expectation = static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); *why << "\n"; expectation->DescribeLocationTo(why); if (count > 1) { *why << "tried expectation #" << i << ": "; } *why << expectation->source_text() << "...\n"; expectation->ExplainMatchResultTo(args, why); expectation->DescribeCallCountTo(why); } } // The current spec (either default action spec or expectation spec) // being described on this function mocker. MockSpec<F> current_spec_; // There is no generally useful and implementable semantics of // copying a mock object, so copying a mock is usually a user error. // Thus we disallow copying function mockers. If the user really // wants to copy a mock object, he should implement his own copy // operation, for example: // // class MockFoo : public Foo { // public: // // Defines a copy constructor explicitly. // MockFoo(const MockFoo& src) {} // ... // }; GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase); }; // class FunctionMockerBase #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif // _MSV_VER // Implements methods of FunctionMockerBase. // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures and // returns false if not. // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const string& msg); } // namespace internal // The style guide prohibits "using" statements in a namespace scope // inside a header file. However, the MockSpec class template is // meant to be defined in the ::testing namespace. The following line // is just a trick for working around a bug in MSVC 8.0, which cannot // handle it if we define MockSpec in ::testing. using internal::MockSpec; // Const(x) is a convenient function for obtaining a const reference // to x. This is useful for setting expectations on an overloaded // const mock method, e.g. // // class MockFoo : public FooInterface { // public: // MOCK_METHOD0(Bar, int()); // MOCK_CONST_METHOD0(Bar, int&()); // }; // // MockFoo foo; // // Expects a call to non-const MockFoo::Bar(). // EXPECT_CALL(foo, Bar()); // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template <typename T> inline const T& Const(const T& x) { return x; } // Constructs an Expectation object that references and co-owns exp. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT : expectation_base_(exp.GetHandle().expectation_base()) {} } // namespace testing // A separate macro is required to avoid compile errors when the name // of the method used in call is a result of macro expansion. // See CompilesWithMethodNameExpandedFromMacro tests in // internal/gmock-spec-builders_test.cc for more details. #define GMOCK_ON_CALL_IMPL_(obj, call) \ ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ #obj, #call) #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/include/gmock/internal/gmock-internal-utils.h b/include/gmock/internal/gmock-internal-utils.h index e12b7d7d..2f530d4e 100644 --- a/include/gmock/internal/gmock-internal-utils.h +++ b/include/gmock/internal/gmock-internal-utils.h @@ -1,498 +1,511 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file defines some utilities useful for implementing Google // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #include <stdio.h> #include <ostream> // NOLINT #include <string> #include "gmock/internal/gmock-generated-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { namespace internal { // Converts an identifier name to a space-separated list of lower-case // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is // treated as one word. For example, both "FooBar123" and // "foo_bar_123" are converted to "foo bar 123". GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name); // PointeeOf<Pointer>::type is the type of a value pointed to by a // Pointer, which can be either a smart pointer or a raw pointer. The // following default implementation is for the case where Pointer is a // smart pointer. template <typename Pointer> struct PointeeOf { // Smart pointer classes define type element_type as the type of // their pointees. typedef typename Pointer::element_type type; }; // This specialization is for the raw pointer case. template <typename T> struct PointeeOf<T*> { typedef T type; }; // NOLINT // GetRawPointer(p) returns the raw pointer underlying p when p is a // smart pointer, or returns p itself when p is already a raw pointer. // The following default implementation is for the smart pointer case. template <typename Pointer> inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { return p.get(); } // This overloaded version is for the raw pointer case. template <typename Element> inline Element* GetRawPointer(Element* p) { return p; } // This comparator allows linked_ptr to be stored in sets. template <typename T> struct LinkedPtrLessThan { bool operator()(const ::testing::internal::linked_ptr<T>& lhs, const ::testing::internal::linked_ptr<T>& rhs) const { return lhs.get() < rhs.get(); } }; // Symbian compilation can be done with wchar_t being either a native // type or a typedef. Using Google Mock with OpenC without wchar_t // should require the definition of _STLP_NO_WCHAR_T. // // MSVC treats wchar_t as a native type usually, but treats it as the // same as unsigned short when the compiler option /Zc:wchar_t- is // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // is a native type. #if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \ (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) // wchar_t is a typedef. #else # define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // signed wchar_t and unsigned wchar_t are NOT in the C++ standard. // Using them is a bad practice and not portable. So DON'T use them. // // Still, Google Mock is designed to work even if the user uses signed // wchar_t or unsigned wchar_t (obviously, assuming the compiler // supports them). // // To gcc, // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int #ifdef __GNUC__ // signed/unsigned wchar_t are valid types. # define GMOCK_HAS_SIGNED_WCHAR_T_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type // is bool, an integer type (excluding bool), a floating-point type, // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf<T>::value is the kind of type T. template <typename T> struct KindOf { enum { value = kOther }; // The default kind. }; // This macro declares that the kind of 'type' is 'kind'. #define GMOCK_DECLARE_KIND_(type, kind) \ template <> struct KindOf<type> { enum { value = kind }; } GMOCK_DECLARE_KIND_(bool, kBool); // All standard integer types. GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DECLARE_KIND_(wchar_t, kInteger); #endif // Non-standard integer types. GMOCK_DECLARE_KIND_(Int64, kInteger); GMOCK_DECLARE_KIND_(UInt64, kInteger); // All standard floating-point types. GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint); GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. #define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) // Evaluates to true iff integer type T is signed. #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0) // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value // is true iff arithmetic type From can be losslessly converted to // arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types, kFromKind is the kind of // From, and kToKind is the kind of To; the value is // implementation-defined when the above pre-condition is violated. template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> struct LosslessArithmeticConvertibleImpl : public false_type {}; // Converting bool to bool is lossless. template <> struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool> : public true_type {}; // NOLINT // Converting bool to any integer type is lossless. template <typename To> struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To> : public true_type {}; // NOLINT // Converting bool to any floating-point type is lossless. template <typename To> struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To> : public true_type {}; // NOLINT // Converting an integer to bool is lossy. template <typename From> struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool> : public false_type {}; // NOLINT // Converting an integer to another non-bool integer is lossless iff // the target type's range encloses the source type's range. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To> : public bool_constant< // When converting from a smaller size to a larger size, we are // fine as long as we are not converting from signed to unsigned. ((sizeof(From) < sizeof(To)) && (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || // When converting between the same size, the signedness must match. ((sizeof(From) == sizeof(To)) && (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT #undef GMOCK_IS_SIGNED_ // Converting an integer to a floating-point type may be lossy, since // the format of a floating-point number is implementation-defined. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To> : public false_type {}; // NOLINT // Converting a floating-point to bool is lossy. template <typename From> struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool> : public false_type {}; // NOLINT // Converting a floating-point to an integer is lossy. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To> : public false_type {}; // NOLINT // Converting a floating-point to another floating-point is lossless // iff the target type is at least as big as the source type. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl< kFloatingPoint, From, kFloatingPoint, To> : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT // LosslessArithmeticConvertible<From, To>::value is true iff arithmetic // type From can be losslessly converted to arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types; the value is // implementation-defined when the above pre-condition is violated. template <typename From, typename To> struct LosslessArithmeticConvertible : public LosslessArithmeticConvertibleImpl< GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} // Reports a failure that occurred at the given source file location. virtual void ReportFailure(FailureType type, const char* file, int line, const string& message) = 0; }; // Returns the failure reporter used by Google Mock. GTEST_API_ FailureReporterInterface* GetFailureReporter(); // Asserts that condition is true; aborts the process with the given // message if condition is false. We cannot use LOG(FATAL) or CHECK() // as Google Mock might be used to mock the log sink itself. We // inline this function to prevent it from showing up in the stack // trace. inline void Assert(bool condition, const char* file, int line, const string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); } } inline void Assert(bool condition, const char* file, int line) { Assert(condition, file, line, "Assertion failed."); } // Verifies that condition is true; generates a non-fatal failure if // condition is false. inline void Expect(bool condition, const char* file, int line, const string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); } } inline void Expect(bool condition, const char* file, int line) { Expect(condition, file, line, "Expectation failed."); } // Severity level of a log. enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. // All logs (informational and warnings) are printed. const char kInfoVerbosity[] = "info"; // Only warnings are printed. const char kWarningVerbosity[] = "warning"; // No logs are printed. const char kErrorVerbosity[] = "error"; // Returns true iff a log with the given severity is visible according // to the --gmock_verbose flag. GTEST_API_ bool LogIsVisible(LogSeverity severity); // Prints the given message to stdout iff 'severity' >= the level // specified by the --gmock_verbose flag. If stack_frames_to_skip >= // 0, also prints the stack trace excluding the top // stack_frames_to_skip frames. In opt mode, any positive // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. GTEST_API_ void Log(LogSeverity severity, const string& message, int stack_frames_to_skip); // TODO(wan@google.com): group all type utilities together. // Type traits. // is_reference<T>::value is non-zero iff T is a reference type. template <typename T> struct is_reference : public false_type {}; template <typename T> struct is_reference<T&> : public true_type {}; // type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type. template <typename T1, typename T2> struct type_equals : public false_type {}; template <typename T> struct type_equals<T, T> : public true_type {}; // remove_reference<T>::type removes the reference from type T, if any. template <typename T> struct remove_reference { typedef T type; }; // NOLINT template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT // DecayArray<T>::type turns an array type U[N] to const U* and preserves // other types. Useful for saving a copy of a function argument. template <typename T> struct DecayArray { typedef T type; }; // NOLINT template <typename T, size_t N> struct DecayArray<T[N]> { typedef const T* type; }; // Sometimes people use arrays whose size is not available at the use site // (e.g. extern const char kNamePrefix[]). This specialization covers that // case. template <typename T> struct DecayArray<T[]> { typedef const T* type; }; -// Invalid<T>() returns an invalid value of type T. This is useful +// Disable MSVC warnings for infinite recursion, since in this case the +// the recursion is unreachable. +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4717) +#endif + +// Invalid<T>() is usable as an expression of type T, but will terminate +// the program with an assertion failure if actually run. This is useful // when a value of type T is needed for compilation, but the statement // will not really be executed (or we don't care if the statement // crashes). template <typename T> inline T Invalid() { - return const_cast<typename remove_reference<T>::type&>( - *static_cast<volatile typename remove_reference<T>::type*>(NULL)); + Assert(false, "", -1, "Internal error: attempt to return invalid value"); + // This statement is unreachable, and would never terminate even if it + // could be reached. It is provided only to placate compiler warnings + // about missing return statements. + return Invalid<T>(); } -template <> -inline void Invalid<void>() {} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif // Given a raw type (i.e. having no top-level reference or const // modifier) RawContainer that's either an STL-style container or a // native array, class StlContainerView<RawContainer> has the // following members: // // - type is a type that provides an STL-style container view to // (i.e. implements the STL container concept for) RawContainer; // - const_reference is a type that provides a reference to a const // RawContainer; // - ConstReference(raw_container) returns a const reference to an STL-style // container view to raw_container, which is a RawContainer. // - Copy(raw_container) returns an STL-style container view of a // copy of raw_container, which is a RawContainer. // // This generic version is used when RawContainer itself is already an // STL-style container. template <class RawContainer> class StlContainerView { public: typedef RawContainer type; typedef const type& const_reference; static const_reference ConstReference(const RawContainer& container) { // Ensures that RawContainer is not a const type. testing::StaticAssertTypeEq<RawContainer, GTEST_REMOVE_CONST_(RawContainer)>(); return container; } static type Copy(const RawContainer& container) { return container; } }; // This specialization is used when RawContainer is a native array type. template <typename Element, size_t N> class StlContainerView<Element[N]> { public: typedef GTEST_REMOVE_CONST_(Element) RawElement; typedef internal::NativeArray<RawElement> type; // NativeArray<T> can represent a native array either by value or by // reference (selected by a constructor argument), so 'const type' // can be used to reference a const native array. We cannot // 'typedef const type& const_reference' here, as that would mean // ConstReference() has to return a reference to a local variable. typedef const type const_reference; static const_reference ConstReference(const Element (&array)[N]) { // Ensures that Element is not a const type. testing::StaticAssertTypeEq<Element, RawElement>(); #if GTEST_OS_SYMBIAN // The Nokia Symbian compiler confuses itself in template instantiation // for this call without the cast to Element*: // function call '[testing::internal::NativeArray<char *>].NativeArray( // {lval} const char *[4], long, testing::internal::RelationToSource)' // does not match // 'testing::internal::NativeArray<char *>::NativeArray( // char *const *, unsigned int, testing::internal::RelationToSource)' // (instantiating: 'testing::internal::ContainsMatcherImpl // <const char * (&)[4]>::Matches(const char * (&)[4]) const') // (instantiating: 'testing::internal::StlContainerView<char *[4]>:: // ConstReference(const char * (&)[4])') // (and though the N parameter type is mismatched in the above explicit // conversion of it doesn't help - only the conversion of the array). return type(const_cast<Element*>(&array[0]), N, kReference); #else return type(array, N, kReference); #endif // GTEST_OS_SYMBIAN } static type Copy(const Element (&array)[N]) { #if GTEST_OS_SYMBIAN return type(const_cast<Element*>(&array[0]), N, kCopy); #else return type(array, N, kCopy); #endif // GTEST_OS_SYMBIAN } }; // This specialization is used when RawContainer is a native array // represented as a (pointer, size) tuple. template <typename ElementPointer, typename Size> class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > { public: typedef GTEST_REMOVE_CONST_( typename internal::PointeeOf<ElementPointer>::type) RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; static const_reference ConstReference( const ::std::tr1::tuple<ElementPointer, Size>& array) { using ::std::tr1::get; return type(get<0>(array), get<1>(array), kReference); } static type Copy(const ::std::tr1::tuple<ElementPointer, Size>& array) { using ::std::tr1::get; return type(get<0>(array), get<1>(array), kCopy); } }; // The following specialization prevents the user from instantiating // StlContainer with a reference type. template <typename T> class StlContainerView<T&>; // A type transform to remove constness from the first part of a pair. // Pairs like that are used as the value_type of associative containers, // and this transform produces a similar but assignable pair. template <typename T> struct RemoveConstFromKey { typedef T type; }; // Partially specialized to remove constness from std::pair<const K, V>. template <typename K, typename V> struct RemoveConstFromKey<std::pair<const K, V> > { typedef std::pair<K, V> type; }; // Mapping from booleans to types. Similar to boost::bool_<kValue> and // std::integral_constant<bool, kValue>. template <bool kValue> struct BooleanConstant {}; } // namespace internal } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ diff --git a/src/gmock-spec-builders.cc b/src/gmock-spec-builders.cc index cefb580f..a74f9e57 100644 --- a/src/gmock-spec-builders.cc +++ b/src/gmock-spec-builders.cc @@ -1,820 +1,820 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements the spec builder syntax (ON_CALL and // EXPECT_CALL). #include "gmock/gmock-spec-builders.h" #include <stdlib.h> #include <iostream> // NOLINT #include <map> #include <set> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC # include <unistd.h> // NOLINT #endif namespace testing { namespace internal { // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const string& message) { ::std::ostringstream s; s << file << ":" << line << ": " << message << ::std::endl; Log(severity, s.str(), 0); } // Constructs an ExpectationBase object. ExpectationBase::ExpectationBase(const char* a_file, int a_line, const string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), cardinality_specified_(false), cardinality_(Exactly(1)), call_count_(0), retired_(false), extra_matcher_specified_(false), repeated_action_specified_(false), retires_on_saturation_(false), last_clause_(kNone), action_count_checked_(false) {} // Destructs an ExpectationBase object. ExpectationBase::~ExpectationBase() {} // Explicitly specifies the cardinality of this expectation. Used by // the subclasses to implement the .Times() clause. void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { cardinality_specified_ = true; cardinality_ = a_cardinality; } // Retires all pre-requisites of this expectation. void ExpectationBase::RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { if (is_retired()) { // We can take this short-cut as we never retire an expectation // until we have retired all its pre-requisites. return; } for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { ExpectationBase* const prerequisite = it->expectation_base().get(); if (!prerequisite->is_retired()) { prerequisite->RetireAllPreRequisites(); prerequisite->Retire(); } } } // Returns true iff all pre-requisites of this expectation have been // satisfied. bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { if (!(it->expectation_base()->IsSatisfied()) || !(it->expectation_base()->AllPrerequisitesAreSatisfied())) return false; } return true; } // Adds unsatisfied pre-requisites of this expectation to 'result'. void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { if (it->expectation_base()->IsSatisfied()) { // If *it is satisfied and has a call count of 0, some of its // pre-requisites may not be satisfied yet. if (it->expectation_base()->call_count_ == 0) { it->expectation_base()->FindUnsatisfiedPrerequisites(result); } } else { // Now that we know *it is unsatisfied, we are not so interested // in whether its pre-requisites are satisfied. Therefore we // don't recursively call FindUnsatisfiedPrerequisites() here. *result += *it; } } } // Describes how many times a function call matching this // expectation has occurred. void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Describes how many times the function is expected to be called. *os << " Expected: to be "; cardinality().DescribeTo(os); *os << "\n Actual: "; Cardinality::DescribeActualCallCountTo(call_count(), os); // Describes the state of the expectation (e.g. is it satisfied? // is it active?). *os << " - " << (IsOverSaturated() ? "over-saturated" : IsSaturated() ? "saturated" : IsSatisfied() ? "satisfied" : "unsatisfied") << " and " << (is_retired() ? "retired" : "active"); } // Checks the action count (i.e. the number of WillOnce() and // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. void ExpectationBase::CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_) { bool should_check = false; { MutexLock l(&mutex_); if (!action_count_checked_) { action_count_checked_ = true; should_check = true; } } if (should_check) { if (!cardinality_specified_) { // The cardinality was inferred - no need to check the action // count against it. return; } // The cardinality was explicitly specified. const int action_count = static_cast<int>(untyped_actions_.size()); const int upper_bound = cardinality().ConservativeUpperBound(); const int lower_bound = cardinality().ConservativeLowerBound(); bool too_many; // True if there are too many actions, or false // if there are too few. if (action_count > upper_bound || (action_count == upper_bound && repeated_action_specified_)) { too_many = true; } else if (0 < action_count && action_count < lower_bound && !repeated_action_specified_) { too_many = false; } else { return; } ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Too " << (too_many ? "many" : "few") << " actions specified in " << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); ss << ", but has " << (too_many ? "" : "only ") << action_count << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } ss << "."; Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace". } } // Implements the .Times() clause. void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { if (last_clause_ == kTimes) { ExpectSpecProperty(false, ".Times() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kTimes, ".Times() cannot appear after " ".InSequence(), .WillOnce(), .WillRepeatedly(), " "or .RetiresOnSaturation()."); } last_clause_ = kTimes; SpecifyCardinality(a_cardinality); } // Points to the implicit sequence introduced by a living InSequence // object (if any) in the current thread or NULL. GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const string& msg) { switch (reaction) { case kAllow: Log(kInfo, msg, 3); break; case kWarn: Log(kWarning, msg + "\nNOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " "See http://code.google.com/p/googlemock/wiki/CookBook#" "Knowing_When_to_Expect for details.", 3); break; default: // FAIL Expect(false, NULL, -1, msg); } } UntypedFunctionMockerBase::UntypedFunctionMockerBase() : mock_obj_(NULL), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} // Sets the mock object this mock method belongs to, and registers // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; } Mock::Register(mock_obj, this); } // Sets the mock object this mock method belongs to, and sets the name // of the mock function. Will be called upon each invocation of this // mock function. void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { // We protect name_ under g_gmock_mutex in case this mock function // is called from two threads concurrently. MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; name_ = name; } // Returns the name of the function being mocked. Must be called // after RegisterOwner() or SetOwnerAndName() has been called. const void* UntypedFunctionMockerBase::MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const void* mock_obj; { // We protect mock_obj_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); Assert(mock_obj_ != NULL, __FILE__, __LINE__, "MockObject() must not be called before RegisterOwner() or " "SetOwnerAndName() has been called."); mock_obj = mock_obj_; } return mock_obj; } // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. const char* UntypedFunctionMockerBase::Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const char* name; { // We protect name_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); Assert(name_ != NULL, __FILE__, __LINE__, "Name() must not be called before SetOwnerAndName() has " "been called."); name = name_; } return name; } // Calculates the result of invoking this mock function with the given // arguments, prints it, and returns it. The caller is responsible // for deleting the result. -const UntypedActionResultHolderBase* +UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { if (untyped_expectations_.size() == 0) { // No expectation is set on this mock method - we have an // uninteresting call. // We must get Google Mock's reaction on uninteresting calls // made on this mock object BEFORE performing the action, // because the action may DELETE the mock object and make the // following expression meaningless. const CallReaction reaction = Mock::GetReactionOnUninterestingCalls(MockObject()); // True iff we need to print this call's arguments and return // value. This definition must be kept in sync with // the behavior of ReportUninterestingCall(). const bool need_to_report_uninteresting_call = // If the user allows this uninteresting call, we print it // only when he wants informational messages. reaction == kAllow ? LogIsVisible(kInfo) : // If the user wants this to be a warning, we print it only // when he wants to see warnings. reaction == kWarn ? LogIsVisible(kWarning) : // Otherwise, the user wants this to be an error, and we // should always print detailed information in the error. true; if (!need_to_report_uninteresting_call) { // Perform the action without printing the call information. return this->UntypedPerformDefaultAction(untyped_args, ""); } // Warns about the uninteresting call. ::std::stringstream ss; this->UntypedDescribeUninterestingCall(untyped_args, &ss); // Calculates the function result. - const UntypedActionResultHolderBase* const result = + UntypedActionResultHolderBase* const result = this->UntypedPerformDefaultAction(untyped_args, ss.str()); // Prints the function result. if (result != NULL) result->PrintAsActionResult(&ss); ReportUninterestingCall(reaction, ss.str()); return result; } bool is_excessive = false; ::std::stringstream ss; ::std::stringstream why; ::std::stringstream loc; const void* untyped_action = NULL; // The UntypedFindMatchingExpectation() function acquires and // releases g_gmock_mutex. const ExpectationBase* const untyped_expectation = this->UntypedFindMatchingExpectation( untyped_args, &untyped_action, &is_excessive, &ss, &why); const bool found = untyped_expectation != NULL; // True iff we need to print the call's arguments and return value. // This definition must be kept in sync with the uses of Expect() // and Log() in this function. const bool need_to_report_call = !found || is_excessive || LogIsVisible(kInfo); if (!need_to_report_call) { // Perform the action without printing the call information. return untyped_action == NULL ? this->UntypedPerformDefaultAction(untyped_args, "") : this->UntypedPerformAction(untyped_action, untyped_args); } ss << " Function call: " << Name(); this->UntypedPrintArgs(untyped_args, &ss); // In case the action deletes a piece of the expectation, we // generate the message beforehand. if (found && !is_excessive) { untyped_expectation->DescribeLocationTo(&loc); } - const UntypedActionResultHolderBase* const result = + UntypedActionResultHolderBase* const result = untyped_action == NULL ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) : this->UntypedPerformAction(untyped_action, untyped_args); if (result != NULL) result->PrintAsActionResult(&ss); ss << "\n" << why.str(); if (!found) { // No expectation matches this call - reports a failure. Expect(false, NULL, -1, ss.str()); } else if (is_excessive) { // We had an upper-bound violation and the failure message is in ss. Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } else { // We had an expected call and the matching expectation is // described in ss. Log(kInfo, loc.str() + ss.str(), 2); } return result; } // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); } } Assert(false, __FILE__, __LINE__, "Cannot find expectation."); return Expectation(); // The above statement is just to make the code compile, and will // never be executed. } // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { // There was an upper-bound violation. Since the error was // already reported when it occurred, there is no need to do // anything here. expectations_met = false; } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; ss << "Actual function call count doesn't match " << untyped_expectation->source_text() << "...\n"; // No need to show the source file location of the expectation // in the description, as the Expect() call that follows already // takes care of it. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } } // Deleting our expectations may trigger other mock objects to be deleted, for // example if an action contains a reference counted smart pointer to that // mock object, and that is the last reference. So if we delete our // expectations within the context of the global mutex we may deadlock when // this method is called again. Instead, make a copy of the set of // expectations to delete, clear our set within the mutex, and then clear the // copied set outside of it. UntypedExpectations expectations_to_delete; untyped_expectations_.swap(expectations_to_delete); g_gmock_mutex.Unlock(); expectations_to_delete.clear(); g_gmock_mutex.Lock(); return expectations_met; } } // namespace internal // Class Mock. namespace { typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; // The current state of a mock object. Such information is needed for // detecting leaked mock objects and explicitly verifying a mock's // expectations. struct MockObjectState { MockObjectState() : first_used_file(NULL), first_used_line(-1), leakable(false) {} // Where in the source file an ON_CALL or EXPECT_CALL is first // invoked on this mock object. const char* first_used_file; int first_used_line; ::std::string first_used_test_case; ::std::string first_used_test; bool leakable; // true iff it's OK to leak the object. FunctionMockers function_mockers; // All registered methods of the object. }; // A global registry holding the state of all mock objects that are // alive. A mock object is added to this registry the first time // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It // is removed from the registry in the mock object's destructor. class MockObjectRegistry { public: // Maps a mock object (identified by its address) to its state. typedef std::map<const void*, MockObjectState> StateMap; // This destructor will be called when a program exits, after all // tests in it have been run. By then, there should be no mock // object alive. Therefore we report any living object as test // failure, unless the user explicitly asked us to ignore it. ~MockObjectRegistry() { // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is // a macro. if (!GMOCK_FLAG(catch_leaked_mocks)) return; int leaked_count = 0; for (StateMap::const_iterator it = states_.begin(); it != states_.end(); ++it) { if (it->second.leakable) // The user said it's fine to leak this object. continue; // TODO(wan@google.com): Print the type of the leaked object. // This can help the user identify the leaked object. std::cout << "\n"; const MockObjectState& state = it->second; std::cout << internal::FormatFileLocation(state.first_used_file, state.first_used_line); std::cout << " ERROR: this mock object"; if (state.first_used_test != "") { std::cout << " (used in test " << state.first_used_test_case << "." << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" << it->first << "."; leaked_count++; } if (leaked_count > 0) { std::cout << "\nERROR: " << leaked_count << " leaked mock " << (leaked_count == 1 ? "object" : "objects") << " found at program exit.\n"; std::cout.flush(); ::std::cerr.flush(); // RUN_ALL_TESTS() has already returned when this destructor is // called. Therefore we cannot use the normal Google Test // failure reporting mechanism. _exit(1); // We cannot call exit() as it is not reentrant and // may already have been called. } } StateMap& states() { return states_; } private: StateMap states_; }; // Protected by g_gmock_mutex. MockObjectRegistry g_mock_object_registry; // Maps a mock object to the reaction Google Mock should have when an // uninteresting method is called. Protected by g_gmock_mutex. std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction; // Sets the reaction Google Mock should have when an uninteresting // method of the given mock object is called. void SetReactionOnUninterestingCalls(const void* mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction[mock_obj] = reaction; } } // namespace // Tells Google Mock to allow uninteresting calls on the given mock // object. void Mock::AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } // Tells Google Mock to warn the user about uninteresting calls on the // given mock object. void Mock::WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } // Tells Google Mock to fail uninteresting calls on the given mock // object. void Mock::FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } // Tells Google Mock the given mock object is being destroyed and its // entry in the call-reaction table should be removed. void Mock::UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction.erase(mock_obj); } // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. internal::CallReaction Mock::GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? internal::kDefault : g_uninteresting_call_reaction[mock_obj]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock // objects. void Mock::AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].leakable = true; } // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. bool Mock::VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return VerifyAndClearExpectationsLocked(mock_obj); } // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); ClearDefaultActionsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj); } // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { // No EXPECT_CALL() was set on the given mock object. return true; } // Verifies and clears the expectations on each mock method in the // given mock object. bool expectations_met = true; FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { if (!(*it)->VerifyAndClearExpectationsLocked()) { expectations_met = false; } } // We don't clear the content of mockers, as they may still be // needed by ClearDefaultActionsLocked(). return expectations_met; } // Registers a mock object and a mock method it owns. void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); } // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; if (state.first_used_file == NULL) { state.first_used_file = file; state.first_used_line = line; const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != NULL) { // TODO(wan@google.com): record the test case name when the // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or // TearDownTestCase(). state.first_used_test_case = test_info->test_case_name(); state.first_used_test = test_info->name(); } } } // Unregisters a mock method; removes the owning mock object from the // registry when the last mock method associated with it has been // unregistered. This is called only in the destructor of // FunctionMockerBase. void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); for (MockObjectRegistry::StateMap::iterator it = g_mock_object_registry.states().begin(); it != g_mock_object_registry.states().end(); ++it) { FunctionMockers& mockers = it->second.function_mockers; if (mockers.erase(mocker) > 0) { // mocker was in mockers and has been just removed. if (mockers.empty()) { g_mock_object_registry.states().erase(it); } return; } } } // Clears all ON_CALL()s set on the given mock object. void Mock::ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { // No ON_CALL() was set on the given mock object. return; } // Clears the default actions for each mock method in the given mock // object. FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { (*it)->ClearDefaultActionsLocked(); } // We don't clear the content of mockers, as they may still be // needed by VerifyAndClearExpectationsLocked(). } Expectation::Expectation() {} Expectation::Expectation( const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base) : expectation_base_(an_expectation_base) {} Expectation::~Expectation() {} // Adds an expectation to a sequence. void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != NULL) { expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } *last_expectation_ = expectation; } } // Creates the implicit sequence if there isn't one. InSequence::InSequence() { if (internal::g_gmock_implicit_sequence.get() == NULL) { internal::g_gmock_implicit_sequence.set(new Sequence); sequence_created_ = true; } else { sequence_created_ = false; } } // Deletes the implicit sequence if it was created by the constructor // of this object. InSequence::~InSequence() { if (sequence_created_) { delete internal::g_gmock_implicit_sequence.get(); internal::g_gmock_implicit_sequence.set(NULL); } } } // namespace testing diff --git a/test/gmock-actions_test.cc b/test/gmock-actions_test.cc index 8cd77e20..115a9020 100644 --- a/test/gmock-actions_test.cc +++ b/test/gmock-actions_test.cc @@ -1,1256 +1,1315 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. #include "gmock/gmock-actions.h" #include <algorithm> #include <iterator> +#include <memory> #include <string> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" namespace { using ::std::tr1::get; using ::std::tr1::make_tuple; using ::std::tr1::tuple; using ::std::tr1::tuple_element; using testing::internal::BuiltInDefaultValue; using testing::internal::Int64; using testing::internal::UInt64; // This list should be kept sorted. using testing::_; using testing::Action; using testing::ActionInterface; using testing::Assign; using testing::ByRef; using testing::DefaultValue; using testing::DoDefault; using testing::IgnoreResult; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::MakePolymorphicAction; using testing::Ne; using testing::PolymorphicAction; using testing::Return; using testing::ReturnNull; using testing::ReturnRef; using testing::ReturnRefOfCopy; using testing::SetArgPointee; using testing::SetArgumentPointee; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; #endif #if GTEST_HAS_PROTOBUF_ using testing::internal::TestMessage; #endif // GTEST_HAS_PROTOBUF_ // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL); EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL); } // Tests that BuiltInDefaultValue<T*>::Exists() return true. TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists()); } // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a // built-in numeric type. TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<char>::Get()); #if GMOCK_HAS_SIGNED_WCHAR_T_ EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); } // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a // built-in numeric type. TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<char>::Exists()); #if GMOCK_HAS_SIGNED_WCHAR_T_ EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); } // Tests that BuiltInDefaultValue<bool>::Get() returns false. TEST(BuiltInDefaultValueTest, IsFalseForBool) { EXPECT_FALSE(BuiltInDefaultValue<bool>::Get()); } // Tests that BuiltInDefaultValue<bool>::Exists() returns true. TEST(BuiltInDefaultValueTest, BoolExists) { EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists()); } // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a // string type. TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { #if GTEST_HAS_GLOBAL_STRING EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get()); #endif // GTEST_HAS_GLOBAL_STRING EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get()); } // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a // string type. TEST(BuiltInDefaultValueTest, ExistsForString) { #if GTEST_HAS_GLOBAL_STRING EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists()); #endif // GTEST_HAS_GLOBAL_STRING EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists()); } // Tests that BuiltInDefaultValue<const T>::Get() returns the same // value as BuiltInDefaultValue<T>::Get() does. TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } // Tests that BuiltInDefaultValue<T>::Get() aborts the program with // the correct error message when T is a user-defined type. struct UserType { UserType() : value(0) {} int value; }; TEST(BuiltInDefaultValueTest, UserTypeHasNoDefault) { EXPECT_FALSE(BuiltInDefaultValue<UserType>::Exists()); } // Tests that BuiltInDefaultValue<T&>::Get() aborts the program. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForUserTypes) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<UserType>::Get(); }, ""); } // Tests that DefaultValue<T>::IsSet() is false initially. TEST(DefaultValueTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<const UserType>::IsSet()); } // Tests that DefaultValue<T> can be set and then unset. TEST(DefaultValueTest, CanBeSetAndUnset) { EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const UserType>::Exists()); DefaultValue<int>::Set(1); DefaultValue<const UserType>::Set(UserType()); EXPECT_EQ(1, DefaultValue<int>::Get()); EXPECT_EQ(0, DefaultValue<const UserType>::Get().value); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_TRUE(DefaultValue<const UserType>::Exists()); DefaultValue<int>::Clear(); DefaultValue<const UserType>::Clear(); EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<const UserType>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const UserType>::Exists()); } // Tests that DefaultValue<T>::Get() returns the // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is // false. TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<UserType>::IsSet()); EXPECT_FALSE(DefaultValue<UserType>::Exists()); EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<UserType>::Get(); }, ""); } +#if GTEST_LANG_CXX11 +TEST(DefaultValueDeathTest, GetWorksForMoveOnlyIfSet) { + EXPECT_FALSE(DefaultValue<std::unique_ptr<int>>::Exists()); + EXPECT_DEATH_IF_SUPPORTED({ + DefaultValue<std::unique_ptr<int>>::Get(); + }, ""); + DefaultValue<std::unique_ptr<int>>::SetFactory([] { + return std::unique_ptr<int>(new int(42)); + }); + EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); + std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); + EXPECT_EQ(42, *i); +} +#endif // GTEST_LANG_CXX11 + // Tests that DefaultValue<void>::Get() returns void. TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } // Tests using DefaultValue with a reference type. // Tests that DefaultValue<T&>::IsSet() is false initially. TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<UserType&>::IsSet()); } // Tests that DefaultValue<T&>::Exists is false initiallly. TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { EXPECT_FALSE(DefaultValue<int&>::Exists()); EXPECT_FALSE(DefaultValue<UserType&>::Exists()); } // Tests that DefaultValue<T&> can be set and then unset. TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) { int n = 1; DefaultValue<const int&>::Set(n); UserType u; DefaultValue<UserType&>::Set(u); EXPECT_TRUE(DefaultValue<const int&>::Exists()); EXPECT_TRUE(DefaultValue<UserType&>::Exists()); EXPECT_EQ(&n, &(DefaultValue<const int&>::Get())); EXPECT_EQ(&u, &(DefaultValue<UserType&>::Get())); DefaultValue<const int&>::Clear(); DefaultValue<UserType&>::Clear(); EXPECT_FALSE(DefaultValue<const int&>::Exists()); EXPECT_FALSE(DefaultValue<UserType&>::Exists()); EXPECT_FALSE(DefaultValue<const int&>::IsSet()); EXPECT_FALSE(DefaultValue<UserType&>::IsSet()); } // Tests that DefaultValue<T&>::Get() returns the // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is // false. TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<UserType&>::IsSet()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<UserType>::Get(); }, ""); } // Tests that ActionInterface can be implemented by defining the // Perform method. typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: virtual int Perform(const tuple<bool, int>& args) { return get<0>(args) ? get<1>(args) : 0; } }; TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) { MyActionImpl my_action_impl; (void)my_action_impl; } TEST(ActionInterfaceTest, MakeAction) { Action<MyGlobalFunction> action = MakeAction(new MyActionImpl); // When exercising the Perform() method of Action<F>, we must pass // it a tuple whose size and type are compatible with F's argument // types. For example, if F is int(), then Perform() takes a // 0-tuple; if F is void(bool, int), then Perform() takes a // tuple<bool, int>, and so on. EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); } // Tests that Action<F> can be contructed from a pointer to // ActionInterface<F>. TEST(ActionTest, CanBeConstructedFromActionInterface) { Action<MyGlobalFunction> action(new MyActionImpl); } // Tests that Action<F> delegates actual work to ActionInterface<F>. TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); EXPECT_EQ(0, action.Perform(make_tuple(false, 1))); } // Tests that Action<F> can be copied. TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a1(new MyActionImpl); Action<MyGlobalFunction> a2(a1); // Tests the copy constructor. // a1 should continue to work after being copied from. EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); // a2 should work like the action it was copied from. EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); a2 = a1; // Tests the assignment operator. // a1 should continue to work after being copied from. EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); // a2 should work like the action it was copied from. EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); } // Tests that an Action<From> object can be converted to a // compatible Action<To> object. class IsNotZero : public ActionInterface<bool(int)> { // NOLINT public: virtual bool Perform(const tuple<int>& arg) { return get<0>(arg) != 0; } }; #if !GTEST_OS_SYMBIAN // Compiling this test on Nokia's Symbian compiler fails with: // 'Result' is not a member of class 'testing::internal::Function<int>' // (point of instantiation: '@unnamed@gmock_actions_test_cc@:: // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()') // with no obvious fix. TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); // NOLINT const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT EXPECT_EQ(1, a2.Perform(make_tuple('a'))); EXPECT_EQ(0, a2.Perform(make_tuple('\0'))); } #endif // !GTEST_OS_SYMBIAN // The following two classes are for testing MakePolymorphicAction(). // Implements a polymorphic action that returns the second of the // arguments it receives. class ReturnSecondArgumentAction { public: // We want to verify that MakePolymorphicAction() can work with a // polymorphic action whose Perform() method template is either // const or not. This lets us verify the non-const case. template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) { return get<1>(args); } }; // Implements a polymorphic action that can be used in a nullary // function to return 0. class ReturnZeroFromNullaryFunctionAction { public: // For testing that MakePolymorphicAction() works when the // implementation class' Perform() method template takes only one // template parameter. // // We want to verify that MakePolymorphicAction() can work with a // polymorphic action whose Perform() method template is either // const or not. This lets us verify the const case. template <typename Result> Result Perform(const tuple<>&) const { return 0; } }; // These functions verify that MakePolymorphicAction() returns a // PolymorphicAction<T> where T is the argument's type. PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } PolymorphicAction<ReturnZeroFromNullaryFunctionAction> ReturnZeroFromNullaryFunction() { return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction()); } // Tests that MakePolymorphicAction() turns a polymorphic action // implementation class into a polymorphic action. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0))); } // Tests that MakePolymorphicAction() works when the implementation // class' Perform() method template has only one template parameter. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); EXPECT_EQ(0, a1.Perform(make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); EXPECT_TRUE(a2.Perform(make_tuple()) == NULL); } // Tests that Return() works as an action for void-returning // functions. TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); // NOLINT return ret.Perform(make_tuple(1)); } // Tests that Return(v) returns v. TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); // NOLINT EXPECT_EQ(1, ret.Perform(make_tuple())); ret = Return(-5); EXPECT_EQ(-5, ret.Perform(make_tuple())); } // Tests that Return("string literal") works. TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); EXPECT_STREQ("Hello", a1.Perform(make_tuple())); Action<std::string()> a2 = Return("world"); EXPECT_EQ("world", a2.Perform(make_tuple())); } // Tests that Return(v) is covaraint. struct Base { bool operator==(const Base&) { return true; } }; struct Derived : public Base { bool operator==(const Derived&) { return true; } }; TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); EXPECT_EQ(&base, ret.Perform(make_tuple())); ret = Return(&derived); EXPECT_EQ(&derived, ret.Perform(make_tuple())); } // Tests that the type of the value passed into Return is converted into T // when the action is cast to Action<T(...)> rather than when the action is // performed. See comments on testing::internal::ReturnAction in // gmock-actions.h for more information. class FromType { public: explicit FromType(bool* is_converted) : converted_(is_converted) {} bool* converted() const { return converted_; } private: bool* const converted_; GTEST_DISALLOW_ASSIGN_(FromType); }; class ToType { public: // Must allow implicit conversion due to use in ImplicitCast_<T>. ToType(const FromType& x) { *x.converted() = true; } // NOLINT }; TEST(ReturnTest, ConvertsArgumentWhenConverted) { bool converted = false; FromType x(&converted); Action<ToType()> action(Return(x)); EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; action.Perform(tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } class DestinationType {}; class SourceType { public: // Note: a non-const typecast operator. operator DestinationType() { return DestinationType(); } }; TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) { SourceType s; Action<DestinationType()> action(Return(s)); } // Tests that ReturnNull() returns NULL in a pointer-returning function. TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(make_tuple()) == NULL); const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL); } // Tests that ReturnRef(v) works for reference types. TEST(ReturnRefTest, WorksForReference) { const int n = 0; const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT EXPECT_EQ(&n, &ret.Perform(make_tuple(true))); } // Tests that ReturnRef(v) is covariant. TEST(ReturnRefTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRef(base); EXPECT_EQ(&base, &a.Perform(make_tuple())); a = ReturnRef(derived); EXPECT_EQ(&derived, &a.Perform(make_tuple())); } // Tests that ReturnRefOfCopy(v) works for reference types. TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; const Action<const int&()> ret = ReturnRefOfCopy(n); EXPECT_NE(&n, &ret.Perform(make_tuple())); EXPECT_EQ(42, ret.Perform(make_tuple())); n = 43; EXPECT_NE(&n, &ret.Perform(make_tuple())); EXPECT_EQ(42, ret.Perform(make_tuple())); } // Tests that ReturnRefOfCopy(v) is covariant. TEST(ReturnRefOfCopyTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRefOfCopy(base); EXPECT_NE(&base, &a.Perform(make_tuple())); a = ReturnRefOfCopy(derived); EXPECT_NE(&derived, &a.Perform(make_tuple())); } // Tests that DoDefault() does the default action for the mock method. class MyClass {}; class MockClass { public: MockClass() {} MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT MOCK_METHOD0(Foo, MyClass()); +#if GTEST_LANG_CXX11 + MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); + MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); +#endif private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass); }; // Tests that DoDefault() returns the built-in default value for the // return type by default. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(0, mock.IntFunc(true)); } // Tests that DoDefault() throws (when exceptions are enabled) or aborts // the process when there is no built-in default value for the return type. TEST(DoDefaultDeathTest, DiesForUnknowType) { MockClass mock; EXPECT_CALL(mock, Foo()) .WillRepeatedly(DoDefault()); #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(mock.Foo()); #else EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); #endif } // Tests that using DoDefault() inside a composite action leads to a // run-time error. void VoidFunc(bool /* flag */) {} TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); // Ideally we should verify the error message as well. Sadly, // EXPECT_DEATH() can only capture stderr, while Google Mock's // errors are printed on stdout. Therefore we have to settle for // not verifying the message. EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); } // Tests that DoDefault() returns the default value set by // DefaultValue<T>::Set() when it's not overriden by an ON_CALL(). TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { DefaultValue<int>::Set(1); MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(1, mock.IntFunc(false)); DefaultValue<int>::Clear(); } // Tests that DoDefault() does the action specified by ON_CALL(). TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { MockClass mock; ON_CALL(mock, IntFunc(_)) .WillByDefault(Return(2)); EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(2, mock.IntFunc(false)); } // Tests that using DoDefault() in ON_CALL() leads to a run-time failure. TEST(DoDefaultTest, CannotBeUsedInOnCall) { MockClass mock; EXPECT_NONFATAL_FAILURE({ // NOLINT ON_CALL(mock, IntFunc(_)) .WillByDefault(DoDefault()); }, "DoDefault() cannot be used in ON_CALL()"); } // Tests that SetArgPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgPointee<2>('a'); n = 0; ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // Tests that SetArgPointee<N>() accepts a string literal. // GCC prior to v4.0 and the Symbian compiler do not support this. TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action<MyFunction> a = SetArgPointee<0>("hi"); std::string str; const char* ptr = NULL; a.Perform(make_tuple(&str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == NULL); a = SetArgPointee<1>("world"); str = ""; a.Perform(make_tuple(&str, &ptr)); EXPECT_EQ("", str); EXPECT_STREQ("world", ptr); } TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyFunction(const wchar_t**); Action<MyFunction> a = SetArgPointee<0>(L"world"); const wchar_t* ptr = NULL; a.Perform(make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); # if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); std::wstring str = L""; a2.Perform(make_tuple(&str)); EXPECT_EQ(L"world", str); # endif } #endif // Tests that SetArgPointee<N>() accepts a char pointer. TEST(SetArgPointeeTest, AcceptsCharPointer) { typedef void MyFunction(bool, std::string*, const char**); const char* const hi = "hi"; Action<MyFunction> a = SetArgPointee<1>(hi); std::string str; const char* ptr = NULL; a.Perform(make_tuple(true, &str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == NULL); char world_array[] = "world"; char* const world = world_array; a = SetArgPointee<2>(world); str = ""; a.Perform(make_tuple(true, &str, &ptr)); EXPECT_EQ("", str); EXPECT_EQ(world, ptr); } TEST(SetArgPointeeTest, AcceptsWideCharPointer) { typedef void MyFunction(bool, const wchar_t**); const wchar_t* const hi = L"hi"; Action<MyFunction> a = SetArgPointee<1>(hi); const wchar_t* ptr = NULL; a.Perform(make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); # if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(bool, std::wstring*); wchar_t world_array[] = L"world"; wchar_t* const world = world_array; Action<MyStringFunction> a2 = SetArgPointee<1>(world); std::wstring str; a2.Perform(make_tuple(true, &str)); EXPECT_EQ(world_array, str); # endif } #if GTEST_HAS_PROTOBUF_ // Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, &dest)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgPointee<N>(proto_buffer) sets the // ::ProtocolMessage variable pointed to by the N-th (0-based) // argument to proto_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; ::ProtocolMessage* const dest_base = &dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, dest_base)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgPointee<N>(proto2_buffer) sets the v2 // protobuf variable pointed to by the N-th (0-based) argument to // proto2_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); a.Perform(make_tuple(true, &dest)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } // Tests that SetArgPointee<N>(proto2_buffer) sets the // proto2::Message variable pointed to by the N-th (0-based) argument // to proto2_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); ::proto2::Message* const dest_base = &dest; a.Perform(make_tuple(true, dest_base)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } #endif // GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgumentPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgumentPointee<2>('a'); n = 0; ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } #if GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, &dest)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgumentPointee<N>(proto_buffer) sets the // ::ProtocolMessage variable pointed to by the N-th (0-based) // argument to proto_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; ::ProtocolMessage* const dest_base = &dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, dest_base)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2 // protobuf variable pointed to by the N-th (0-based) argument to // proto2_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); a.Perform(make_tuple(true, &dest)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } // Tests that SetArgumentPointee<N>(proto2_buffer) sets the // proto2::Message variable pointed to by the N-th (0-based) argument // to proto2_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); ::proto2::Message* const dest_base = &dest; a.Perform(make_tuple(true, dest_base)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } #endif // GTEST_HAS_PROTOBUF_ // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } class NullaryFunctor { public: int operator()() { return 2; } }; bool g_done = false; void VoidNullary() { g_done = true; } class VoidNullaryFunctor { public: void operator()() { g_done = true; } }; class Foo { public: Foo() : value_(123) {} int Nullary() const { return value_; } private: int value_; }; // Tests InvokeWithoutArgs(function). TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT EXPECT_EQ(1, a.Perform(make_tuple(2))); // As an action that takes two arguments. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5))); // As an action that returns void. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT g_done = false; a3.Perform(make_tuple(1)); EXPECT_TRUE(g_done); } // Tests InvokeWithoutArgs(functor). TEST(InvokeWithoutArgsTest, Functor) { // As an action that takes no argument. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT EXPECT_EQ(2, a.Perform(make_tuple())); // As an action that takes three arguments. Action<int(int, double, char)> a2 = // NOLINT InvokeWithoutArgs(NullaryFunctor()); EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a'))); // As an action that returns void. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); g_done = false; a3.Perform(make_tuple()); EXPECT_TRUE(g_done); } // Tests InvokeWithoutArgs(obj_ptr, method). TEST(InvokeWithoutArgsTest, Method) { Foo foo; Action<int(bool, char)> a = // NOLINT InvokeWithoutArgs(&foo, &Foo::Nullary); EXPECT_EQ(123, a.Perform(make_tuple(true, 'a'))); } // Tests using IgnoreResult() on a polymorphic action. TEST(IgnoreResultTest, PolymorphicAction) { Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT a.Perform(make_tuple(1)); } // Tests using IgnoreResult() on a monomorphic action. int ReturnOne() { g_done = true; return 1; } TEST(IgnoreResultTest, MonomorphicAction) { g_done = false; Action<void()> a = IgnoreResult(Invoke(ReturnOne)); a.Perform(make_tuple()); EXPECT_TRUE(g_done); } // Tests using IgnoreResult() on an action that returns a class type. MyClass ReturnMyClass(double /* x */) { g_done = true; return MyClass(); } TEST(IgnoreResultTest, ActionReturningClass) { g_done = false; Action<void(int)> a = IgnoreResult(Invoke(ReturnMyClass)); // NOLINT a.Perform(make_tuple(2)); EXPECT_TRUE(g_done); } TEST(AssignTest, Int) { int x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(make_tuple(0)); EXPECT_EQ(5, x); } TEST(AssignTest, String) { ::std::string x; Action<void(void)> a = Assign(&x, "Hello, world"); a.Perform(make_tuple()); EXPECT_EQ("Hello, world", x); } TEST(AssignTest, CompatibleTypes) { double x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(make_tuple(0)); EXPECT_DOUBLE_EQ(5, x); } #if !GTEST_OS_WINDOWS_MOBILE class SetErrnoAndReturnTest : public testing::Test { protected: virtual void SetUp() { errno = 0; } virtual void TearDown() { errno = 0; } }; TEST_F(SetErrnoAndReturnTest, Int) { Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); EXPECT_EQ(-5, a.Perform(make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, Ptr) { int x; Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); EXPECT_EQ(&x, a.Perform(make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { Action<double()> a = SetErrnoAndReturn(EINVAL, 5); EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple())); EXPECT_EQ(EINVAL, errno); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests ByRef(). // Tests that ReferenceWrapper<T> is copyable. TEST(ByRefTest, IsCopyable) { const std::string s1 = "Hi"; const std::string s2 = "Hello"; ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper = ByRef(s1); const std::string& r1 = ref_wrapper; EXPECT_EQ(&s1, &r1); // Assigns a new value to ref_wrapper. ref_wrapper = ByRef(s2); const std::string& r2 = ref_wrapper; EXPECT_EQ(&s2, &r2); ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 = ByRef(s1); // Copies ref_wrapper1 to ref_wrapper. ref_wrapper = ref_wrapper1; const std::string& r3 = ref_wrapper; EXPECT_EQ(&s1, &r3); } // Tests using ByRef() on a const value. TEST(ByRefTest, ConstValue) { const int n = 0; // int& ref = ByRef(n); // This shouldn't compile - we have a // negative compilation test to catch it. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } // Tests using ByRef() on a non-const value. TEST(ByRefTest, NonConstValue) { int n = 0; // ByRef(n) can be used as either an int&, int& ref = ByRef(n); EXPECT_EQ(&n, &ref); // or a const int&. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } // Tests explicitly specifying the type when using ByRef(). TEST(ByRefTest, ExplicitType) { int n = 0; const int& r1 = ByRef<const int>(n); EXPECT_EQ(&n, &r1); // ByRef<char>(n); // This shouldn't compile - we have a negative // compilation test to catch it. Derived d; Derived& r2 = ByRef<Derived>(d); EXPECT_EQ(&d, &r2); const Derived& r3 = ByRef<const Derived>(d); EXPECT_EQ(&d, &r3); Base& r4 = ByRef<Base>(d); EXPECT_EQ(&d, &r4); const Base& r5 = ByRef<const Base>(d); EXPECT_EQ(&d, &r5); // The following shouldn't compile - we have a negative compilation // test for it. // // Base b; // ByRef<Derived>(b); } // Tests that Google Mock prints expression ByRef(x) as a reference to x. TEST(ByRefTest, PrintsCorrectly) { int n = 42; ::std::stringstream expected, actual; testing::internal::UniversalPrinter<const int&>::Print(n, &expected); testing::internal::UniversalPrint(ByRef(n), &actual); EXPECT_EQ(expected.str(), actual.str()); } +#if GTEST_LANG_CXX11 + +std::unique_ptr<int> UniquePtrSource() { + return std::unique_ptr<int>(new int(19)); +} + +std::vector<std::unique_ptr<int>> VectorUniquePtrSource() { + std::vector<std::unique_ptr<int>> out; + out.emplace_back(new int(7)); + return out; +} + +TEST(MockMethodTest, CanReturnMoveOnlyValue) { + MockClass mock; + + // Check default value + DefaultValue<std::unique_ptr<int>>::SetFactory([] { + return std::unique_ptr<int>(new int(42)); + }); + EXPECT_EQ(42, *mock.MakeUnique()); + + EXPECT_CALL(mock, MakeUnique()) + .WillRepeatedly(Invoke(UniquePtrSource)); + EXPECT_CALL(mock, MakeVectorUnique()) + .WillRepeatedly(Invoke(VectorUniquePtrSource)); + std::unique_ptr<int> result1 = mock.MakeUnique(); + EXPECT_EQ(19, *result1); + std::unique_ptr<int> result2 = mock.MakeUnique(); + EXPECT_EQ(19, *result2); + EXPECT_NE(result1, result2); + + std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); + EXPECT_EQ(1, vresult.size()); + EXPECT_NE(nullptr, vresult[0]); + EXPECT_EQ(7, *vresult[0]); +} + +#endif // GTEST_LANG_CXX11 + } // Unnamed namespace