diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index c0df5ccb..e58adfcb 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -1,1918 +1,1918 @@ // 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. // 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. // GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #include #include #include #include #include #include #include #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" #if GTEST_HAS_EXCEPTIONS # include // NOLINT #endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) 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 class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. template class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; // Base class for function mockers. template 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. 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( void* untyped_args, const std::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, 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. // FIXME: 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. UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector UntypedOnCallSpecs; using UntypedExpectations = std::vector>; // 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. // // It's undefined behavior to interleave expectations (EXPECT_CALLs // or ON_CALLs) and mock function calls. Also, the order of // expectations is important. Therefore it's a logic race condition // to read/write untyped_expectations_ concurrently. In order for // tools like tsan to catch concurrent read/write accesses to // untyped_expectations, we deliberately leave accesses to it // unprotected. UntypedExpectations untyped_expectations_; }; // class UntypedFunctionMockerBase // Untyped base class for OnCallSpec. 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 std::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 std::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 class OnCallSpec : public UntypedOnCallSpecBase { public: typedef typename Function::ArgumentTuple ArgumentTuple; typedef typename Function::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). extra_matcher_(A()) { } // Implements the .With() clause. OnCallSpec& With(const Matcher& 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& 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& 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 extra_matcher_; Action action_; }; // class OnCallSpec // Possible reactions on uninteresting calls. enum CallReaction { kAllow, kWarn, kFail, }; } // 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); // Returns whether the mock was created as a naggy mock (default) static bool IsNaggy(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns whether the mock was created as a nice mock static bool IsNice(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns whether the mock was created as a strict mock static bool IsStrict(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 friend class internal::FunctionMockerBase; template friend class NiceMock; template friend class NaggyMock; template 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(). 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 friend class ::testing::internal::FunctionMockerBase; template 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 Set; Expectation( const std::shared_ptr& expectation_base); // Returns the expectation this object references. const std::shared_ptr& expectation_base() const { return expectation_base_; } // A shared_ptr that co-owns the expectation this handle references. std::shared_ptr 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(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. std::shared_ptr 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 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 std::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 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 std::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 std::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 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 std::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 std::shared_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 class TypedExpectation : public ExpectationBase { public: typedef typename Function::ArgumentTuple ArgumentTuple; typedef typename Function::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function::Result Result; TypedExpectation(FunctionMockerBase* owner, const char* a_file, int a_line, const std::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). extra_matcher_(A()), 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*>(*it); } } // Implements the .With() clause. TypedExpectation& With(const Matcher& 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& action) { ExpectSpecProperty(last_clause_ <= kWillOnce, ".WillOnce() cannot appear after " ".WillRepeatedly() or .RetiresOnSaturation()."); last_clause_ = kWillOnce; untyped_actions_.push_back(new Action(action)); if (!cardinality_specified()) { set_cardinality(Exactly(static_cast(untyped_actions_.size()))); } return *this; } // Implements the .WillRepeatedly() clause. TypedExpectation& WillRepeatedly(const Action& 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(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& extra_matcher() const { return extra_matcher_; } // Returns the action specified by the .WillRepeatedly() clause. const Action& 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 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& GetCurrentAction( const FunctionMockerBase* 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(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*>( untyped_actions_[static_cast(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* GetActionForArguments( const FunctionMockerBase* 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); // FIXME: allow the user to control whether // unexpected calls should fail immediately or continue using a // flag --gmock_unexpected_calls_are_fatal. return nullptr; } 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* const owner_; ArgumentMatcherTuple matchers_; Matcher extra_matcher_; Action 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 std::string& message); template class MockSpec { public: typedef typename internal::Function::ArgumentTuple ArgumentTuple; typedef typename internal::Function::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. MockSpec(internal::FunctionMockerBase* function_mocker, const ArgumentMatcherTuple& matchers) : function_mocker_(function_mocker), matchers_(matchers) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. internal::OnCallSpec& InternalDefaultActionSetAt( const char* file, int line, const char* obj, const char* call) { LogWithLocation(internal::kInfo, file, line, std::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& InternalExpectedAt( const char* file, int line, const char* obj, const char* call) { const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); return function_mocker_->AddNewExpectation( file, line, source_text, matchers_); } // This operator overload is used to swallow the superfluous parameter list // introduced by the ON/EXPECT_CALL macros. See the macro comments for more // explanation. MockSpec& operator()(const internal::WithoutMatchers&, void* const) { return *this; } private: template friend class internal::FunctionMocker; // The function mocker that owns this spec. internal::FunctionMockerBase* 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 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 class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. explicit ReferenceOrValueWrapper(T value) : value_(std::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 std::move(value_); } // Provides nondestructive access to the underlying value/reference. // Always returns a const reference (more precisely, // const RemoveReference&). 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 class ReferenceOrValueWrapper { 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. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355) // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. // ActionResultHolder 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. 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 class ActionResultHolder : public UntypedActionResultHolderBase { public: // 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::Print(result_.Peek(), os); } // Performs the given mock function's default action and returns the // result in a new-ed ActionResultHolder. template static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase* func_mocker, typename Function::ArgumentTuple&& args, const std::string& call_description) { return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( std::move(args), call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template static ActionResultHolder* PerformAction( const Action& action, typename Function::ArgumentTuple&& args) { return new ActionResultHolder( Wrapper(action.Perform(std::move(args)))); } private: typedef ReferenceOrValueWrapper Wrapper; explicit ActionResultHolder(Wrapper result) : result_(std::move(result)) { } Wrapper result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); }; // Specialization for T = void. template <> class ActionResultHolder : public UntypedActionResultHolderBase { public: void Unwrap() { } virtual void PrintAsActionResult(::std::ostream* /* os */) const {} // Performs the given mock function's default action and returns ownership // of an empty ActionResultHolder*. template static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase* func_mocker, typename Function::ArgumentTuple&& args, const std::string& call_description) { func_mocker->PerformDefaultAction(std::move(args), call_description); return new ActionResultHolder; } // Performs the given action and returns ownership of an empty // ActionResultHolder*. template static ActionResultHolder* PerformAction( const Action& action, typename Function::ArgumentTuple&& args) { action.Perform(std::move(args)); 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 class FunctionMockerBase : public UntypedFunctionMockerBase { public: typedef typename Function::Result Result; typedef typename Function::ArgumentTuple ArgumentTuple; typedef typename Function::ArgumentMatcherTuple ArgumentMatcherTuple; FunctionMockerBase() {} // 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* 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* spec = static_cast*>(*it); if (spec->Matches(args)) return spec; } return nullptr; } // 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(typename Function::ArgumentTuple&& args, const std::string& call_description) const { const OnCallSpec* const spec = this->FindOnCallSpec(args); if (spec != nullptr) { return spec->GetAction().Perform(std::move(args)); } const std::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::Exists()) { throw std::runtime_error(message); } #else Assert(DefaultValue::Exists(), "", -1, message); #endif return DefaultValue::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( void* untyped_args, // must point to an ArgumentTuple const std::string& call_description) const { ArgumentTuple* args = static_cast(untyped_args); return ResultHolder::PerformDefaultAction(this, std::move(*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, 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 action = *static_cast*>(untyped_action); ArgumentTuple* args = static_cast(untyped_args); return ResultHolder::PerformAction(action, std::move(*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*>(*it); } // Lock the mutex again, since the caller expects it to be locked when we // return. g_gmock_mutex.Lock(); } protected: template friend class MockSpec; typedef ActionResultHolder 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(typename Function::ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { // const_cast is required since in C++98 we still pass ArgumentTuple around // by const& instead of rvalue reference. void* untyped_args = const_cast(static_cast(&args)); - scoped_ptr holder( + std::unique_ptr holder( DownCast_(this->UntypedInvokeWith(untyped_args))); return holder->Unwrap(); } // Adds and returns a default action spec for this mock function. OnCallSpec& AddNewOnCallSpec( const char* file, int line, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec* const on_call_spec = new OnCallSpec(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& AddNewExpectation(const char* file, int line, const std::string& source_text, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); TypedExpectation* const expectation = new TypedExpectation(this, file, line, source_text, m); const std::shared_ptr untyped_expectation(expectation); // See the definition of untyped_expectations_ for why access to // it is unprotected here. 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 != nullptr) { implicit_sequence->AddExpectation(Expectation(untyped_expectation)); } return *expectation; } private: template 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* const spec = FindOnCallSpec(args); if (spec == nullptr) { *os << (internal::type_equals::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(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(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation* exp = this->FindMatchingExpectationLocked(args); if (exp == nullptr) { // A match wasn't found. this->FormatUnexpectedCallMessageLocked(args, what, why); return nullptr; } // 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* action = exp->GetActionForArguments(this, args, what, why); if (action != nullptr && action->IsDoDefault()) action = nullptr; // 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(untyped_args); UniversalPrint(args, os); } // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. TypedExpectation* FindMatchingExpectationLocked( const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // See the definition of untyped_expectations_ for why access to // it is unprotected here. for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { TypedExpectation* const exp = static_cast*>(it->get()); if (exp->ShouldHandleArguments(args)) { return exp; } } return nullptr; } // 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 size_t count = untyped_expectations_.size(); *why << "Google Mock tried the following " << count << " " << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; for (size_t i = 0; i < count; i++) { TypedExpectation* const expectation = static_cast*>(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); } } // 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, they should implement their 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 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355 // 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 std::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 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 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Implementation for ON_CALL and EXPECT_CALL macros. 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. // // This macro supports statements both with and without parameter matchers. If // the parameter list is omitted, gMock will accept any parameters, which allows // tests to be written that don't need to encode the number of method // parameter. This technique may only be used for non-overloaded methods. // // // These are the same: // ON_CALL(mock, NoArgsMethod()).WillByDefault(...); // ON_CALL(mock, NoArgsMethod).WillByDefault(...); // // // As are these: // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); // ON_CALL(mock, TwoArgsMethod).WillByDefault(...); // // // Can also specify args if you want, of course: // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); // // // Overloads work as long as you specify parameters: // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); // // // Oops! Which overload did you want? // ON_CALL(mock, OverloadedMethod).WillByDefault(...); // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous // // How this works: The mock class uses two overloads of the gmock_Method // expectation setter method plus an operator() overload on the MockSpec object. // In the matcher list form, the macro expands to: // // // This statement: // ON_CALL(mock, TwoArgsMethod(_, 45))... // // // ...expands to: // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... // |-------------v---------------||------------v-------------| // invokes first overload swallowed by operator() // // // ...which is essentially: // mock.gmock_TwoArgsMethod(_, 45)... // // Whereas the form without a matcher list: // // // This statement: // ON_CALL(mock, TwoArgsMethod)... // // // ...expands to: // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... // |-----------------------v--------------------------| // invokes second overload // // // ...which is essentially: // mock.gmock_TwoArgsMethod(_, _)... // // The WithoutMatchers() argument is used to disambiguate overloads and to // block the caller from accidentally invoking the second overload directly. The // second argument is an internal type derived from the method signature. The // failure to disambiguate two overloads of this method in the ON_CALL statement // is how we block callers from setting expectations on overloaded methods. #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \ nullptr) \ .Setter(__FILE__, __LINE__, #mock_expr, #call) #define ON_CALL(obj, call) \ GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call) #define EXPECT_CALL(obj, call) \ GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 6f042489..347c2c7b 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -1,6770 +1,6768 @@ // 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. // Google Mock - a framework for writing C++ mock classes. // // This file tests some commonly used argument matchers. #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-matchers.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #if GTEST_HAS_STD_FORWARD_LIST_ # include // NOLINT #endif #if GTEST_LANG_CXX11 # include #endif namespace testing { namespace gmock_matchers_test { using std::greater; using std::less; using std::list; using std::make_pair; using std::map; using std::multimap; using std::multiset; using std::ostream; using std::pair; using std::set; using std::stringstream; using std::vector; using testing::A; using testing::AllArgs; using testing::AllOf; using testing::An; using testing::AnyOf; using testing::ByRef; using testing::ContainsRegex; using testing::DoubleEq; using testing::DoubleNear; using testing::EndsWith; using testing::Eq; using testing::ExplainMatchResult; using testing::Field; using testing::FloatEq; using testing::FloatNear; using testing::Ge; using testing::Gt; using testing::HasSubstr; using testing::IsEmpty; using testing::IsNull; using testing::Key; using testing::Le; using testing::Lt; using testing::MakeMatcher; using testing::MakePolymorphicMatcher; using testing::MatchResultListener; using testing::Matcher; using testing::MatcherCast; using testing::MatcherInterface; using testing::Matches; using testing::MatchesRegex; using testing::NanSensitiveDoubleEq; using testing::NanSensitiveDoubleNear; using testing::NanSensitiveFloatEq; using testing::NanSensitiveFloatNear; using testing::Ne; using testing::Not; using testing::NotNull; using testing::Pair; using testing::Pointee; using testing::Pointwise; using testing::PolymorphicMatcher; using testing::Property; using testing::Ref; using testing::ResultOf; using testing::SizeIs; using testing::StartsWith; using testing::StrCaseEq; using testing::StrCaseNe; using testing::StrEq; using testing::StrNe; using testing::StringMatchResultListener; using testing::Truly; using testing::TypedEq; using testing::UnorderedPointwise; using testing::Value; using testing::WhenSorted; using testing::WhenSortedBy; using testing::_; using testing::internal::DummyMatchResultListener; using testing::internal::ElementMatcherPair; using testing::internal::ElementMatcherPairs; using testing::internal::ExplainMatchFailureTupleTo; using testing::internal::FloatingEqMatcher; using testing::internal::FormatMatcherDescription; using testing::internal::IsReadableTypeName; using testing::internal::MatchMatrix; using testing::internal::RE; -using testing::internal::scoped_ptr; using testing::internal::StreamMatchResultListener; using testing::internal::Strings; -using testing::internal::scoped_ptr; using testing::internal::string; // For testing ExplainMatchResultTo(). class GreaterThanMatcher : public MatcherInterface { public: explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} virtual void DescribeTo(ostream* os) const { *os << "is > " << rhs_; } virtual bool MatchAndExplain(int lhs, MatchResultListener* listener) const { const int diff = lhs - rhs_; if (diff > 0) { *listener << "which is " << diff << " more than " << rhs_; } else if (diff == 0) { *listener << "which is the same as " << rhs_; } else { *listener << "which is " << -diff << " less than " << rhs_; } return lhs > rhs_; } private: int rhs_; }; Matcher GreaterThan(int n) { return MakeMatcher(new GreaterThanMatcher(n)); } std::string OfType(const std::string& type_name) { #if GTEST_HAS_RTTI return " (of type " + type_name + ")"; #else return ""; #endif } // Returns the description of the given matcher. template std::string Describe(const Matcher& m) { return DescribeMatcher(m); } // Returns the description of the negation of the given matcher. template std::string DescribeNegation(const Matcher& m) { return DescribeMatcher(m, true); } // Returns the reason why x matches, or doesn't match, m. template std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } TEST(MonotonicMatcherTest, IsPrintable) { stringstream ss; ss << GreaterThan(5); EXPECT_EQ("is > 5", ss.str()); } TEST(MatchResultListenerTest, StreamingWorks) { StringMatchResultListener listener; listener << "hi" << 5; EXPECT_EQ("hi5", listener.str()); listener.Clear(); EXPECT_EQ("", listener.str()); listener << 42; EXPECT_EQ("42", listener.str()); // Streaming shouldn't crash when the underlying ostream is NULL. DummyMatchResultListener dummy; dummy << "hi" << 5; } TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); } TEST(MatchResultListenerTest, IsInterestedWorks) { EXPECT_TRUE(StringMatchResultListener().IsInterested()); EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); EXPECT_FALSE(DummyMatchResultListener().IsInterested()); EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); } // Makes sure that the MatcherInterface interface doesn't // change. class EvenMatcherImpl : public MatcherInterface { public: virtual bool MatchAndExplain(int x, MatchResultListener* /* listener */) const { return x % 2 == 0; } virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } // We deliberately don't define DescribeNegationTo() and // ExplainMatchResultTo() here, to make sure the definition of these // two methods is optional. }; // Makes sure that the MatcherInterface API doesn't change. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) { EvenMatcherImpl m; } // Tests implementing a monomorphic matcher using MatchAndExplain(). class NewEvenMatcherImpl : public MatcherInterface { public: virtual bool MatchAndExplain(int x, MatchResultListener* listener) const { const bool match = x % 2 == 0; // Verifies that we can stream to a listener directly. *listener << "value % " << 2; if (listener->stream() != nullptr) { // Verifies that we can stream to a listener's underlying stream // too. *listener->stream() << " == " << (x % 2); } return match; } virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } }; TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { Matcher m = MakeMatcher(new NewEvenMatcherImpl); EXPECT_TRUE(m.Matches(2)); EXPECT_FALSE(m.Matches(3)); EXPECT_EQ("value % 2 == 0", Explain(m, 2)); EXPECT_EQ("value % 2 == 1", Explain(m, 3)); } // Tests default-constructing a matcher. TEST(MatcherTest, CanBeDefaultConstructed) { Matcher m; } // Tests that Matcher can be constructed from a MatcherInterface*. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { const MatcherInterface* impl = new EvenMatcherImpl; Matcher m(impl); EXPECT_TRUE(m.Matches(4)); EXPECT_FALSE(m.Matches(5)); } // Tests that value can be used in place of Eq(value). TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { Matcher m1 = 5; EXPECT_TRUE(m1.Matches(5)); EXPECT_FALSE(m1.Matches(6)); } // Tests that NULL can be used in place of Eq(NULL). TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { Matcher m1 = nullptr; EXPECT_TRUE(m1.Matches(nullptr)); int n = 0; EXPECT_FALSE(m1.Matches(&n)); } // Tests that matchers can be constructed from a variable that is not properly // defined. This should be illegal, but many users rely on this accidentally. struct Undefined { virtual ~Undefined() = 0; static const int kInt = 1; }; TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { Matcher m1 = Undefined::kInt; EXPECT_TRUE(m1.Matches(1)); EXPECT_FALSE(m1.Matches(2)); } // Test that a matcher parameterized with an abstract class compiles. TEST(MatcherTest, CanAcceptAbstractClass) { Matcher m = _; } // Tests that matchers are copyable. TEST(MatcherTest, IsCopyable) { // Tests the copy constructor. Matcher m1 = Eq(false); EXPECT_TRUE(m1.Matches(false)); EXPECT_FALSE(m1.Matches(true)); // Tests the assignment operator. m1 = Eq(true); EXPECT_TRUE(m1.Matches(true)); EXPECT_FALSE(m1.Matches(false)); } // Tests that Matcher::DescribeTo() calls // MatcherInterface::DescribeTo(). TEST(MatcherTest, CanDescribeItself) { EXPECT_EQ("is an even number", Describe(Matcher(new EvenMatcherImpl))); } // Tests Matcher::MatchAndExplain(). TEST(MatcherTest, MatchAndExplain) { Matcher m = GreaterThan(0); StringMatchResultListener listener1; EXPECT_TRUE(m.MatchAndExplain(42, &listener1)); EXPECT_EQ("which is 42 more than 0", listener1.str()); StringMatchResultListener listener2; EXPECT_FALSE(m.MatchAndExplain(-9, &listener2)); EXPECT_EQ("which is 9 less than 0", listener2.str()); } // Tests that a C-string literal can be implicitly converted to a // Matcher or Matcher. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { Matcher m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a string object can be implicitly converted to a // Matcher or Matcher. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { Matcher m1 = std::string("hi"); EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = std::string("hi"); EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } #if GTEST_HAS_GLOBAL_STRING // Tests that a ::string object can be implicitly converted to a // Matcher or Matcher. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { Matcher m1 = ::string("hi"); EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = ::string("hi"); EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_STRING // Tests that a C-string literal can be implicitly converted to a // Matcher<::string> or Matcher. TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { Matcher< ::string> m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a std::string object can be implicitly converted to a // Matcher<::string> or Matcher. TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) { Matcher< ::string> m1 = std::string("hi"); EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = std::string("hi"); EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a ::string object can be implicitly converted to a // Matcher<::string> or Matcher. TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { Matcher< ::string> m1 = ::string("hi"); EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); Matcher m2 = ::string("hi"); EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_ABSL // Tests that a C-string literal can be implicitly converted to a // Matcher or Matcher. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { Matcher m1 = "cats"; EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); Matcher m2 = "cats"; EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } // Tests that a std::string object can be implicitly converted to a // Matcher or Matcher. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { Matcher m1 = std::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); Matcher m2 = std::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } #if GTEST_HAS_GLOBAL_STRING // Tests that a ::string object can be implicitly converted to a // Matcher or Matcher. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { Matcher m1 = ::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); Matcher m2 = ::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } #endif // GTEST_HAS_GLOBAL_STRING // Tests that a absl::string_view object can be implicitly converted to a // Matcher or Matcher. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { Matcher m1 = absl::string_view("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); Matcher m2 = absl::string_view("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } #endif // GTEST_HAS_ABSL // Tests that MakeMatcher() constructs a Matcher from a // MatcherInterface* without requiring the user to explicitly // write the type. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { const MatcherInterface* dummy_impl = nullptr; Matcher m = MakeMatcher(dummy_impl); } // Tests that MakePolymorphicMatcher() can construct a polymorphic // matcher from its implementation using the old API. const int g_bar = 1; class ReferencesBarOrIsZeroImpl { public: template bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const { const void* p = &x; return p == &g_bar || x == 0; } void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } void DescribeNegationTo(ostream* os) const { *os << "doesn't reference g_bar and is not zero"; } }; // This function verifies that MakePolymorphicMatcher() returns a // PolymorphicMatcher where T is the argument's type. PolymorphicMatcher ReferencesBarOrIsZero() { return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); } TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { // Using a polymorphic matcher to match a reference type. Matcher m1 = ReferencesBarOrIsZero(); EXPECT_TRUE(m1.Matches(0)); // Verifies that the identity of a by-reference argument is preserved. EXPECT_TRUE(m1.Matches(g_bar)); EXPECT_FALSE(m1.Matches(1)); EXPECT_EQ("g_bar or zero", Describe(m1)); // Using a polymorphic matcher to match a value type. Matcher m2 = ReferencesBarOrIsZero(); EXPECT_TRUE(m2.Matches(0.0)); EXPECT_FALSE(m2.Matches(0.1)); EXPECT_EQ("g_bar or zero", Describe(m2)); } // Tests implementing a polymorphic matcher using MatchAndExplain(). class PolymorphicIsEvenImpl { public: void DescribeTo(ostream* os) const { *os << "is even"; } void DescribeNegationTo(ostream* os) const { *os << "is odd"; } template bool MatchAndExplain(const T& x, MatchResultListener* listener) const { // Verifies that we can stream to the listener directly. *listener << "% " << 2; if (listener->stream() != nullptr) { // Verifies that we can stream to the listener's underlying stream // too. *listener->stream() << " == " << (x % 2); } return (x % 2) == 0; } }; PolymorphicMatcher PolymorphicIsEven() { return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); } TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { // Using PolymorphicIsEven() as a Matcher. const Matcher m1 = PolymorphicIsEven(); EXPECT_TRUE(m1.Matches(42)); EXPECT_FALSE(m1.Matches(43)); EXPECT_EQ("is even", Describe(m1)); const Matcher not_m1 = Not(m1); EXPECT_EQ("is odd", Describe(not_m1)); EXPECT_EQ("% 2 == 0", Explain(m1, 42)); // Using PolymorphicIsEven() as a Matcher. const Matcher m2 = PolymorphicIsEven(); EXPECT_TRUE(m2.Matches('\x42')); EXPECT_FALSE(m2.Matches('\x43')); EXPECT_EQ("is even", Describe(m2)); const Matcher not_m2 = Not(m2); EXPECT_EQ("is odd", Describe(not_m2)); EXPECT_EQ("% 2 == 0", Explain(m2, '\x42')); } // Tests that MatcherCast(m) works when m is a polymorphic matcher. TEST(MatcherCastTest, FromPolymorphicMatcher) { Matcher m = MatcherCast(Eq(5)); EXPECT_TRUE(m.Matches(5)); EXPECT_FALSE(m.Matches(6)); } // For testing casting matchers between compatible types. class IntValue { public: // An int can be statically (although not implicitly) cast to a // IntValue. explicit IntValue(int a_value) : value_(a_value) {} int value() const { return value_; } private: int value_; }; // For testing casting matchers between compatible types. bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; } // Tests that MatcherCast(m) works when m is a Matcher where T // can be statically converted to U. TEST(MatcherCastTest, FromCompatibleType) { Matcher m1 = Eq(2.0); Matcher m2 = MatcherCast(m1); EXPECT_TRUE(m2.Matches(2)); EXPECT_FALSE(m2.Matches(3)); Matcher m3 = Truly(IsPositiveIntValue); Matcher m4 = MatcherCast(m3); // In the following, the arguments 1 and 0 are statically converted // to IntValue objects, and then tested by the IsPositiveIntValue() // predicate. EXPECT_TRUE(m4.Matches(1)); EXPECT_FALSE(m4.Matches(0)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(MatcherCastTest, FromConstReferenceToNonReference) { Matcher m1 = Eq(0); Matcher m2 = MatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(MatcherCastTest, FromReferenceToNonReference) { Matcher m1 = Eq(0); Matcher m2 = MatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(MatcherCastTest, FromNonReferenceToConstReference) { Matcher m1 = Eq(0); Matcher m2 = MatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(MatcherCastTest, FromNonReferenceToReference) { Matcher m1 = Eq(0); Matcher m2 = MatcherCast(m1); int n = 0; EXPECT_TRUE(m2.Matches(n)); n = 1; EXPECT_FALSE(m2.Matches(n)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(MatcherCastTest, FromSameType) { Matcher m1 = Eq(0); Matcher m2 = MatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } // Tests that MatcherCast(m) works when m is a value of the same type as the // value type of the Matcher. TEST(MatcherCastTest, FromAValue) { Matcher m = MatcherCast(42); EXPECT_TRUE(m.Matches(42)); EXPECT_FALSE(m.Matches(239)); } // Tests that MatcherCast(m) works when m is a value of the type implicitly // convertible to the value type of the Matcher. TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { const int kExpected = 'c'; Matcher m = MatcherCast('c'); EXPECT_TRUE(m.Matches(kExpected)); EXPECT_FALSE(m.Matches(kExpected + 1)); } struct NonImplicitlyConstructibleTypeWithOperatorEq { friend bool operator==( const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, int rhs) { return 42 == rhs; } friend bool operator==( int lhs, const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { return lhs == 42; } }; // Tests that MatcherCast(m) works when m is a neither a matcher nor // implicitly convertible to the value type of the Matcher, but the value type // of the matcher has operator==() overload accepting m. TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { Matcher m1 = MatcherCast(42); EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); Matcher m2 = MatcherCast(239); EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); // When updating the following lines please also change the comment to // namespace convertible_from_any. Matcher m3 = MatcherCast(NonImplicitlyConstructibleTypeWithOperatorEq()); EXPECT_TRUE(m3.Matches(42)); EXPECT_FALSE(m3.Matches(239)); } // ConvertibleFromAny does not work with MSVC. resulting in // error C2440: 'initializing': cannot convert from 'Eq' to 'M' // No constructor could take the source type, or constructor overload // resolution was ambiguous #if !defined _MSC_VER // The below ConvertibleFromAny struct is implicitly constructible from anything // and when in the same namespace can interact with other tests. In particular, // if it is in the same namespace as other tests and one removes // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); // then the corresponding test still compiles (and it should not!) by implicitly // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny // in m3.Matcher(). namespace convertible_from_any { // Implicitly convertible from any type. struct ConvertibleFromAny { ConvertibleFromAny(int a_value) : value(a_value) {} template ConvertibleFromAny(const T& /*a_value*/) : value(-1) { ADD_FAILURE() << "Conversion constructor called"; } int value; }; bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) { return a.value == b.value; } ostream& operator<<(ostream& os, const ConvertibleFromAny& a) { return os << a.value; } TEST(MatcherCastTest, ConversionConstructorIsUsed) { Matcher m = MatcherCast(1); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } TEST(MatcherCastTest, FromConvertibleFromAny) { Matcher m = MatcherCast(Eq(ConvertibleFromAny(1))); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } } // namespace convertible_from_any #endif // !defined _MSC_VER struct IntReferenceWrapper { IntReferenceWrapper(const int& a_value) : value(&a_value) {} const int* value; }; bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) { return a.value == b.value; } TEST(MatcherCastTest, ValueIsNotCopied) { int n = 42; Matcher m = MatcherCast(n); // Verify that the matcher holds a reference to n, not to its temporary copy. EXPECT_TRUE(m.Matches(n)); } class Base { public: virtual ~Base() {} Base() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Base); }; class Derived : public Base { public: Derived() : Base() {} int i; }; class OtherDerived : public Base {}; // Tests that SafeMatcherCast(m) works when m is a polymorphic matcher. TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { Matcher m2 = SafeMatcherCast(Eq(32)); EXPECT_TRUE(m2.Matches(' ')); EXPECT_FALSE(m2.Matches('\n')); } // Tests that SafeMatcherCast(m) works when m is a Matcher where // T and U are arithmetic types and T can be losslessly converted to // U. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { Matcher m1 = DoubleEq(1.0); Matcher m2 = SafeMatcherCast(m1); EXPECT_TRUE(m2.Matches(1.0f)); EXPECT_FALSE(m2.Matches(2.0f)); Matcher m3 = SafeMatcherCast(TypedEq('a')); EXPECT_TRUE(m3.Matches('a')); EXPECT_FALSE(m3.Matches('b')); } // Tests that SafeMatcherCast(m) works when m is a Matcher where T and U // are pointers or references to a derived and a base class, correspondingly. TEST(SafeMatcherCastTest, FromBaseClass) { Derived d, d2; Matcher m1 = Eq(&d); Matcher m2 = SafeMatcherCast(m1); EXPECT_TRUE(m2.Matches(&d)); EXPECT_FALSE(m2.Matches(&d2)); Matcher m3 = Ref(d); Matcher m4 = SafeMatcherCast(m3); EXPECT_TRUE(m4.Matches(d)); EXPECT_FALSE(m4.Matches(d2)); } // Tests that SafeMatcherCast(m) works when m is a Matcher. TEST(SafeMatcherCastTest, FromConstReferenceToReference) { int n = 0; Matcher m1 = Ref(n); Matcher m2 = SafeMatcherCast(m1); int n1 = 0; EXPECT_TRUE(m2.Matches(n)); EXPECT_FALSE(m2.Matches(n1)); } // Tests that MatcherCast(m) works when m is a Matcher. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { Matcher m1 = Eq(0); Matcher m2 = SafeMatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } // Tests that SafeMatcherCast(m) works when m is a Matcher. TEST(SafeMatcherCastTest, FromNonReferenceToReference) { Matcher m1 = Eq(0); Matcher m2 = SafeMatcherCast(m1); int n = 0; EXPECT_TRUE(m2.Matches(n)); n = 1; EXPECT_FALSE(m2.Matches(n)); } // Tests that SafeMatcherCast(m) works when m is a Matcher. TEST(SafeMatcherCastTest, FromSameType) { Matcher m1 = Eq(0); Matcher m2 = SafeMatcherCast(m1); EXPECT_TRUE(m2.Matches(0)); EXPECT_FALSE(m2.Matches(1)); } #if !defined _MSC_VER namespace convertible_from_any { TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { Matcher m = SafeMatcherCast(1); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } TEST(SafeMatcherCastTest, FromConvertibleFromAny) { Matcher m = SafeMatcherCast(Eq(ConvertibleFromAny(1))); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } } // namespace convertible_from_any #endif // !defined _MSC_VER TEST(SafeMatcherCastTest, ValueIsNotCopied) { int n = 42; Matcher m = SafeMatcherCast(n); // Verify that the matcher holds a reference to n, not to its temporary copy. EXPECT_TRUE(m.Matches(n)); } TEST(ExpectThat, TakesLiterals) { EXPECT_THAT(1, 1); EXPECT_THAT(1.0, 1.0); EXPECT_THAT(std::string(), ""); } TEST(ExpectThat, TakesFunctions) { struct Helper { static void Func() {} }; void (*func)() = Helper::Func; EXPECT_THAT(func, Helper::Func); EXPECT_THAT(func, &Helper::Func); } // Tests that A() matches any value of type T. TEST(ATest, MatchesAnyValue) { // Tests a matcher for a value type. Matcher m1 = A(); EXPECT_TRUE(m1.Matches(91.43)); EXPECT_TRUE(m1.Matches(-15.32)); // Tests a matcher for a reference type. int a = 2; int b = -6; Matcher m2 = A(); EXPECT_TRUE(m2.Matches(a)); EXPECT_TRUE(m2.Matches(b)); } TEST(ATest, WorksForDerivedClass) { Base base; Derived derived; EXPECT_THAT(&base, A()); // This shouldn't compile: EXPECT_THAT(&base, A()); EXPECT_THAT(&derived, A()); EXPECT_THAT(&derived, A()); } // Tests that A() describes itself properly. TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A())); } // Tests that An() matches any value of type T. TEST(AnTest, MatchesAnyValue) { // Tests a matcher for a value type. Matcher m1 = An(); EXPECT_TRUE(m1.Matches(9143)); EXPECT_TRUE(m1.Matches(-1532)); // Tests a matcher for a reference type. int a = 2; int b = -6; Matcher m2 = An(); EXPECT_TRUE(m2.Matches(a)); EXPECT_TRUE(m2.Matches(b)); } // Tests that An() describes itself properly. TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An())); } // Tests that _ can be used as a matcher for any type and matches any // value of that type. TEST(UnderscoreTest, MatchesAnyValue) { // Uses _ as a matcher for a value type. Matcher m1 = _; EXPECT_TRUE(m1.Matches(123)); EXPECT_TRUE(m1.Matches(-242)); // Uses _ as a matcher for a reference type. bool a = false; const bool b = true; Matcher m2 = _; EXPECT_TRUE(m2.Matches(a)); EXPECT_TRUE(m2.Matches(b)); } // Tests that _ describes itself properly. TEST(UnderscoreTest, CanDescribeSelf) { Matcher m = _; EXPECT_EQ("is anything", Describe(m)); } // Tests that Eq(x) matches any value equal to x. TEST(EqTest, MatchesEqualValue) { // 2 C-strings with same content but different addresses. const char a1[] = "hi"; const char a2[] = "hi"; Matcher m1 = Eq(a1); EXPECT_TRUE(m1.Matches(a1)); EXPECT_FALSE(m1.Matches(a2)); } // Tests that Eq(v) describes itself properly. class Unprintable { public: Unprintable() : c_('a') {} bool operator==(const Unprintable& /* rhs */) const { return true; } private: char c_; }; TEST(EqTest, CanDescribeSelf) { Matcher m = Eq(Unprintable()); EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); } // Tests that Eq(v) can be used to match any type that supports // comparing with type T, where T is v's type. TEST(EqTest, IsPolymorphic) { Matcher m1 = Eq(1); EXPECT_TRUE(m1.Matches(1)); EXPECT_FALSE(m1.Matches(2)); Matcher m2 = Eq(1); EXPECT_TRUE(m2.Matches('\1')); EXPECT_FALSE(m2.Matches('a')); } // Tests that TypedEq(v) matches values of type T that's equal to v. TEST(TypedEqTest, ChecksEqualityForGivenType) { Matcher m1 = TypedEq('a'); EXPECT_TRUE(m1.Matches('a')); EXPECT_FALSE(m1.Matches('b')); Matcher m2 = TypedEq(6); EXPECT_TRUE(m2.Matches(6)); EXPECT_FALSE(m2.Matches(7)); } // Tests that TypedEq(v) describes itself properly. TEST(TypedEqTest, CanDescribeSelf) { EXPECT_EQ("is equal to 2", Describe(TypedEq(2))); } // Tests that TypedEq(v) has type Matcher. // Type::IsTypeOf(v) compiles iff the type of value v is T, where T // is a "bare" type (i.e. not in the form of const U or U&). If v's // type is not T, the compiler will generate a message about // "undefined reference". template struct Type { static bool IsTypeOf(const T& /* v */) { return true; } template static void IsTypeOf(T2 v); }; TEST(TypedEqTest, HasSpecifiedType) { // Verfies that the type of TypedEq(v) is Matcher. Type >::IsTypeOf(TypedEq(5)); Type >::IsTypeOf(TypedEq(5)); } // Tests that Ge(v) matches anything >= v. TEST(GeTest, ImplementsGreaterThanOrEqual) { Matcher m1 = Ge(0); EXPECT_TRUE(m1.Matches(1)); EXPECT_TRUE(m1.Matches(0)); EXPECT_FALSE(m1.Matches(-1)); } // Tests that Ge(v) describes itself properly. TEST(GeTest, CanDescribeSelf) { Matcher m = Ge(5); EXPECT_EQ("is >= 5", Describe(m)); } // Tests that Gt(v) matches anything > v. TEST(GtTest, ImplementsGreaterThan) { Matcher m1 = Gt(0); EXPECT_TRUE(m1.Matches(1.0)); EXPECT_FALSE(m1.Matches(0.0)); EXPECT_FALSE(m1.Matches(-1.0)); } // Tests that Gt(v) describes itself properly. TEST(GtTest, CanDescribeSelf) { Matcher m = Gt(5); EXPECT_EQ("is > 5", Describe(m)); } // Tests that Le(v) matches anything <= v. TEST(LeTest, ImplementsLessThanOrEqual) { Matcher m1 = Le('b'); EXPECT_TRUE(m1.Matches('a')); EXPECT_TRUE(m1.Matches('b')); EXPECT_FALSE(m1.Matches('c')); } // Tests that Le(v) describes itself properly. TEST(LeTest, CanDescribeSelf) { Matcher m = Le(5); EXPECT_EQ("is <= 5", Describe(m)); } // Tests that Lt(v) matches anything < v. TEST(LtTest, ImplementsLessThan) { Matcher m1 = Lt("Hello"); EXPECT_TRUE(m1.Matches("Abc")); EXPECT_FALSE(m1.Matches("Hello")); EXPECT_FALSE(m1.Matches("Hello, world!")); } // Tests that Lt(v) describes itself properly. TEST(LtTest, CanDescribeSelf) { Matcher m = Lt(5); EXPECT_EQ("is < 5", Describe(m)); } // Tests that Ne(v) matches anything != v. TEST(NeTest, ImplementsNotEqual) { Matcher m1 = Ne(0); EXPECT_TRUE(m1.Matches(1)); EXPECT_TRUE(m1.Matches(-1)); EXPECT_FALSE(m1.Matches(0)); } // Tests that Ne(v) describes itself properly. TEST(NeTest, CanDescribeSelf) { Matcher m = Ne(5); EXPECT_EQ("isn't equal to 5", Describe(m)); } // Tests that IsNull() matches any NULL pointer of any type. TEST(IsNullTest, MatchesNullPointer) { Matcher m1 = IsNull(); int* p1 = nullptr; int n = 0; EXPECT_TRUE(m1.Matches(p1)); EXPECT_FALSE(m1.Matches(&n)); Matcher m2 = IsNull(); const char* p2 = nullptr; EXPECT_TRUE(m2.Matches(p2)); EXPECT_FALSE(m2.Matches("hi")); #if !GTEST_OS_SYMBIAN // Nokia's Symbian compiler generates: // gmock-matchers.h: ambiguous access to overloaded function // gmock-matchers.h: 'testing::Matcher::Matcher(void *)' // gmock-matchers.h: 'testing::Matcher::Matcher(const testing:: // MatcherInterface *)' // gmock-matchers.h: (point of instantiation: 'testing:: // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc Matcher m3 = IsNull(); void* p3 = nullptr; EXPECT_TRUE(m3.Matches(p3)); EXPECT_FALSE(m3.Matches(reinterpret_cast(0xbeef))); #endif } #if GTEST_LANG_CXX11 TEST(IsNullTest, StdFunction) { const Matcher> m = IsNull(); EXPECT_TRUE(m.Matches(std::function())); EXPECT_FALSE(m.Matches([]{})); } #endif // GTEST_LANG_CXX11 // Tests that IsNull() describes itself properly. TEST(IsNullTest, CanDescribeSelf) { Matcher m = IsNull(); EXPECT_EQ("is NULL", Describe(m)); EXPECT_EQ("isn't NULL", DescribeNegation(m)); } // Tests that NotNull() matches any non-NULL pointer of any type. TEST(NotNullTest, MatchesNonNullPointer) { Matcher m1 = NotNull(); int* p1 = nullptr; int n = 0; EXPECT_FALSE(m1.Matches(p1)); EXPECT_TRUE(m1.Matches(&n)); Matcher m2 = NotNull(); const char* p2 = nullptr; EXPECT_FALSE(m2.Matches(p2)); EXPECT_TRUE(m2.Matches("hi")); } TEST(NotNullTest, LinkedPtr) { const Matcher> m = NotNull(); const std::shared_ptr null_p; const std::shared_ptr non_null_p(new int); EXPECT_FALSE(m.Matches(null_p)); EXPECT_TRUE(m.Matches(non_null_p)); } TEST(NotNullTest, ReferenceToConstLinkedPtr) { const Matcher&> m = NotNull(); const std::shared_ptr null_p; const std::shared_ptr non_null_p(new double); EXPECT_FALSE(m.Matches(null_p)); EXPECT_TRUE(m.Matches(non_null_p)); } #if GTEST_LANG_CXX11 TEST(NotNullTest, StdFunction) { const Matcher> m = NotNull(); EXPECT_TRUE(m.Matches([]{})); EXPECT_FALSE(m.Matches(std::function())); } #endif // GTEST_LANG_CXX11 // Tests that NotNull() describes itself properly. TEST(NotNullTest, CanDescribeSelf) { Matcher m = NotNull(); EXPECT_EQ("isn't NULL", Describe(m)); } // Tests that Ref(variable) matches an argument that references // 'variable'. TEST(RefTest, MatchesSameVariable) { int a = 0; int b = 0; Matcher m = Ref(a); EXPECT_TRUE(m.Matches(a)); EXPECT_FALSE(m.Matches(b)); } // Tests that Ref(variable) describes itself properly. TEST(RefTest, CanDescribeSelf) { int n = 5; Matcher m = Ref(n); stringstream ss; ss << "references the variable @" << &n << " 5"; EXPECT_EQ(ss.str(), Describe(m)); } // Test that Ref(non_const_varialbe) can be used as a matcher for a // const reference. TEST(RefTest, CanBeUsedAsMatcherForConstReference) { int a = 0; int b = 0; Matcher m = Ref(a); EXPECT_TRUE(m.Matches(a)); EXPECT_FALSE(m.Matches(b)); } // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be // used wherever Ref(base) can be used (Ref(derived) is a sub-type // of Ref(base), but not vice versa. TEST(RefTest, IsCovariant) { Base base, base2; Derived derived; Matcher m1 = Ref(base); EXPECT_TRUE(m1.Matches(base)); EXPECT_FALSE(m1.Matches(base2)); EXPECT_FALSE(m1.Matches(derived)); m1 = Ref(derived); EXPECT_TRUE(m1.Matches(derived)); EXPECT_FALSE(m1.Matches(base)); EXPECT_FALSE(m1.Matches(base2)); } TEST(RefTest, ExplainsResult) { int n = 0; EXPECT_THAT(Explain(Matcher(Ref(n)), n), StartsWith("which is located @")); int m = 0; EXPECT_THAT(Explain(Matcher(Ref(n)), m), StartsWith("which is located @")); } // Tests string comparison matchers. TEST(StrEqTest, MatchesEqualString) { Matcher m = StrEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrEq("Hello"); EXPECT_TRUE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hi")); #if GTEST_HAS_ABSL Matcher m3 = StrEq("Hello"); EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); EXPECT_FALSE(m3.Matches(absl::string_view())); Matcher m_empty = StrEq(""); EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); EXPECT_TRUE(m_empty.Matches(absl::string_view())); EXPECT_FALSE(m_empty.Matches(absl::string_view("hello"))); #endif // GTEST_HAS_ABSL } TEST(StrEqTest, CanDescribeSelf) { Matcher m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", Describe(m)); std::string str("01204500800"); str[3] = '\0'; Matcher m2 = StrEq(str); EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; Matcher m3 = StrEq(str); EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); } TEST(StrNeTest, MatchesUnequalString) { Matcher m = StrNe("Hello"); EXPECT_TRUE(m.Matches("")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); Matcher m2 = StrNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hello")); #if GTEST_HAS_ABSL Matcher m3 = StrNe("Hello"); EXPECT_TRUE(m3.Matches(absl::string_view(""))); EXPECT_TRUE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); #endif // GTEST_HAS_ABSL } TEST(StrNeTest, CanDescribeSelf) { Matcher m = StrNe("Hi"); EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); } TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { Matcher m = StrCaseEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_TRUE(m.Matches("hello")); EXPECT_FALSE(m.Matches("Hi")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrCaseEq("Hello"); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hi")); #if GTEST_HAS_ABSL Matcher m3 = StrCaseEq(std::string("Hello")); EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); EXPECT_FALSE(m3.Matches(absl::string_view())); #endif // GTEST_HAS_ABSL } TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { std::string str1("oabocdooeoo"); std::string str2("OABOCDOOEOO"); Matcher m0 = StrCaseEq(str1); EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); str1[3] = str2[3] = '\0'; Matcher m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = '\0'; str2[0] = str2[6] = str2[7] = str2[10] = '\0'; Matcher m2 = StrCaseEq(str1); str1[9] = str2[9] = '\0'; EXPECT_FALSE(m2.Matches(str2)); Matcher m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + "x")); str2.append(1, '\0'); EXPECT_FALSE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); } TEST(StrCaseEqTest, CanDescribeSelf) { Matcher m = StrCaseEq("Hi"); EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); } TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher m = StrCaseNe("Hello"); EXPECT_TRUE(m.Matches("Hi")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); Matcher m2 = StrCaseNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("")); EXPECT_FALSE(m2.Matches("Hello")); #if GTEST_HAS_ABSL Matcher m3 = StrCaseNe("Hello"); EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); EXPECT_TRUE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); #endif // GTEST_HAS_ABSL } TEST(StrCaseNeTest, CanDescribeSelf) { Matcher m = StrCaseNe("Hi"); EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m)); } // Tests that HasSubstr() works for matching string-typed values. TEST(HasSubstrTest, WorksForStringClasses) { const Matcher m1 = HasSubstr("foo"); EXPECT_TRUE(m1.Matches(std::string("I love food."))); EXPECT_FALSE(m1.Matches(std::string("tofo"))); const Matcher m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches(std::string("I love food."))); EXPECT_FALSE(m2.Matches(std::string("tofo"))); const Matcher m_empty = HasSubstr(""); EXPECT_TRUE(m_empty.Matches(std::string())); EXPECT_TRUE(m_empty.Matches(std::string("not empty"))); } // Tests that HasSubstr() works for matching C-string-typed values. TEST(HasSubstrTest, WorksForCStrings) { const Matcher m1 = HasSubstr("foo"); EXPECT_TRUE(m1.Matches(const_cast("I love food."))); EXPECT_FALSE(m1.Matches(const_cast("tofo"))); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches("I love food.")); EXPECT_FALSE(m2.Matches("tofo")); EXPECT_FALSE(m2.Matches(nullptr)); const Matcher m_empty = HasSubstr(""); EXPECT_TRUE(m_empty.Matches("not empty")); EXPECT_TRUE(m_empty.Matches("")); EXPECT_FALSE(m_empty.Matches(nullptr)); } #if GTEST_HAS_ABSL // Tests that HasSubstr() works for matching absl::string_view-typed values. TEST(HasSubstrTest, WorksForStringViewClasses) { const Matcher m1 = HasSubstr("foo"); EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); EXPECT_FALSE(m1.Matches(absl::string_view())); const Matcher m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); EXPECT_FALSE(m2.Matches(absl::string_view())); const Matcher m3 = HasSubstr(""); EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); EXPECT_TRUE(m3.Matches(absl::string_view(""))); EXPECT_TRUE(m3.Matches(absl::string_view())); } #endif // GTEST_HAS_ABSL // Tests that HasSubstr(s) describes itself properly. TEST(HasSubstrTest, CanDescribeSelf) { Matcher m = HasSubstr("foo\n\""); EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); } TEST(KeyTest, CanDescribeSelf) { Matcher&> m = Key("foo"); EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m)); EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m)); } TEST(KeyTest, ExplainsResult) { Matcher > m = Key(GreaterThan(10)); EXPECT_EQ("whose first field is a value which is 5 less than 10", Explain(m, make_pair(5, true))); EXPECT_EQ("whose first field is a value which is 5 more than 10", Explain(m, make_pair(15, true))); } TEST(KeyTest, MatchesCorrectly) { pair p(25, "foo"); EXPECT_THAT(p, Key(25)); EXPECT_THAT(p, Not(Key(42))); EXPECT_THAT(p, Key(Ge(20))); EXPECT_THAT(p, Not(Key(Lt(25)))); } #if GTEST_LANG_CXX11 template struct Tag {}; struct PairWithGet { int member_1; string member_2; using first_type = int; using second_type = string; const int& GetImpl(Tag<0>) const { return member_1; } const string& GetImpl(Tag<1>) const { return member_2; } }; template auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag())) { return value.GetImpl(Tag()); } TEST(PairTest, MatchesPairWithGetCorrectly) { PairWithGet p{25, "foo"}; EXPECT_THAT(p, Key(25)); EXPECT_THAT(p, Not(Key(42))); EXPECT_THAT(p, Key(Ge(20))); EXPECT_THAT(p, Not(Key(Lt(25)))); std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; EXPECT_THAT(v, Contains(Key(29))); } #endif // GTEST_LANG_CXX11 TEST(KeyTest, SafelyCastsInnerMatcher) { Matcher is_positive = Gt(0); Matcher is_negative = Lt(0); pair p('a', true); EXPECT_THAT(p, Key(is_positive)); EXPECT_THAT(p, Not(Key(is_negative))); } TEST(KeyTest, InsideContainsUsingMap) { map container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); EXPECT_THAT(container, Contains(Key(1))); EXPECT_THAT(container, Not(Contains(Key(3)))); } TEST(KeyTest, InsideContainsUsingMultimap) { multimap container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); EXPECT_THAT(container, Not(Contains(Key(25)))); container.insert(make_pair(25, 'd')); EXPECT_THAT(container, Contains(Key(25))); container.insert(make_pair(25, 'e')); EXPECT_THAT(container, Contains(Key(25))); EXPECT_THAT(container, Contains(Key(1))); EXPECT_THAT(container, Not(Contains(Key(3)))); } TEST(PairTest, Typing) { // Test verifies the following type conversions can be compiled. Matcher&> m1 = Pair("foo", 42); Matcher > m2 = Pair("foo", 42); Matcher > m3 = Pair("foo", 42); Matcher > m4 = Pair(25, "42"); Matcher > m5 = Pair("25", 42); } TEST(PairTest, CanDescribeSelf) { Matcher&> m1 = Pair("foo", 42); EXPECT_EQ("has a first field that is equal to \"foo\"" ", and has a second field that is equal to 42", Describe(m1)); EXPECT_EQ("has a first field that isn't equal to \"foo\"" ", or has a second field that isn't equal to 42", DescribeNegation(m1)); // Double and triple negation (1 or 2 times not and description of negation). Matcher&> m2 = Not(Pair(Not(13), 42)); EXPECT_EQ("has a first field that isn't equal to 13" ", and has a second field that is equal to 42", DescribeNegation(m2)); } TEST(PairTest, CanExplainMatchResultTo) { // If neither field matches, Pair() should explain about the first // field. const Matcher > m = Pair(GreaterThan(0), GreaterThan(0)); EXPECT_EQ("whose first field does not match, which is 1 less than 0", Explain(m, make_pair(-1, -2))); // If the first field matches but the second doesn't, Pair() should // explain about the second field. EXPECT_EQ("whose second field does not match, which is 2 less than 0", Explain(m, make_pair(1, -2))); // If the first field doesn't match but the second does, Pair() // should explain about the first field. EXPECT_EQ("whose first field does not match, which is 1 less than 0", Explain(m, make_pair(-1, 2))); // If both fields match, Pair() should explain about them both. EXPECT_EQ("whose both fields match, where the first field is a value " "which is 1 more than 0, and the second field is a value " "which is 2 more than 0", Explain(m, make_pair(1, 2))); // If only the first match has an explanation, only this explanation should // be printed. const Matcher > explain_first = Pair(GreaterThan(0), 0); EXPECT_EQ("whose both fields match, where the first field is a value " "which is 1 more than 0", Explain(explain_first, make_pair(1, 0))); // If only the second match has an explanation, only this explanation should // be printed. const Matcher > explain_second = Pair(0, GreaterThan(0)); EXPECT_EQ("whose both fields match, where the second field is a value " "which is 1 more than 0", Explain(explain_second, make_pair(0, 1))); } TEST(PairTest, MatchesCorrectly) { pair p(25, "foo"); // Both fields match. EXPECT_THAT(p, Pair(25, "foo")); EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o"))); // 'first' doesnt' match, but 'second' matches. EXPECT_THAT(p, Not(Pair(42, "foo"))); EXPECT_THAT(p, Not(Pair(Lt(25), "foo"))); // 'first' matches, but 'second' doesn't match. EXPECT_THAT(p, Not(Pair(25, "bar"))); EXPECT_THAT(p, Not(Pair(25, Not("foo")))); // Neither field matches. EXPECT_THAT(p, Not(Pair(13, "bar"))); EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a")))); } TEST(PairTest, SafelyCastsInnerMatchers) { Matcher is_positive = Gt(0); Matcher is_negative = Lt(0); pair p('a', true); EXPECT_THAT(p, Pair(is_positive, _)); EXPECT_THAT(p, Not(Pair(is_negative, _))); EXPECT_THAT(p, Pair(_, is_positive)); EXPECT_THAT(p, Not(Pair(_, is_negative))); } TEST(PairTest, InsideContainsUsingMap) { map container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); EXPECT_THAT(container, Contains(Pair(1, 'a'))); EXPECT_THAT(container, Contains(Pair(1, _))); EXPECT_THAT(container, Contains(Pair(_, 'a'))); EXPECT_THAT(container, Not(Contains(Pair(3, _)))); } #if GTEST_LANG_CXX11 TEST(PairTest, UseGetInsteadOfMembers) { PairWithGet pair{7, "ABC"}; EXPECT_THAT(pair, Pair(7, "ABC")); EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); } #endif // GTEST_LANG_CXX11 // Tests StartsWith(s). TEST(StartsWithTest, MatchesStringWithGivenPrefix) { const Matcher m1 = StartsWith(std::string("")); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = StartsWith("Hi"); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Hi Hi!")); EXPECT_TRUE(m2.Matches("High")); EXPECT_FALSE(m2.Matches("H")); EXPECT_FALSE(m2.Matches(" Hi")); #if GTEST_HAS_ABSL const Matcher m_empty = StartsWith(""); EXPECT_TRUE(m_empty.Matches(absl::string_view())); EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty"))); #endif // GTEST_HAS_ABSL } TEST(StartsWithTest, CanDescribeSelf) { Matcher m = StartsWith("Hi"); EXPECT_EQ("starts with \"Hi\"", Describe(m)); } // Tests EndsWith(s). TEST(EndsWithTest, MatchesStringWithGivenSuffix) { const Matcher m1 = EndsWith(""); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = EndsWith(std::string("Hi")); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Wow Hi Hi")); EXPECT_TRUE(m2.Matches("Super Hi")); EXPECT_FALSE(m2.Matches("i")); EXPECT_FALSE(m2.Matches("Hi ")); #if GTEST_HAS_GLOBAL_STRING const Matcher m3 = EndsWith(::string("Hi")); EXPECT_TRUE(m3.Matches("Hi")); EXPECT_TRUE(m3.Matches("Wow Hi Hi")); EXPECT_TRUE(m3.Matches("Super Hi")); EXPECT_FALSE(m3.Matches("i")); EXPECT_FALSE(m3.Matches("Hi ")); #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_ABSL const Matcher m4 = EndsWith(""); EXPECT_TRUE(m4.Matches("Hi")); EXPECT_TRUE(m4.Matches("")); EXPECT_TRUE(m4.Matches(absl::string_view())); EXPECT_TRUE(m4.Matches(absl::string_view(""))); #endif // GTEST_HAS_ABSL } TEST(EndsWithTest, CanDescribeSelf) { Matcher m = EndsWith("Hi"); EXPECT_EQ("ends with \"Hi\"", Describe(m)); } // Tests MatchesRegex(). TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { const Matcher m1 = MatchesRegex("a.*z"); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("abcz")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = MatchesRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_FALSE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1az")); #if GTEST_HAS_ABSL const Matcher m3 = MatchesRegex("a.*z"); EXPECT_TRUE(m3.Matches(absl::string_view("az"))); EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); EXPECT_FALSE(m3.Matches(absl::string_view())); const Matcher m4 = MatchesRegex(""); EXPECT_TRUE(m4.Matches(absl::string_view(""))); EXPECT_TRUE(m4.Matches(absl::string_view())); #endif // GTEST_HAS_ABSL } TEST(MatchesRegexTest, CanDescribeSelf) { Matcher m1 = MatchesRegex(std::string("Hi.*")); EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); Matcher m2 = MatchesRegex(new RE("a.*")); EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); #if GTEST_HAS_ABSL Matcher m3 = MatchesRegex(new RE("0.*")); EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); #endif // GTEST_HAS_ABSL } // Tests ContainsRegex(). TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { const Matcher m1 = ContainsRegex(std::string("a.*z")); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("0abcz1")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_TRUE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1a")); #if GTEST_HAS_ABSL const Matcher m3 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); EXPECT_FALSE(m3.Matches(absl::string_view())); const Matcher m4 = ContainsRegex(""); EXPECT_TRUE(m4.Matches(absl::string_view(""))); EXPECT_TRUE(m4.Matches(absl::string_view())); #endif // GTEST_HAS_ABSL } TEST(ContainsRegexTest, CanDescribeSelf) { Matcher m1 = ContainsRegex("Hi.*"); EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); Matcher m2 = ContainsRegex(new RE("a.*")); EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); #if GTEST_HAS_ABSL Matcher m3 = ContainsRegex(new RE("0.*")); EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); #endif // GTEST_HAS_ABSL } // Tests for wide strings. #if GTEST_HAS_STD_WSTRING TEST(StdWideStrEqTest, MatchesEqual) { Matcher m = StrEq(::std::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); EXPECT_FALSE(m2.Matches(L"Hi")); Matcher m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); ::std::wstring str(L"01204500800"); str[3] = L'\0'; Matcher m4 = StrEq(str); EXPECT_TRUE(m4.Matches(str)); str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; Matcher m5 = StrEq(str); EXPECT_TRUE(m5.Matches(str)); } TEST(StdWideStrEqTest, CanDescribeSelf) { Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", Describe(m)); Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2)); ::std::wstring str(L"01204500800"); str[3] = L'\0'; Matcher m4 = StrEq(str); EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; Matcher m5 = StrEq(str); EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); } TEST(StdWideStrNeTest, MatchesUnequalString) { Matcher m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"hello")); EXPECT_FALSE(m2.Matches(L"Hello")); } TEST(StdWideStrNeTest, CanDescribeSelf) { Matcher m = StrNe(L"Hi"); EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); } TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { Matcher m = StrCaseEq(::std::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); EXPECT_FALSE(m2.Matches(L"Hi")); } TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { ::std::wstring str1(L"oabocdooeoo"); ::std::wstring str2(L"OABOCDOOEOO"); Matcher m0 = StrCaseEq(str1); EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); str1[3] = str2[3] = L'\0'; Matcher m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; Matcher m2 = StrCaseEq(str1); str1[9] = str2[9] = L'\0'; EXPECT_FALSE(m2.Matches(str2)); Matcher m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + L"x")); str2.append(1, L'\0'); EXPECT_FALSE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9))); } TEST(StdWideStrCaseEqTest, CanDescribeSelf) { Matcher< ::std::wstring> m = StrCaseEq(L"Hi"); EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); } TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"")); EXPECT_FALSE(m2.Matches(L"Hello")); } TEST(StdWideStrCaseNeTest, CanDescribeSelf) { Matcher m = StrCaseNe(L"Hi"); EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); } // Tests that HasSubstr() works for matching wstring-typed values. TEST(StdWideHasSubstrTest, WorksForStringClasses) { const Matcher< ::std::wstring> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food."))); EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo"))); const Matcher m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food."))); EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo"))); } // Tests that HasSubstr() works for matching C-wide-string-typed values. TEST(StdWideHasSubstrTest, WorksForCStrings) { const Matcher m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast(L"tofo"))); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. TEST(StdWideHasSubstrTest, CanDescribeSelf) { Matcher< ::std::wstring> m = HasSubstr(L"foo\n\""); EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); } // Tests StartsWith(s). TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher m1 = StartsWith(::std::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi Hi!")); EXPECT_TRUE(m2.Matches(L"High")); EXPECT_FALSE(m2.Matches(L"H")); EXPECT_FALSE(m2.Matches(L" Hi")); } TEST(StdWideStartsWithTest, CanDescribeSelf) { Matcher m = StartsWith(L"Hi"); EXPECT_EQ("starts with L\"Hi\"", Describe(m)); } // Tests EndsWith(s). TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = EndsWith(::std::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); EXPECT_TRUE(m2.Matches(L"Super Hi")); EXPECT_FALSE(m2.Matches(L"i")); EXPECT_FALSE(m2.Matches(L"Hi ")); } TEST(StdWideEndsWithTest, CanDescribeSelf) { Matcher m = EndsWith(L"Hi"); EXPECT_EQ("ends with L\"Hi\"", Describe(m)); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING TEST(GlobalWideStrEqTest, MatchesEqual) { Matcher m = StrEq(::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); EXPECT_FALSE(m2.Matches(L"Hi")); Matcher m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); ::wstring str(L"01204500800"); str[3] = L'\0'; Matcher m4 = StrEq(str); EXPECT_TRUE(m4.Matches(str)); str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; Matcher m5 = StrEq(str); EXPECT_TRUE(m5.Matches(str)); } TEST(GlobalWideStrEqTest, CanDescribeSelf) { Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", Describe(m)); Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2)); ::wstring str(L"01204500800"); str[3] = L'\0'; Matcher m4 = StrEq(str); EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; Matcher m5 = StrEq(str); EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); } TEST(GlobalWideStrNeTest, MatchesUnequalString) { Matcher m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"hello")); EXPECT_FALSE(m2.Matches(L"Hello")); } TEST(GlobalWideStrNeTest, CanDescribeSelf) { Matcher m = StrNe(L"Hi"); EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); } TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { Matcher m = StrCaseEq(::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); EXPECT_FALSE(m.Matches(nullptr)); Matcher m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); EXPECT_FALSE(m2.Matches(L"Hi")); } TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { ::wstring str1(L"oabocdooeoo"); ::wstring str2(L"OABOCDOOEOO"); Matcher m0 = StrCaseEq(str1); EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0'))); str1[3] = str2[3] = L'\0'; Matcher m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; Matcher m2 = StrCaseEq(str1); str1[9] = str2[9] = L'\0'; EXPECT_FALSE(m2.Matches(str2)); Matcher m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + L"x")); str2.append(1, L'\0'); EXPECT_FALSE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9))); } TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) { Matcher< ::wstring> m = StrCaseEq(L"Hi"); EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); } TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"")); EXPECT_FALSE(m2.Matches(L"Hello")); } TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) { Matcher m = StrCaseNe(L"Hi"); EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); } // Tests that HasSubstr() works for matching wstring-typed values. TEST(GlobalWideHasSubstrTest, WorksForStringClasses) { const Matcher< ::wstring> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(::wstring(L"I love food."))); EXPECT_FALSE(m1.Matches(::wstring(L"tofo"))); const Matcher m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(::wstring(L"I love food."))); EXPECT_FALSE(m2.Matches(::wstring(L"tofo"))); } // Tests that HasSubstr() works for matching C-wide-string-typed values. TEST(GlobalWideHasSubstrTest, WorksForCStrings) { const Matcher m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast(L"tofo"))); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. TEST(GlobalWideHasSubstrTest, CanDescribeSelf) { Matcher< ::wstring> m = HasSubstr(L"foo\n\""); EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); } // Tests StartsWith(s). TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher m1 = StartsWith(::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi Hi!")); EXPECT_TRUE(m2.Matches(L"High")); EXPECT_FALSE(m2.Matches(L"H")); EXPECT_FALSE(m2.Matches(L" Hi")); } TEST(GlobalWideStartsWithTest, CanDescribeSelf) { Matcher m = StartsWith(L"Hi"); EXPECT_EQ("starts with L\"Hi\"", Describe(m)); } // Tests EndsWith(s). TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); EXPECT_FALSE(m1.Matches(nullptr)); const Matcher m2 = EndsWith(::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); EXPECT_TRUE(m2.Matches(L"Super Hi")); EXPECT_FALSE(m2.Matches(L"i")); EXPECT_FALSE(m2.Matches(L"Hi ")); } TEST(GlobalWideEndsWithTest, CanDescribeSelf) { Matcher m = EndsWith(L"Hi"); EXPECT_EQ("ends with L\"Hi\"", Describe(m)); } #endif // GTEST_HAS_GLOBAL_WSTRING typedef ::std::tuple Tuple2; // NOLINT // Tests that Eq() matches a 2-tuple where the first field == the // second field. TEST(Eq2Test, MatchesEqualArguments) { Matcher m = Eq(); EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); } // Tests that Eq() describes itself properly. TEST(Eq2Test, CanDescribeSelf) { Matcher m = Eq(); EXPECT_EQ("are an equal pair", Describe(m)); } // Tests that Ge() matches a 2-tuple where the first field >= the // second field. TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { Matcher m = Ge(); EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); } // Tests that Ge() describes itself properly. TEST(Ge2Test, CanDescribeSelf) { Matcher m = Ge(); EXPECT_EQ("are a pair where the first >= the second", Describe(m)); } // Tests that Gt() matches a 2-tuple where the first field > the // second field. TEST(Gt2Test, MatchesGreaterThanArguments) { Matcher m = Gt(); EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); } // Tests that Gt() describes itself properly. TEST(Gt2Test, CanDescribeSelf) { Matcher m = Gt(); EXPECT_EQ("are a pair where the first > the second", Describe(m)); } // Tests that Le() matches a 2-tuple where the first field <= the // second field. TEST(Le2Test, MatchesLessThanOrEqualArguments) { Matcher m = Le(); EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); } // Tests that Le() describes itself properly. TEST(Le2Test, CanDescribeSelf) { Matcher m = Le(); EXPECT_EQ("are a pair where the first <= the second", Describe(m)); } // Tests that Lt() matches a 2-tuple where the first field < the // second field. TEST(Lt2Test, MatchesLessThanArguments) { Matcher m = Lt(); EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); } // Tests that Lt() describes itself properly. TEST(Lt2Test, CanDescribeSelf) { Matcher m = Lt(); EXPECT_EQ("are a pair where the first < the second", Describe(m)); } // Tests that Ne() matches a 2-tuple where the first field != the // second field. TEST(Ne2Test, MatchesUnequalArguments) { Matcher m = Ne(); EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); } // Tests that Ne() describes itself properly. TEST(Ne2Test, CanDescribeSelf) { Matcher m = Ne(); EXPECT_EQ("are an unequal pair", Describe(m)); } // Tests that FloatEq() matches a 2-tuple where // FloatEq(first field) matches the second field. TEST(FloatEq2Test, MatchesEqualArguments) { typedef ::std::tuple Tpl; Matcher m = FloatEq(); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); } // Tests that FloatEq() describes itself properly. TEST(FloatEq2Test, CanDescribeSelf) { Matcher&> m = FloatEq(); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that NanSensitiveFloatEq() matches a 2-tuple where // NanSensitiveFloatEq(first field) matches the second field. TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { typedef ::std::tuple Tpl; Matcher m = NanSensitiveFloatEq(); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); } // Tests that NanSensitiveFloatEq() describes itself properly. TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { Matcher&> m = NanSensitiveFloatEq(); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that DoubleEq() matches a 2-tuple where // DoubleEq(first field) matches the second field. TEST(DoubleEq2Test, MatchesEqualArguments) { typedef ::std::tuple Tpl; Matcher m = DoubleEq(); EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); } // Tests that DoubleEq() describes itself properly. TEST(DoubleEq2Test, CanDescribeSelf) { Matcher&> m = DoubleEq(); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that NanSensitiveDoubleEq() matches a 2-tuple where // NanSensitiveDoubleEq(first field) matches the second field. TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { typedef ::std::tuple Tpl; Matcher m = NanSensitiveDoubleEq(); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); } // Tests that DoubleEq() describes itself properly. TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { Matcher&> m = NanSensitiveDoubleEq(); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that FloatEq() matches a 2-tuple where // FloatNear(first field, max_abs_error) matches the second field. TEST(FloatNear2Test, MatchesEqualArguments) { typedef ::std::tuple Tpl; Matcher m = FloatNear(0.5f); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); } // Tests that FloatNear() describes itself properly. TEST(FloatNear2Test, CanDescribeSelf) { Matcher&> m = FloatNear(0.5f); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that NanSensitiveFloatNear() matches a 2-tuple where // NanSensitiveFloatNear(first field) matches the second field. TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { typedef ::std::tuple Tpl; Matcher m = NanSensitiveFloatNear(0.5f); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); } // Tests that NanSensitiveFloatNear() describes itself properly. TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { Matcher&> m = NanSensitiveFloatNear(0.5f); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that FloatEq() matches a 2-tuple where // DoubleNear(first field, max_abs_error) matches the second field. TEST(DoubleNear2Test, MatchesEqualArguments) { typedef ::std::tuple Tpl; Matcher m = DoubleNear(0.5); EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); } // Tests that DoubleNear() describes itself properly. TEST(DoubleNear2Test, CanDescribeSelf) { Matcher&> m = DoubleNear(0.5); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that NanSensitiveDoubleNear() matches a 2-tuple where // NanSensitiveDoubleNear(first field) matches the second field. TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { typedef ::std::tuple Tpl; Matcher m = NanSensitiveDoubleNear(0.5f); EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); } // Tests that NanSensitiveDoubleNear() describes itself properly. TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { Matcher&> m = NanSensitiveDoubleNear(0.5f); EXPECT_EQ("are an almost-equal pair", Describe(m)); } // Tests that Not(m) matches any value that doesn't match m. TEST(NotTest, NegatesMatcher) { Matcher m; m = Not(Eq(2)); EXPECT_TRUE(m.Matches(3)); EXPECT_FALSE(m.Matches(2)); } // Tests that Not(m) describes itself properly. TEST(NotTest, CanDescribeSelf) { Matcher m = Not(Eq(5)); EXPECT_EQ("isn't equal to 5", Describe(m)); } // Tests that monomorphic matchers are safely cast by the Not matcher. TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) { // greater_than_5 is a monomorphic matcher. Matcher greater_than_5 = Gt(5); Matcher m = Not(greater_than_5); Matcher m2 = Not(greater_than_5); Matcher m3 = Not(m); } // Helper to allow easy testing of AllOf matchers with num parameters. void AllOfMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_TRUE(m.Matches(0)); for (int i = 1; i <= num; ++i) { EXPECT_FALSE(m.Matches(i)); } EXPECT_TRUE(m.Matches(num + 1)); } // Tests that AllOf(m1, ..., mn) matches any value that matches all of // the given matchers. TEST(AllOfTest, MatchesWhenAllMatch) { Matcher m; m = AllOf(Le(2), Ge(1)); EXPECT_TRUE(m.Matches(1)); EXPECT_TRUE(m.Matches(2)); EXPECT_FALSE(m.Matches(0)); EXPECT_FALSE(m.Matches(3)); m = AllOf(Gt(0), Ne(1), Ne(2)); EXPECT_TRUE(m.Matches(3)); EXPECT_FALSE(m.Matches(2)); EXPECT_FALSE(m.Matches(1)); EXPECT_FALSE(m.Matches(0)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); EXPECT_TRUE(m.Matches(4)); EXPECT_FALSE(m.Matches(3)); EXPECT_FALSE(m.Matches(2)); EXPECT_FALSE(m.Matches(1)); EXPECT_FALSE(m.Matches(0)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); EXPECT_TRUE(m.Matches(0)); EXPECT_TRUE(m.Matches(1)); EXPECT_FALSE(m.Matches(3)); // The following tests for varying number of sub-matchers. Due to the way // the sub-matchers are handled it is enough to test every sub-matcher once // with sub-matchers using the same matcher type. Varying matcher types are // checked for above. AllOfMatches(2, AllOf(Ne(1), Ne(2))); AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3))); AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4))); AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8))); AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9))); AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10))); AllOfMatches( 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), Ne(50))); } // Tests that AllOf(m1, ..., mn) describes itself properly. TEST(AllOfTest, CanDescribeSelf) { Matcher m; m = AllOf(Le(2), Ge(1)); EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); std::string expected_descr1 = "(is > 0) and (isn't equal to 1) and (isn't equal to 2)"; EXPECT_EQ(expected_descr1, Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); std::string expected_descr2 = "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal " "to 3)"; EXPECT_EQ(expected_descr2, Describe(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); std::string expected_descr3 = "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) " "and (isn't equal to 7)"; EXPECT_EQ(expected_descr3, Describe(m)); } // Tests that AllOf(m1, ..., mn) describes its negation properly. TEST(AllOfTest, CanDescribeNegation) { Matcher m; m = AllOf(Le(2), Ge(1)); std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)"; EXPECT_EQ(expected_descr4, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); std::string expected_descr5 = "(isn't > 0) or (is equal to 1) or (is equal to 2)"; EXPECT_EQ(expected_descr5, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); std::string expected_descr6 = "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)"; EXPECT_EQ(expected_descr6, DescribeNegation(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); std::string expected_desr7 = "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or " "(is equal to 7)"; EXPECT_EQ(expected_desr7, DescribeNegation(m)); m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10), Ne(11)); AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); AllOfMatches(11, m); } // Tests that monomorphic matchers are safely cast by the AllOf matcher. TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) { // greater_than_5 and less_than_10 are monomorphic matchers. Matcher greater_than_5 = Gt(5); Matcher less_than_10 = Lt(10); Matcher m = AllOf(greater_than_5, less_than_10); Matcher m2 = AllOf(greater_than_5, less_than_10); Matcher m3 = AllOf(greater_than_5, m2); // Tests that BothOf works when composing itself. Matcher m4 = AllOf(greater_than_5, less_than_10, less_than_10); Matcher m5 = AllOf(greater_than_5, less_than_10, less_than_10); } TEST(AllOfTest, ExplainsResult) { Matcher m; // Successful match. Both matchers need to explain. The second // matcher doesn't give an explanation, so only the first matcher's // explanation is printed. m = AllOf(GreaterThan(10), Lt(30)); EXPECT_EQ("which is 15 more than 10", Explain(m, 25)); // Successful match. Both matchers need to explain. m = AllOf(GreaterThan(10), GreaterThan(20)); EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20", Explain(m, 30)); // Successful match. All matchers need to explain. The second // matcher doesn't given an explanation. m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20", Explain(m, 25)); // Successful match. All matchers need to explain. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " "and which is 10 more than 30", Explain(m, 40)); // Failed match. The first matcher, which failed, needs to // explain. m = AllOf(GreaterThan(10), GreaterThan(20)); EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); // Failed match. The second matcher, which failed, needs to // explain. Since it doesn't given an explanation, nothing is // printed. m = AllOf(GreaterThan(10), Lt(30)); EXPECT_EQ("", Explain(m, 40)); // Failed match. The second matcher, which failed, needs to // explain. m = AllOf(GreaterThan(10), GreaterThan(20)); EXPECT_EQ("which is 5 less than 20", Explain(m, 15)); } // Helper to allow easy testing of AnyOf matchers with num parameters. static void AnyOfMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { EXPECT_TRUE(m.Matches(i)); } EXPECT_FALSE(m.Matches(num + 1)); } #if GTEST_LANG_CXX11 static void AnyOfStringMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(std::to_string(0))); for (int i = 1; i <= num; ++i) { EXPECT_TRUE(m.Matches(std::to_string(i))); } EXPECT_FALSE(m.Matches(std::to_string(num + 1))); } #endif // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { Matcher m; m = AnyOf(Le(1), Ge(3)); EXPECT_TRUE(m.Matches(1)); EXPECT_TRUE(m.Matches(4)); EXPECT_FALSE(m.Matches(2)); m = AnyOf(Lt(0), Eq(1), Eq(2)); EXPECT_TRUE(m.Matches(-1)); EXPECT_TRUE(m.Matches(1)); EXPECT_TRUE(m.Matches(2)); EXPECT_FALSE(m.Matches(0)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); EXPECT_TRUE(m.Matches(-1)); EXPECT_TRUE(m.Matches(1)); EXPECT_TRUE(m.Matches(2)); EXPECT_TRUE(m.Matches(3)); EXPECT_FALSE(m.Matches(0)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); EXPECT_TRUE(m.Matches(0)); EXPECT_TRUE(m.Matches(11)); EXPECT_TRUE(m.Matches(3)); EXPECT_FALSE(m.Matches(2)); // The following tests for varying number of sub-matchers. Due to the way // the sub-matchers are handled it is enough to test every sub-matcher once // with sub-matchers using the same matcher type. Varying matcher types are // checked for above. AnyOfMatches(2, AnyOf(1, 2)); AnyOfMatches(3, AnyOf(1, 2, 3)); AnyOfMatches(4, AnyOf(1, 2, 3, 4)); AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5)); AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6)); AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7)); AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8)); AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9)); AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); } #if GTEST_LANG_CXX11 // Tests the variadic version of the AnyOfMatcher. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { // Also make sure AnyOf is defined in the right namespace and does not depend // on ADL. Matcher m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); AnyOfMatches(11, m); AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); AnyOfStringMatches( 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50")); } // Tests the variadic version of the ElementsAreMatcher TEST(ElementsAreTest, HugeMatcher) { vector test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; EXPECT_THAT(test_vector, ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); } // Tests the variadic version of the UnorderedElementsAreMatcher TEST(ElementsAreTest, HugeMatcherStr) { vector test_vector{ "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, _, _, _, _, _, _)); } // Tests the variadic version of the UnorderedElementsAreMatcher TEST(ElementsAreTest, HugeMatcherUnordered) { vector test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; EXPECT_THAT(test_vector, UnorderedElementsAre( Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); } #endif // GTEST_LANG_CXX11 // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher m; m = AnyOf(Le(1), Ge(3)); EXPECT_EQ("(is <= 1) or (is >= 3)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)", Describe(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); EXPECT_EQ( "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is " "equal to 7)", Describe(m)); } // Tests that AnyOf(m1, ..., mn) describes its negation properly. TEST(AnyOfTest, CanDescribeNegation) { Matcher m; m = AnyOf(Le(1), Ge(3)); EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)", DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); EXPECT_EQ( "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't " "equal to 3)", DescribeNegation(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); EXPECT_EQ( "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal " "to 5) and (isn't equal to 7)", DescribeNegation(m)); } // Tests that monomorphic matchers are safely cast by the AnyOf matcher. TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) { // greater_than_5 and less_than_10 are monomorphic matchers. Matcher greater_than_5 = Gt(5); Matcher less_than_10 = Lt(10); Matcher m = AnyOf(greater_than_5, less_than_10); Matcher m2 = AnyOf(greater_than_5, less_than_10); Matcher m3 = AnyOf(greater_than_5, m2); // Tests that EitherOf works when composing itself. Matcher m4 = AnyOf(greater_than_5, less_than_10, less_than_10); Matcher m5 = AnyOf(greater_than_5, less_than_10, less_than_10); } TEST(AnyOfTest, ExplainsResult) { Matcher m; // Failed match. Both matchers need to explain. The second // matcher doesn't give an explanation, so only the first matcher's // explanation is printed. m = AnyOf(GreaterThan(10), Lt(0)); EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); // Failed match. Both matchers need to explain. m = AnyOf(GreaterThan(10), GreaterThan(20)); EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20", Explain(m, 5)); // Failed match. All matchers need to explain. The second // matcher doesn't given an explanation. m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30", Explain(m, 5)); // Failed match. All matchers need to explain. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " "and which is 25 less than 30", Explain(m, 5)); // Successful match. The first matcher, which succeeded, needs to // explain. m = AnyOf(GreaterThan(10), GreaterThan(20)); EXPECT_EQ("which is 5 more than 10", Explain(m, 15)); // Successful match. The second matcher, which succeeded, needs to // explain. Since it doesn't given an explanation, nothing is // printed. m = AnyOf(GreaterThan(10), Lt(30)); EXPECT_EQ("", Explain(m, 0)); // Successful match. The second matcher, which succeeded, needs to // explain. m = AnyOf(GreaterThan(30), GreaterThan(20)); EXPECT_EQ("which is 5 more than 20", Explain(m, 25)); } // The following predicate function and predicate functor are for // testing the Truly(predicate) matcher. // Returns non-zero if the input is positive. Note that the return // type of this function is not bool. It's OK as Truly() accepts any // unary function or functor whose return type can be implicitly // converted to bool. int IsPositive(double x) { return x > 0 ? 1 : 0; } // This functor returns true if the input is greater than the given // number. class IsGreaterThan { public: explicit IsGreaterThan(int threshold) : threshold_(threshold) {} bool operator()(int n) const { return n > threshold_; } private: int threshold_; }; // For testing Truly(). const int foo = 0; // This predicate returns true iff the argument references foo and has // a zero value. bool ReferencesFooAndIsZero(const int& n) { return (&n == &foo) && (n == 0); } // Tests that Truly(predicate) matches what satisfies the given // predicate. TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) { Matcher m = Truly(IsPositive); EXPECT_TRUE(m.Matches(2.0)); EXPECT_FALSE(m.Matches(-1.5)); } // Tests that Truly(predicate_functor) works too. TEST(TrulyTest, CanBeUsedWithFunctor) { Matcher m = Truly(IsGreaterThan(5)); EXPECT_TRUE(m.Matches(6)); EXPECT_FALSE(m.Matches(4)); } // A class that can be implicitly converted to bool. class ConvertibleToBool { public: explicit ConvertibleToBool(int number) : number_(number) {} operator bool() const { return number_ != 0; } private: int number_; }; ConvertibleToBool IsNotZero(int number) { return ConvertibleToBool(number); } // Tests that the predicate used in Truly() may return a class that's // implicitly convertible to bool, even when the class has no // operator!(). TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { Matcher m = Truly(IsNotZero); EXPECT_TRUE(m.Matches(1)); EXPECT_FALSE(m.Matches(0)); } // Tests that Truly(predicate) can describe itself properly. TEST(TrulyTest, CanDescribeSelf) { Matcher m = Truly(IsPositive); EXPECT_EQ("satisfies the given predicate", Describe(m)); } // Tests that Truly(predicate) works when the matcher takes its // argument by reference. TEST(TrulyTest, WorksForByRefArguments) { Matcher m = Truly(ReferencesFooAndIsZero); EXPECT_TRUE(m.Matches(foo)); int n = 0; EXPECT_FALSE(m.Matches(n)); } // Tests that Matches(m) is a predicate satisfied by whatever that // matches matcher m. TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) { EXPECT_TRUE(Matches(Ge(0))(1)); EXPECT_FALSE(Matches(Eq('a'))('b')); } // Tests that Matches(m) works when the matcher takes its argument by // reference. TEST(MatchesTest, WorksOnByRefArguments) { int m = 0, n = 0; EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n)); EXPECT_FALSE(Matches(Ref(m))(n)); } // Tests that a Matcher on non-reference type can be used in // Matches(). TEST(MatchesTest, WorksWithMatcherOnNonRefType) { Matcher eq5 = Eq(5); EXPECT_TRUE(Matches(eq5)(5)); EXPECT_FALSE(Matches(eq5)(2)); } // Tests Value(value, matcher). Since Value() is a simple wrapper for // Matches(), which has been tested already, we don't spend a lot of // effort on testing Value(). TEST(ValueTest, WorksWithPolymorphicMatcher) { EXPECT_TRUE(Value("hi", StartsWith("h"))); EXPECT_FALSE(Value(5, Gt(10))); } TEST(ValueTest, WorksWithMonomorphicMatcher) { const Matcher is_zero = Eq(0); EXPECT_TRUE(Value(0, is_zero)); EXPECT_FALSE(Value('a', is_zero)); int n = 0; const Matcher ref_n = Ref(n); EXPECT_TRUE(Value(n, ref_n)); EXPECT_FALSE(Value(1, ref_n)); } TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) { StringMatchResultListener listener1; EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1)); EXPECT_EQ("% 2 == 0", listener1.str()); StringMatchResultListener listener2; EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2)); EXPECT_EQ("", listener2.str()); } TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) { const Matcher is_even = PolymorphicIsEven(); StringMatchResultListener listener1; EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); EXPECT_EQ("% 2 == 0", listener1.str()); const Matcher is_zero = Eq(0); StringMatchResultListener listener2; EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2)); EXPECT_EQ("", listener2.str()); } MATCHER_P(Really, inner_matcher, "") { return ExplainMatchResult(inner_matcher, arg, result_listener); } TEST(ExplainMatchResultTest, WorksInsideMATCHER) { EXPECT_THAT(0, Really(Eq(0))); } TEST(DescribeMatcherTest, WorksWithValue) { EXPECT_EQ("is equal to 42", DescribeMatcher(42)); EXPECT_EQ("isn't equal to 42", DescribeMatcher(42, true)); } TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { const Matcher monomorphic = Le(0); EXPECT_EQ("is <= 0", DescribeMatcher(monomorphic)); EXPECT_EQ("isn't <= 0", DescribeMatcher(monomorphic, true)); } TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { EXPECT_EQ("is even", DescribeMatcher(PolymorphicIsEven())); EXPECT_EQ("is odd", DescribeMatcher(PolymorphicIsEven(), true)); } TEST(AllArgsTest, WorksForTuple) { EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); } TEST(AllArgsTest, WorksForNonTuple) { EXPECT_THAT(42, AllArgs(Gt(0))); EXPECT_THAT('a', Not(AllArgs(Eq('b')))); } class AllArgsHelper { public: AllArgsHelper() {} MOCK_METHOD2(Helper, int(char x, int y)); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); }; TEST(AllArgsTest, WorksInWithClause) { AllArgsHelper helper; ON_CALL(helper, Helper(_, _)) .With(AllArgs(Lt())) .WillByDefault(Return(1)); EXPECT_CALL(helper, Helper(_, _)); EXPECT_CALL(helper, Helper(_, _)) .With(AllArgs(Gt())) .WillOnce(Return(2)); EXPECT_EQ(1, helper.Helper('\1', 2)); EXPECT_EQ(2, helper.Helper('a', 1)); } class OptionalMatchersHelper { public: OptionalMatchersHelper() {} MOCK_METHOD0(NoArgs, int()); MOCK_METHOD1(OneArg, int(int y)); MOCK_METHOD2(TwoArgs, int(char x, int y)); MOCK_METHOD1(Overloaded, int(char x)); MOCK_METHOD2(Overloaded, int(char x, int y)); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); }; TEST(AllArgsTest, WorksWithoutMatchers) { OptionalMatchersHelper helper; ON_CALL(helper, NoArgs).WillByDefault(Return(10)); ON_CALL(helper, OneArg).WillByDefault(Return(20)); ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); EXPECT_EQ(10, helper.NoArgs()); EXPECT_EQ(20, helper.OneArg(1)); EXPECT_EQ(30, helper.TwoArgs('\1', 2)); EXPECT_CALL(helper, NoArgs).Times(1); EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); EXPECT_CALL(helper, TwoArgs).Times(0); EXPECT_EQ(10, helper.NoArgs()); EXPECT_EQ(100, helper.OneArg(1)); EXPECT_EQ(200, helper.OneArg(17)); } // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value // matches the matcher. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { ASSERT_THAT(5, Ge(2)) << "This should succeed."; ASSERT_THAT("Foo", EndsWith("oo")); EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; EXPECT_THAT("Hello", StartsWith("Hell")); } // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value // doesn't match the matcher. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), // which cannot reference auto variables. static unsigned short n; // NOLINT n = 5; // VC++ prior to version 8.0 SP1 has a bug where it will not see any // functions declared in the namespace scope from within nested classes. // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all // namespace-level functions invoked inside them need to be explicitly // resolved. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)), "Value of: n\n" "Expected: is > 10\n" " Actual: 5" + OfType("unsigned short")); n = 0; EXPECT_NONFATAL_FAILURE( EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))), "Value of: n\n" "Expected: (is <= 7) and (is >= 5)\n" " Actual: 0" + OfType("unsigned short")); } // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument // has a reference type. TEST(MatcherAssertionTest, WorksForByRefArguments) { // We use a static variable here as EXPECT_FATAL_FAILURE() cannot // reference auto variables. static int n; n = 0; EXPECT_THAT(n, AllOf(Le(7), Ref(n))); EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), "Value of: n\n" "Expected: does not reference the variable @"); // Tests the "Actual" part. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), "Actual: 0" + OfType("int") + ", which is located @"); } #if !GTEST_OS_SYMBIAN // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is // monomorphic. // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's // Symbian compiler: it tries to compile // template class MatcherCastImpl { ... // virtual bool MatchAndExplain(T x, ...) const { // return source_matcher_.MatchAndExplain(static_cast(x), ...); // with U == string and T == const char* // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... ) // the compiler silently crashes with no output. // If MatcherCastImpl is changed to use U(x) instead of static_cast(x) // the code compiles but the converted string is bogus. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { Matcher starts_with_he = StartsWith("he"); ASSERT_THAT("hello", starts_with_he); Matcher ends_with_ok = EndsWith("ok"); ASSERT_THAT("book", ends_with_ok); const std::string bad = "bad"; EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), "Value of: bad\n" "Expected: ends with \"ok\"\n" " Actual: \"bad\""); Matcher is_greater_than_5 = Gt(5); EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), "Value of: 5\n" "Expected: is > 5\n" " Actual: 5" + OfType("int")); } #endif // !GTEST_OS_SYMBIAN // Tests floating-point matchers. template class FloatingPointTest : public testing::Test { protected: typedef testing::internal::FloatingPoint Floating; typedef typename Floating::Bits Bits; FloatingPointTest() : max_ulps_(Floating::kMaxUlps), zero_bits_(Floating(0).bits()), one_bits_(Floating(1).bits()), infinity_bits_(Floating(Floating::Infinity()).bits()), close_to_positive_zero_( Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), close_to_negative_zero_( -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), further_from_negative_zero_(-Floating::ReinterpretBits( zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), infinity_(Floating::Infinity()), close_to_infinity_( Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), further_from_infinity_( Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), max_(Floating::Max()), nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { } void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } // A battery of tests for FloatingEqMatcher::Matches. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. void TestMatches( testing::internal::FloatingEqMatcher (*matcher_maker)(RawType)) { Matcher m1 = matcher_maker(0.0); EXPECT_TRUE(m1.Matches(-0.0)); EXPECT_TRUE(m1.Matches(close_to_positive_zero_)); EXPECT_TRUE(m1.Matches(close_to_negative_zero_)); EXPECT_FALSE(m1.Matches(1.0)); Matcher m2 = matcher_maker(close_to_positive_zero_); EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); Matcher m3 = matcher_maker(1.0); EXPECT_TRUE(m3.Matches(close_to_one_)); EXPECT_FALSE(m3.Matches(further_from_one_)); // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above. EXPECT_FALSE(m3.Matches(0.0)); Matcher m4 = matcher_maker(-infinity_); EXPECT_TRUE(m4.Matches(-close_to_infinity_)); Matcher m5 = matcher_maker(infinity_); EXPECT_TRUE(m5.Matches(close_to_infinity_)); // This is interesting as the representations of infinity_ and nan1_ // are only 1 DLP apart. EXPECT_FALSE(m5.Matches(nan1_)); // matcher_maker can produce a Matcher, which is needed in // some cases. Matcher m6 = matcher_maker(0.0); EXPECT_TRUE(m6.Matches(-0.0)); EXPECT_TRUE(m6.Matches(close_to_positive_zero_)); EXPECT_FALSE(m6.Matches(1.0)); // matcher_maker can produce a Matcher, which is needed in some // cases. Matcher m7 = matcher_maker(0.0); RawType x = 0.0; EXPECT_TRUE(m7.Matches(x)); x = 0.01f; EXPECT_FALSE(m7.Matches(x)); } // Pre-calculated numbers to be used by the tests. const Bits max_ulps_; const Bits zero_bits_; // The bits that represent 0.0. const Bits one_bits_; // The bits that represent 1.0. const Bits infinity_bits_; // The bits that represent +infinity. // Some numbers close to 0.0. const RawType close_to_positive_zero_; const RawType close_to_negative_zero_; const RawType further_from_negative_zero_; // Some numbers close to 1.0. const RawType close_to_one_; const RawType further_from_one_; // Some numbers close to +infinity. const RawType infinity_; const RawType close_to_infinity_; const RawType further_from_infinity_; // Maximum representable value that's not infinity. const RawType max_; // Some NaNs. const RawType nan1_; const RawType nan2_; }; // Tests floating-point matchers with fixed epsilons. template class FloatingPointNearTest : public FloatingPointTest { protected: typedef FloatingPointTest ParentType; // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. void TestNearMatches( testing::internal::FloatingEqMatcher (*matcher_maker)(RawType, RawType)) { Matcher m1 = matcher_maker(0.0, 0.0); EXPECT_TRUE(m1.Matches(0.0)); EXPECT_TRUE(m1.Matches(-0.0)); EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_)); EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_)); EXPECT_FALSE(m1.Matches(1.0)); Matcher m2 = matcher_maker(0.0, 1.0); EXPECT_TRUE(m2.Matches(0.0)); EXPECT_TRUE(m2.Matches(-0.0)); EXPECT_TRUE(m2.Matches(1.0)); EXPECT_TRUE(m2.Matches(-1.0)); EXPECT_FALSE(m2.Matches(ParentType::close_to_one_)); EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_)); // Check that inf matches inf, regardless of the of the specified max // absolute error. Matcher m3 = matcher_maker(ParentType::infinity_, 0.0); EXPECT_TRUE(m3.Matches(ParentType::infinity_)); EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_)); EXPECT_FALSE(m3.Matches(-ParentType::infinity_)); Matcher m4 = matcher_maker(-ParentType::infinity_, 0.0); EXPECT_TRUE(m4.Matches(-ParentType::infinity_)); EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_)); EXPECT_FALSE(m4.Matches(ParentType::infinity_)); // Test various overflow scenarios. Matcher m5 = matcher_maker(ParentType::max_, ParentType::max_); EXPECT_TRUE(m5.Matches(ParentType::max_)); EXPECT_FALSE(m5.Matches(-ParentType::max_)); Matcher m6 = matcher_maker(-ParentType::max_, ParentType::max_); EXPECT_FALSE(m6.Matches(ParentType::max_)); EXPECT_TRUE(m6.Matches(-ParentType::max_)); Matcher m7 = matcher_maker(ParentType::max_, 0); EXPECT_TRUE(m7.Matches(ParentType::max_)); EXPECT_FALSE(m7.Matches(-ParentType::max_)); Matcher m8 = matcher_maker(-ParentType::max_, 0); EXPECT_FALSE(m8.Matches(ParentType::max_)); EXPECT_TRUE(m8.Matches(-ParentType::max_)); // The difference between max() and -max() normally overflows to infinity, // but it should still match if the max_abs_error is also infinity. Matcher m9 = matcher_maker( ParentType::max_, ParentType::infinity_); EXPECT_TRUE(m8.Matches(-ParentType::max_)); // matcher_maker can produce a Matcher, which is needed in // some cases. Matcher m10 = matcher_maker(0.0, 1.0); EXPECT_TRUE(m10.Matches(-0.0)); EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_)); EXPECT_FALSE(m10.Matches(ParentType::close_to_one_)); // matcher_maker can produce a Matcher, which is needed in some // cases. Matcher m11 = matcher_maker(0.0, 1.0); RawType x = 0.0; EXPECT_TRUE(m11.Matches(x)); x = 1.0f; EXPECT_TRUE(m11.Matches(x)); x = -1.0f; EXPECT_TRUE(m11.Matches(x)); x = 1.1f; EXPECT_FALSE(m11.Matches(x)); x = -1.1f; EXPECT_FALSE(m11.Matches(x)); } }; // Instantiate FloatingPointTest for testing floats. typedef FloatingPointTest FloatTest; TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { TestMatches(&FloatEq); } TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { TestMatches(&NanSensitiveFloatEq); } TEST_F(FloatTest, FloatEqCannotMatchNaN) { // FloatEq never matches NaN. Matcher m = FloatEq(nan1_); EXPECT_FALSE(m.Matches(nan1_)); EXPECT_FALSE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) { // NanSensitiveFloatEq will match NaN. Matcher m = NanSensitiveFloatEq(nan1_); EXPECT_TRUE(m.Matches(nan1_)); EXPECT_TRUE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(FloatTest, FloatEqCanDescribeSelf) { Matcher m1 = FloatEq(2.0f); EXPECT_EQ("is approximately 2", Describe(m1)); EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); Matcher m2 = FloatEq(0.5f); EXPECT_EQ("is approximately 0.5", Describe(m2)); EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); Matcher m3 = FloatEq(nan1_); EXPECT_EQ("never matches", Describe(m3)); EXPECT_EQ("is anything", DescribeNegation(m3)); } TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { Matcher m1 = NanSensitiveFloatEq(2.0f); EXPECT_EQ("is approximately 2", Describe(m1)); EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); Matcher m2 = NanSensitiveFloatEq(0.5f); EXPECT_EQ("is approximately 0.5", Describe(m2)); EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); Matcher m3 = NanSensitiveFloatEq(nan1_); EXPECT_EQ("is NaN", Describe(m3)); EXPECT_EQ("isn't NaN", DescribeNegation(m3)); } // Instantiate FloatingPointTest for testing floats with a user-specified // max absolute error. typedef FloatingPointNearTest FloatNearTest; TEST_F(FloatNearTest, FloatNearMatches) { TestNearMatches(&FloatNear); } TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { TestNearMatches(&NanSensitiveFloatNear); } TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { Matcher m1 = FloatNear(2.0f, 0.5f); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); EXPECT_EQ( "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); Matcher m2 = FloatNear(0.5f, 0.5f); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); EXPECT_EQ( "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); Matcher m3 = FloatNear(nan1_, 0.0); EXPECT_EQ("never matches", Describe(m3)); EXPECT_EQ("is anything", DescribeNegation(m3)); } TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { Matcher m1 = NanSensitiveFloatNear(2.0f, 0.5f); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); EXPECT_EQ( "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); Matcher m2 = NanSensitiveFloatNear(0.5f, 0.5f); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); EXPECT_EQ( "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); Matcher m3 = NanSensitiveFloatNear(nan1_, 0.1f); EXPECT_EQ("is NaN", Describe(m3)); EXPECT_EQ("isn't NaN", DescribeNegation(m3)); } TEST_F(FloatNearTest, FloatNearCannotMatchNaN) { // FloatNear never matches NaN. Matcher m = FloatNear(ParentType::nan1_, 0.1f); EXPECT_FALSE(m.Matches(nan1_)); EXPECT_FALSE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) { // NanSensitiveFloatNear will match NaN. Matcher m = NanSensitiveFloatNear(nan1_, 0.1f); EXPECT_TRUE(m.Matches(nan1_)); EXPECT_TRUE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } // Instantiate FloatingPointTest for testing doubles. typedef FloatingPointTest DoubleTest; TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { TestMatches(&DoubleEq); } TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { TestMatches(&NanSensitiveDoubleEq); } TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { // DoubleEq never matches NaN. Matcher m = DoubleEq(nan1_); EXPECT_FALSE(m.Matches(nan1_)); EXPECT_FALSE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) { // NanSensitiveDoubleEq will match NaN. Matcher m = NanSensitiveDoubleEq(nan1_); EXPECT_TRUE(m.Matches(nan1_)); EXPECT_TRUE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { Matcher m1 = DoubleEq(2.0); EXPECT_EQ("is approximately 2", Describe(m1)); EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); Matcher m2 = DoubleEq(0.5); EXPECT_EQ("is approximately 0.5", Describe(m2)); EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); Matcher m3 = DoubleEq(nan1_); EXPECT_EQ("never matches", Describe(m3)); EXPECT_EQ("is anything", DescribeNegation(m3)); } TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { Matcher m1 = NanSensitiveDoubleEq(2.0); EXPECT_EQ("is approximately 2", Describe(m1)); EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); Matcher m2 = NanSensitiveDoubleEq(0.5); EXPECT_EQ("is approximately 0.5", Describe(m2)); EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); Matcher m3 = NanSensitiveDoubleEq(nan1_); EXPECT_EQ("is NaN", Describe(m3)); EXPECT_EQ("isn't NaN", DescribeNegation(m3)); } // Instantiate FloatingPointTest for testing floats with a user-specified // max absolute error. typedef FloatingPointNearTest DoubleNearTest; TEST_F(DoubleNearTest, DoubleNearMatches) { TestNearMatches(&DoubleNear); } TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { TestNearMatches(&NanSensitiveDoubleNear); } TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { Matcher m1 = DoubleNear(2.0, 0.5); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); EXPECT_EQ( "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); Matcher m2 = DoubleNear(0.5, 0.5); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); EXPECT_EQ( "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); Matcher m3 = DoubleNear(nan1_, 0.0); EXPECT_EQ("never matches", Describe(m3)); EXPECT_EQ("is anything", DescribeNegation(m3)); } TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05)); EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); const std::string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); // Different C++ implementations may print floating-point numbers // slightly differently. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC explanation == "which is 1.2e-010 from 2.1") // MSVC << " where explanation is \"" << explanation << "\"."; } TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { Matcher m1 = NanSensitiveDoubleNear(2.0, 0.5); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); EXPECT_EQ( "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); Matcher m2 = NanSensitiveDoubleNear(0.5, 0.5); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); EXPECT_EQ( "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); Matcher m3 = NanSensitiveDoubleNear(nan1_, 0.1); EXPECT_EQ("is NaN", Describe(m3)); EXPECT_EQ("isn't NaN", DescribeNegation(m3)); } TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) { // DoubleNear never matches NaN. Matcher m = DoubleNear(ParentType::nan1_, 0.1); EXPECT_FALSE(m.Matches(nan1_)); EXPECT_FALSE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) { // NanSensitiveDoubleNear will match NaN. Matcher m = NanSensitiveDoubleNear(nan1_, 0.1); EXPECT_TRUE(m.Matches(nan1_)); EXPECT_TRUE(m.Matches(nan2_)); EXPECT_FALSE(m.Matches(1.0)); } TEST(PointeeTest, RawPointer) { const Matcher m = Pointee(Ge(0)); int n = 1; EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, RawPointerToConst) { const Matcher m = Pointee(Ge(0)); double x = 1; EXPECT_TRUE(m.Matches(&x)); x = -1; EXPECT_FALSE(m.Matches(&x)); EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToConstRawPointer) { const Matcher m = Pointee(Ge(0)); int n = 1; EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToNonConstRawPointer) { const Matcher m = Pointee(Ge(0)); double x = 1.0; double* p = &x; EXPECT_TRUE(m.Matches(p)); x = -1; EXPECT_FALSE(m.Matches(p)); p = nullptr; EXPECT_FALSE(m.Matches(p)); } MATCHER_P(FieldIIs, inner_matcher, "") { return ExplainMatchResult(inner_matcher, arg.i, result_listener); } #if GTEST_HAS_RTTI TEST(WhenDynamicCastToTest, SameType) { Derived derived; derived.i = 4; // Right type. A pointer is passed down. Base* as_base_ptr = &derived; EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Not(IsNull()))); EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Pointee(FieldIIs(4)))); EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(FieldIIs(5))))); } TEST(WhenDynamicCastToTest, WrongTypes) { Base base; Derived derived; OtherDerived other_derived; // Wrong types. NULL is passed. EXPECT_THAT(&base, Not(WhenDynamicCastTo(Pointee(_)))); EXPECT_THAT(&base, WhenDynamicCastTo(IsNull())); Base* as_base_ptr = &derived; EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); as_base_ptr = &other_derived; EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); } TEST(WhenDynamicCastToTest, AlreadyNull) { // Already NULL. Base* as_base_ptr = nullptr; EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); } struct AmbiguousCastTypes { class VirtualDerived : public virtual Base {}; class DerivedSub1 : public VirtualDerived {}; class DerivedSub2 : public VirtualDerived {}; class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {}; }; TEST(WhenDynamicCastToTest, AmbiguousCast) { AmbiguousCastTypes::DerivedSub1 sub1; AmbiguousCastTypes::ManyDerivedInHierarchy many_derived; // Multiply derived from Base. dynamic_cast<> returns NULL. Base* as_base_ptr = static_cast(&many_derived); EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); as_base_ptr = &sub1; EXPECT_THAT( as_base_ptr, WhenDynamicCastTo(Not(IsNull()))); } TEST(WhenDynamicCastToTest, Describe) { Matcher matcher = WhenDynamicCastTo(Pointee(_)); const std::string prefix = "when dynamic_cast to " + internal::GetTypeName() + ", "; EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); EXPECT_EQ(prefix + "does not point to a value that is anything", DescribeNegation(matcher)); } TEST(WhenDynamicCastToTest, Explain) { Matcher matcher = WhenDynamicCastTo(Pointee(_)); Base* null = nullptr; EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL")); Derived derived; EXPECT_TRUE(matcher.Matches(&derived)); EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to ")); // With references, the matcher itself can fail. Test for that one. Matcher ref_matcher = WhenDynamicCastTo(_); EXPECT_THAT(Explain(ref_matcher, derived), HasSubstr("which cannot be dynamic_cast")); } TEST(WhenDynamicCastToTest, GoodReference) { Derived derived; derived.i = 4; Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, WhenDynamicCastTo(FieldIIs(4))); EXPECT_THAT(as_base_ref, WhenDynamicCastTo(Not(FieldIIs(5)))); } TEST(WhenDynamicCastToTest, BadReference) { Derived derived; Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); } #endif // GTEST_HAS_RTTI // Minimal const-propagating pointer. template class ConstPropagatingPtr { public: typedef T element_type; ConstPropagatingPtr() : val_() {} explicit ConstPropagatingPtr(T* t) : val_(t) {} ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} T* get() { return val_; } T& operator*() { return *val_; } // Most smart pointers return non-const T* and T& from the next methods. const T* get() const { return val_; } const T& operator*() const { return *val_; } private: T* val_; }; TEST(PointeeTest, WorksWithConstPropagatingPointers) { const Matcher< ConstPropagatingPtr > m = Pointee(Lt(5)); int three = 3; const ConstPropagatingPtr co(&three); ConstPropagatingPtr o(&three); EXPECT_TRUE(m.Matches(o)); EXPECT_TRUE(m.Matches(co)); *o = 6; EXPECT_FALSE(m.Matches(o)); EXPECT_FALSE(m.Matches(ConstPropagatingPtr())); } TEST(PointeeTest, NeverMatchesNull) { const Matcher m = Pointee(_); EXPECT_FALSE(m.Matches(nullptr)); } // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). TEST(PointeeTest, MatchesAgainstAValue) { const Matcher m = Pointee(5); int n = 5; EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, CanDescribeSelf) { const Matcher m = Pointee(Gt(3)); EXPECT_EQ("points to a value that is > 3", Describe(m)); EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m)); } TEST(PointeeTest, CanExplainMatchResult) { const Matcher m = Pointee(StartsWith("Hi")); EXPECT_EQ("", Explain(m, static_cast(nullptr))); const Matcher m2 = Pointee(GreaterThan(1)); // NOLINT long n = 3; // NOLINT EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", Explain(m2, &n)); } TEST(PointeeTest, AlwaysExplainsPointee) { const Matcher m = Pointee(0); int n = 42; EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); } // An uncopyable class. class Uncopyable { public: Uncopyable() : value_(-1) {} explicit Uncopyable(int a_value) : value_(a_value) {} int value() const { return value_; } void set_value(int i) { value_ = i; } private: int value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); }; // Returns true iff x.value() is positive. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } MATCHER_P(UncopyableIs, inner_matcher, "") { return ExplainMatchResult(inner_matcher, arg.value(), result_listener); } // A user-defined struct for testing Field(). struct AStruct { AStruct() : x(0), y(1.0), z(5), p(nullptr) {} AStruct(const AStruct& rhs) : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} int x; // A non-const field. const double y; // A const field. Uncopyable z; // An uncopyable field. const char* p; // A pointer field. private: GTEST_DISALLOW_ASSIGN_(AStruct); }; // A derived struct for testing Field(). struct DerivedStruct : public AStruct { char ch; private: GTEST_DISALLOW_ASSIGN_(DerivedStruct); }; // Tests that Field(&Foo::field, ...) works when field is non-const. TEST(FieldTest, WorksForNonConstField) { Matcher m = Field(&AStruct::x, Ge(0)); Matcher m_with_name = Field("x", &AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is const. TEST(FieldTest, WorksForConstField) { AStruct a; Matcher m = Field(&AStruct::y, Ge(0.0)); Matcher m_with_name = Field("y", &AStruct::y, Ge(0.0)); EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); m = Field(&AStruct::y, Le(0.0)); m_with_name = Field("y", &AStruct::y, Le(0.0)); EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is not copyable. TEST(FieldTest, WorksForUncopyableField) { AStruct a; Matcher m = Field(&AStruct::z, Truly(ValueIsPositive)); EXPECT_TRUE(m.Matches(a)); m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); EXPECT_FALSE(m.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is a pointer. TEST(FieldTest, WorksForPointerField) { // Matching against NULL. Matcher m = Field(&AStruct::p, static_cast(nullptr)); AStruct a; EXPECT_TRUE(m.Matches(a)); a.p = "hi"; EXPECT_FALSE(m.Matches(a)); // Matching a pointer that is not NULL. m = Field(&AStruct::p, StartsWith("hi")); a.p = "hill"; EXPECT_TRUE(m.Matches(a)); a.p = "hole"; EXPECT_FALSE(m.Matches(a)); } // Tests that Field() works when the object is passed by reference. TEST(FieldTest, WorksForByRefArgument) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); } // Tests that Field(&Foo::field, ...) works when the argument's type // is a sub-type of Foo. TEST(FieldTest, WorksForArgumentOfSubType) { // Note that the matcher expects DerivedStruct but we say AStruct // inside Field(). Matcher m = Field(&AStruct::x, Ge(0)); DerivedStruct d; EXPECT_TRUE(m.Matches(d)); d.x = -1; EXPECT_FALSE(m.Matches(d)); } // Tests that Field(&Foo::field, m) works when field's type and m's // argument type are compatible but not the same. TEST(FieldTest, WorksForCompatibleMatcherType) { // The field is an int, but the inner matcher expects a signed char. Matcher m = Field(&AStruct::x, Matcher(Ge(0))); AStruct a; EXPECT_TRUE(m.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); } // Tests that Field() can describe itself. TEST(FieldTest, CanDescribeSelf) { Matcher m = Field(&AStruct::x, Ge(0)); EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } TEST(FieldTest, CanDescribeSelfWithFieldName) { Matcher m = Field("field_name", &AStruct::x, Ge(0)); EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); EXPECT_EQ("is an object whose field `field_name` isn't >= 0", DescribeNegation(m)); } // Tests that Field() can explain the match result. TEST(FieldTest, CanExplainMatchResult) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; a.x = 1; EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a)); m = Field(&AStruct::x, GreaterThan(0)); EXPECT_EQ( "whose given field is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, a)); } TEST(FieldTest, CanExplainMatchResultWithFieldName) { Matcher m = Field("field_name", &AStruct::x, Ge(0)); AStruct a; a.x = 1; EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); m = Field("field_name", &AStruct::x, GreaterThan(0)); EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, a)); } // Tests that Field() works when the argument is a pointer to const. TEST(FieldForPointerTest, WorksForPointerToConst) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(&a)); a.x = -1; EXPECT_FALSE(m.Matches(&a)); } // Tests that Field() works when the argument is a pointer to non-const. TEST(FieldForPointerTest, WorksForPointerToNonConst) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(&a)); a.x = -1; EXPECT_FALSE(m.Matches(&a)); } // Tests that Field() works when the argument is a reference to a const pointer. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(&a)); a.x = -1; EXPECT_FALSE(m.Matches(&a)); } // Tests that Field() does not match the NULL pointer. TEST(FieldForPointerTest, DoesNotMatchNull) { Matcher m = Field(&AStruct::x, _); EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Field(&Foo::field, ...) works when the argument's type // is a sub-type of const Foo*. TEST(FieldForPointerTest, WorksForArgumentOfSubType) { // Note that the matcher expects DerivedStruct but we say AStruct // inside Field(). Matcher m = Field(&AStruct::x, Ge(0)); DerivedStruct d; EXPECT_TRUE(m.Matches(&d)); d.x = -1; EXPECT_FALSE(m.Matches(&d)); } // Tests that Field() can describe itself when used to match a pointer. TEST(FieldForPointerTest, CanDescribeSelf) { Matcher m = Field(&AStruct::x, Ge(0)); EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { Matcher m = Field("field_name", &AStruct::x, Ge(0)); EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); EXPECT_EQ("is an object whose field `field_name` isn't >= 0", DescribeNegation(m)); } // Tests that Field() can explain the result of matching a pointer. TEST(FieldForPointerTest, CanExplainMatchResult) { Matcher m = Field(&AStruct::x, Ge(0)); AStruct a; a.x = 1; EXPECT_EQ("", Explain(m, static_cast(nullptr))); EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), Explain(m, &a)); m = Field(&AStruct::x, GreaterThan(0)); EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, &a)); } TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { Matcher m = Field("field_name", &AStruct::x, Ge(0)); AStruct a; a.x = 1; EXPECT_EQ("", Explain(m, static_cast(nullptr))); EXPECT_EQ( "which points to an object whose field `field_name` is 1" + OfType("int"), Explain(m, &a)); m = Field("field_name", &AStruct::x, GreaterThan(0)); EXPECT_EQ("which points to an object whose field `field_name` is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, &a)); } // A user-defined class for testing Property(). class AClass { public: AClass() : n_(0) {} // A getter that returns a non-reference. int n() const { return n_; } void set_n(int new_n) { n_ = new_n; } // A getter that returns a reference to const. const std::string& s() const { return s_; } #if GTEST_LANG_CXX11 const std::string& s_ref() const & { return s_; } #endif void set_s(const std::string& new_s) { s_ = new_s; } // A getter that returns a reference to non-const. double& x() const { return x_; } private: int n_; std::string s_; static double x_; }; double AClass::x_ = 0.0; // A derived class for testing Property(). class DerivedClass : public AClass { public: int k() const { return k_; } private: int k_; }; // Tests that Property(&Foo::property, ...) works when property() // returns a non-reference. TEST(PropertyTest, WorksForNonReferenceProperty) { Matcher m = Property(&AClass::n, Ge(0)); Matcher m_with_name = Property("n", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property(&Foo::property, ...) works when property() // returns a reference to const. TEST(PropertyTest, WorksForReferenceToConstProperty) { Matcher m = Property(&AClass::s, StartsWith("hi")); Matcher m_with_name = Property("s", &AClass::s, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } #if GTEST_LANG_CXX11 // Tests that Property(&Foo::property, ...) works when property() is // ref-qualified. TEST(PropertyTest, WorksForRefQualifiedProperty) { Matcher m = Property(&AClass::s_ref, StartsWith("hi")); Matcher m_with_name = Property("s", &AClass::s_ref, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } #endif // Tests that Property(&Foo::property, ...) works when property() // returns a reference to non-const. TEST(PropertyTest, WorksForReferenceToNonConstProperty) { double x = 0.0; AClass a; Matcher m = Property(&AClass::x, Ref(x)); EXPECT_FALSE(m.Matches(a)); m = Property(&AClass::x, Not(Ref(x))); EXPECT_TRUE(m.Matches(a)); } // Tests that Property(&Foo::property, ...) works when the argument is // passed by value. TEST(PropertyTest, WorksForByValueArgument) { Matcher m = Property(&AClass::s, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); } // Tests that Property(&Foo::property, ...) works when the argument's // type is a sub-type of Foo. TEST(PropertyTest, WorksForArgumentOfSubType) { // The matcher expects a DerivedClass, but inside the Property() we // say AClass. Matcher m = Property(&AClass::n, Ge(0)); DerivedClass d; d.set_n(1); EXPECT_TRUE(m.Matches(d)); d.set_n(-1); EXPECT_FALSE(m.Matches(d)); } // Tests that Property(&Foo::property, m) works when property()'s type // and m's argument type are compatible but different. TEST(PropertyTest, WorksForCompatibleMatcherType) { // n() returns an int but the inner matcher expects a signed char. Matcher m = Property(&AClass::n, Matcher(Ge(0))); Matcher m_with_name = Property("n", &AClass::n, Matcher(Ge(0))); AClass a; EXPECT_TRUE(m.Matches(a)); EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property() can describe itself. TEST(PropertyTest, CanDescribeSelf) { Matcher m = Property(&AClass::n, Ge(0)); EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); EXPECT_EQ("is an object whose given property isn't >= 0", DescribeNegation(m)); } TEST(PropertyTest, CanDescribeSelfWithPropertyName) { Matcher m = Property("fancy_name", &AClass::n, Ge(0)); EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", DescribeNegation(m)); } // Tests that Property() can explain the match result. TEST(PropertyTest, CanExplainMatchResult) { Matcher m = Property(&AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a)); m = Property(&AClass::n, GreaterThan(0)); EXPECT_EQ( "whose given property is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, a)); } TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { Matcher m = Property("fancy_name", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); m = Property("fancy_name", &AClass::n, GreaterThan(0)); EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, a)); } // Tests that Property() works when the argument is a pointer to const. TEST(PropertyForPointerTest, WorksForPointerToConst) { Matcher m = Property(&AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_TRUE(m.Matches(&a)); a.set_n(-1); EXPECT_FALSE(m.Matches(&a)); } // Tests that Property() works when the argument is a pointer to non-const. TEST(PropertyForPointerTest, WorksForPointerToNonConst) { Matcher m = Property(&AClass::s, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(&a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(&a)); } // Tests that Property() works when the argument is a reference to a // const pointer. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { Matcher m = Property(&AClass::s, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(&a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(&a)); } // Tests that Property() does not match the NULL pointer. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { Matcher m = Property(&AClass::x, _); EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Property(&Foo::property, ...) works when the argument's // type is a sub-type of const Foo*. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { // The matcher expects a DerivedClass, but inside the Property() we // say AClass. Matcher m = Property(&AClass::n, Ge(0)); DerivedClass d; d.set_n(1); EXPECT_TRUE(m.Matches(&d)); d.set_n(-1); EXPECT_FALSE(m.Matches(&d)); } // Tests that Property() can describe itself when used to match a pointer. TEST(PropertyForPointerTest, CanDescribeSelf) { Matcher m = Property(&AClass::n, Ge(0)); EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); EXPECT_EQ("is an object whose given property isn't >= 0", DescribeNegation(m)); } TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { Matcher m = Property("fancy_name", &AClass::n, Ge(0)); EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", DescribeNegation(m)); } // Tests that Property() can explain the result of matching a pointer. TEST(PropertyForPointerTest, CanExplainMatchResult) { Matcher m = Property(&AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_EQ("", Explain(m, static_cast(nullptr))); EXPECT_EQ( "which points to an object whose given property is 1" + OfType("int"), Explain(m, &a)); m = Property(&AClass::n, GreaterThan(0)); EXPECT_EQ("which points to an object whose given property is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, &a)); } TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { Matcher m = Property("fancy_name", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_EQ("", Explain(m, static_cast(nullptr))); EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + OfType("int"), Explain(m, &a)); m = Property("fancy_name", &AClass::n, GreaterThan(0)); EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + OfType("int") + ", which is 1 more than 0", Explain(m, &a)); } // Tests ResultOf. // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function pointer. std::string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; } TEST(ResultOfTest, WorksForFunctionPointers) { Matcher matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf() can describe itself. TEST(ResultOfTest, CanDescribeItself) { Matcher matcher = ResultOf(&IntToStringFunction, StrEq("foo")); EXPECT_EQ("is mapped by the given callable to a value that " "is equal to \"foo\"", Describe(matcher)); EXPECT_EQ("is mapped by the given callable to a value that " "isn't equal to \"foo\"", DescribeNegation(matcher)); } // Tests that ResultOf() can explain the match result. int IntFunction(int input) { return input == 42 ? 80 : 90; } TEST(ResultOfTest, CanExplainMatchResult) { Matcher matcher = ResultOf(&IntFunction, Ge(85)); EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"), Explain(matcher, 36)); matcher = ResultOf(&IntFunction, GreaterThan(85)); EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + ", which is 5 more than 85", Explain(matcher, 36)); } // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a non-reference. TEST(ResultOfTest, WorksForNonReferenceResults) { Matcher matcher = ResultOf(&IntFunction, Eq(80)); EXPECT_TRUE(matcher.Matches(42)); EXPECT_FALSE(matcher.Matches(36)); } // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a reference to non-const. double& DoubleFunction(double& input) { return input; } // NOLINT Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT return obj; } TEST(ResultOfTest, WorksForReferenceToNonConstResults) { double x = 3.14; double x2 = x; Matcher matcher = ResultOf(&DoubleFunction, Ref(x)); EXPECT_TRUE(matcher.Matches(x)); EXPECT_FALSE(matcher.Matches(x2)); // Test that ResultOf works with uncopyable objects Uncopyable obj(0); Uncopyable obj2(0); Matcher matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj)); EXPECT_TRUE(matcher2.Matches(obj)); EXPECT_FALSE(matcher2.Matches(obj2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a reference to const. const std::string& StringFunction(const std::string& input) { return input; } TEST(ResultOfTest, WorksForReferenceToConstResults) { std::string s = "foo"; std::string s2 = s; Matcher matcher = ResultOf(&StringFunction, Ref(s)); EXPECT_TRUE(matcher.Matches(s)); EXPECT_FALSE(matcher.Matches(s2)); } // Tests that ResultOf(f, m) works when f(x) and m's // argument types are compatible but different. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { // IntFunction() returns int but the inner matcher expects a signed char. Matcher matcher = ResultOf(IntFunction, Matcher(Ge(85))); EXPECT_TRUE(matcher.Matches(36)); EXPECT_FALSE(matcher.Matches(42)); } // Tests that the program aborts when ResultOf is passed // a NULL function pointer. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { EXPECT_DEATH_IF_SUPPORTED( ResultOf(static_cast(nullptr), Eq(std::string("foo"))), "NULL function pointer is passed into ResultOf\\(\\)\\."); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function reference. TEST(ResultOfTest, WorksForFunctionReferences) { Matcher matcher = ResultOf(IntToStringFunction, StrEq("foo")); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function object. struct Functor : public ::std::unary_function { result_type operator()(argument_type input) const { return IntToStringFunction(input); } }; TEST(ResultOfTest, WorksForFunctors) { Matcher matcher = ResultOf(Functor(), Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a // functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; int operator()(int n) { return n; } int operator()(const char* s) { return static_cast(strlen(s)); } std::string operator()(int *p) { return p ? "good ptr" : "null"; } }; TEST(ResultOfTest, WorksForPolymorphicFunctors) { Matcher matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); EXPECT_TRUE(matcher_int.Matches(10)); EXPECT_FALSE(matcher_int.Matches(2)); Matcher matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); EXPECT_TRUE(matcher_string.Matches("long string")); EXPECT_FALSE(matcher_string.Matches("shrt")); } #if GTEST_LANG_CXX11 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); int n = 0; EXPECT_TRUE(matcher.Matches(&n)); EXPECT_FALSE(matcher.Matches(nullptr)); } TEST(ResultOfTest, WorksForLambdas) { Matcher matcher = ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx"); EXPECT_TRUE(matcher.Matches(3)); EXPECT_FALSE(matcher.Matches(1)); } #endif const int* ReferencingFunction(const int& n) { return &n; } struct ReferencingFunctor { typedef const int* result_type; result_type operator()(const int& n) { return &n; } }; TEST(ResultOfTest, WorksForReferencingCallables) { const int n = 1; const int n2 = 1; Matcher matcher2 = ResultOf(ReferencingFunction, Eq(&n)); EXPECT_TRUE(matcher2.Matches(n)); EXPECT_FALSE(matcher2.Matches(n2)); Matcher matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); EXPECT_TRUE(matcher3.Matches(n)); EXPECT_FALSE(matcher3.Matches(n2)); } class DivisibleByImpl { public: explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} // For testing using ExplainMatchResultTo() with polymorphic matchers. template bool MatchAndExplain(const T& n, MatchResultListener* listener) const { *listener << "which is " << (n % divider_) << " modulo " << divider_; return (n % divider_) == 0; } void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; } void DescribeNegationTo(ostream* os) const { *os << "is not divisible by " << divider_; } void set_divider(int a_divider) { divider_ = a_divider; } int divider() const { return divider_; } private: int divider_; }; PolymorphicMatcher DivisibleBy(int n) { return MakePolymorphicMatcher(DivisibleByImpl(n)); } // Tests that when AllOf() fails, only the first failing matcher is // asked to explain why. TEST(ExplainMatchResultTest, AllOf_False_False) { const Matcher m = AllOf(DivisibleBy(4), DivisibleBy(3)); EXPECT_EQ("which is 1 modulo 4", Explain(m, 5)); } // Tests that when AllOf() fails, only the first failing matcher is // asked to explain why. TEST(ExplainMatchResultTest, AllOf_False_True) { const Matcher m = AllOf(DivisibleBy(4), DivisibleBy(3)); EXPECT_EQ("which is 2 modulo 4", Explain(m, 6)); } // Tests that when AllOf() fails, only the first failing matcher is // asked to explain why. TEST(ExplainMatchResultTest, AllOf_True_False) { const Matcher m = AllOf(Ge(1), DivisibleBy(3)); EXPECT_EQ("which is 2 modulo 3", Explain(m, 5)); } // Tests that when AllOf() succeeds, all matchers are asked to explain // why. TEST(ExplainMatchResultTest, AllOf_True_True) { const Matcher m = AllOf(DivisibleBy(2), DivisibleBy(3)); EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6)); } TEST(ExplainMatchResultTest, AllOf_True_True_2) { const Matcher m = AllOf(Ge(2), Le(3)); EXPECT_EQ("", Explain(m, 2)); } TEST(ExplainmatcherResultTest, MonomorphicMatcher) { const Matcher m = GreaterThan(5); EXPECT_EQ("which is 1 more than 5", Explain(m, 6)); } // The following two tests verify that values without a public copy // ctor can be used as arguments to matchers like Eq(), Ge(), and etc // with the help of ByRef(). class NotCopyable { public: explicit NotCopyable(int a_value) : value_(a_value) {} int value() const { return value_; } bool operator==(const NotCopyable& rhs) const { return value() == rhs.value(); } bool operator>=(const NotCopyable& rhs) const { return value() >= rhs.value(); } private: int value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable); }; TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { const NotCopyable const_value1(1); const Matcher m = Eq(ByRef(const_value1)); const NotCopyable n1(1), n2(2); EXPECT_TRUE(m.Matches(n1)); EXPECT_FALSE(m.Matches(n2)); } TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { NotCopyable value2(2); const Matcher m = Ge(ByRef(value2)); NotCopyable n1(1), n2(2); EXPECT_FALSE(m.Matches(n1)); EXPECT_TRUE(m.Matches(n2)); } TEST(IsEmptyTest, ImplementsIsEmpty) { vector container; EXPECT_THAT(container, IsEmpty()); container.push_back(0); EXPECT_THAT(container, Not(IsEmpty())); container.push_back(1); EXPECT_THAT(container, Not(IsEmpty())); } TEST(IsEmptyTest, WorksWithString) { std::string text; EXPECT_THAT(text, IsEmpty()); text = "foo"; EXPECT_THAT(text, Not(IsEmpty())); text = std::string("\0", 1); EXPECT_THAT(text, Not(IsEmpty())); } TEST(IsEmptyTest, CanDescribeSelf) { Matcher > m = IsEmpty(); EXPECT_EQ("is empty", Describe(m)); EXPECT_EQ("isn't empty", DescribeNegation(m)); } TEST(IsEmptyTest, ExplainsResult) { Matcher > m = IsEmpty(); vector container; EXPECT_EQ("", Explain(m, container)); container.push_back(0); EXPECT_EQ("whose size is 1", Explain(m, container)); } TEST(IsTrueTest, IsTrueIsFalse) { EXPECT_THAT(true, IsTrue()); EXPECT_THAT(false, IsFalse()); EXPECT_THAT(true, Not(IsFalse())); EXPECT_THAT(false, Not(IsTrue())); EXPECT_THAT(0, Not(IsTrue())); EXPECT_THAT(0, IsFalse()); EXPECT_THAT(nullptr, Not(IsTrue())); EXPECT_THAT(nullptr, IsFalse()); EXPECT_THAT(-1, IsTrue()); EXPECT_THAT(-1, Not(IsFalse())); EXPECT_THAT(1, IsTrue()); EXPECT_THAT(1, Not(IsFalse())); EXPECT_THAT(2, IsTrue()); EXPECT_THAT(2, Not(IsFalse())); int a = 42; EXPECT_THAT(a, IsTrue()); EXPECT_THAT(a, Not(IsFalse())); EXPECT_THAT(&a, IsTrue()); EXPECT_THAT(&a, Not(IsFalse())); EXPECT_THAT(false, Not(IsTrue())); EXPECT_THAT(true, Not(IsFalse())); #if GTEST_LANG_CXX11 EXPECT_THAT(std::true_type(), IsTrue()); EXPECT_THAT(std::true_type(), Not(IsFalse())); EXPECT_THAT(std::false_type(), IsFalse()); EXPECT_THAT(std::false_type(), Not(IsTrue())); EXPECT_THAT(nullptr, Not(IsTrue())); EXPECT_THAT(nullptr, IsFalse()); std::unique_ptr null_unique; std::unique_ptr nonnull_unique(new int(0)); EXPECT_THAT(null_unique, Not(IsTrue())); EXPECT_THAT(null_unique, IsFalse()); EXPECT_THAT(nonnull_unique, IsTrue()); EXPECT_THAT(nonnull_unique, Not(IsFalse())); #endif // GTEST_LANG_CXX11 } TEST(SizeIsTest, ImplementsSizeIs) { vector container; EXPECT_THAT(container, SizeIs(0)); EXPECT_THAT(container, Not(SizeIs(1))); container.push_back(0); EXPECT_THAT(container, Not(SizeIs(0))); EXPECT_THAT(container, SizeIs(1)); container.push_back(0); EXPECT_THAT(container, Not(SizeIs(0))); EXPECT_THAT(container, SizeIs(2)); } TEST(SizeIsTest, WorksWithMap) { map container; EXPECT_THAT(container, SizeIs(0)); EXPECT_THAT(container, Not(SizeIs(1))); container.insert(make_pair("foo", 1)); EXPECT_THAT(container, Not(SizeIs(0))); EXPECT_THAT(container, SizeIs(1)); container.insert(make_pair("bar", 2)); EXPECT_THAT(container, Not(SizeIs(0))); EXPECT_THAT(container, SizeIs(2)); } TEST(SizeIsTest, WorksWithReferences) { vector container; Matcher&> m = SizeIs(1); EXPECT_THAT(container, Not(m)); container.push_back(0); EXPECT_THAT(container, m); } TEST(SizeIsTest, CanDescribeSelf) { Matcher > m = SizeIs(2); EXPECT_EQ("size is equal to 2", Describe(m)); EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); } TEST(SizeIsTest, ExplainsResult) { Matcher > m1 = SizeIs(2); Matcher > m2 = SizeIs(Lt(2u)); Matcher > m3 = SizeIs(AnyOf(0, 3)); Matcher > m4 = SizeIs(GreaterThan(1)); vector container; EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); EXPECT_EQ("whose size 0 matches", Explain(m2, container)); EXPECT_EQ("whose size 0 matches", Explain(m3, container)); EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1", Explain(m4, container)); container.push_back(0); container.push_back(0); EXPECT_EQ("whose size 2 matches", Explain(m1, container)); EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); EXPECT_EQ("whose size 2 matches, which is 1 more than 1", Explain(m4, container)); } #if GTEST_HAS_TYPED_TEST // Tests ContainerEq with different container types, and // different element types. template class ContainerEqTest : public testing::Test {}; typedef testing::Types< set, vector, multiset, list > ContainerEqTestTypes; TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes); // Tests that the filled container is equal to itself. TYPED_TEST(ContainerEqTest, EqualsSelf) { static const int vals[] = {1, 1, 2, 3, 5, 8}; TypeParam my_set(vals, vals + 6); const Matcher m = ContainerEq(my_set); EXPECT_TRUE(m.Matches(my_set)); EXPECT_EQ("", Explain(m, my_set)); } // Tests that missing values are reported. TYPED_TEST(ContainerEqTest, ValueMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 8, 5}; TypeParam my_set(vals, vals + 6); TypeParam test_set(test_vals, test_vals + 4); const Matcher m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which doesn't have these expected elements: 3", Explain(m, test_set)); } // Tests that added values are reported. TYPED_TEST(ContainerEqTest, ValueAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 5, 8, 46}; TypeParam my_set(vals, vals + 6); TypeParam test_set(test_vals, test_vals + 6); const Matcher m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set)); } // Tests that added and missing values are reported together. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 8, 46}; TypeParam my_set(vals, vals + 6); TypeParam test_set(test_vals, test_vals + 5); const Matcher m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 46,\n" "and doesn't have these expected elements: 5", Explain(m, test_set)); } // Tests duplicated value -- expect no explanation. TYPED_TEST(ContainerEqTest, DuplicateDifference) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 5, 8}; TypeParam my_set(vals, vals + 6); TypeParam test_set(test_vals, test_vals + 5); const Matcher m = ContainerEq(my_set); // Depending on the container, match may be true or false // But in any case there should be no explanation. EXPECT_EQ("", Explain(m, test_set)); } #endif // GTEST_HAS_TYPED_TEST // Tests that mutliple missing values are reported. // Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; vector my_set(vals, vals + 6); vector test_set(test_vals, test_vals + 3); const Matcher > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which doesn't have these expected elements: 3, 8", Explain(m, test_set)); } // Tests that added values are reported. // Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; list my_set(vals, vals + 6); list test_set(test_vals, test_vals + 7); const Matcher&> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46", Explain(m, test_set)); } // Tests that added and missing values are reported together. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 92, 46}; list my_set(vals, vals + 6); list test_set(test_vals, test_vals + 5); const Matcher > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46,\n" "and doesn't have these expected elements: 5, 8", Explain(m, test_set)); } // Tests to see that duplicate elements are detected, // but (as above) not reported in the explanation. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 5, 8}; vector my_set(vals, vals + 6); vector test_set(test_vals, test_vals + 5); const Matcher > m = ContainerEq(my_set); EXPECT_TRUE(m.Matches(my_set)); EXPECT_FALSE(m.Matches(test_set)); // There is nothing to report when both sets contain all the same values. EXPECT_EQ("", Explain(m, test_set)); } // Tests that ContainerEq works for non-trivial associative containers, // like maps. TEST(ContainerEqExtraTest, WorksForMaps) { map my_map; my_map[0] = "a"; my_map[1] = "b"; map test_map; test_map[0] = "aa"; test_map[1] = "b"; const Matcher&> m = ContainerEq(my_map); EXPECT_TRUE(m.Matches(my_map)); EXPECT_FALSE(m.Matches(test_map)); EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" "and doesn't have these expected elements: (0, \"a\")", Explain(m, test_map)); } TEST(ContainerEqExtraTest, WorksForNativeArray) { int a1[] = {1, 2, 3}; int a2[] = {1, 2, 3}; int b[] = {1, 2, 4}; EXPECT_THAT(a1, ContainerEq(a2)); EXPECT_THAT(a1, Not(ContainerEq(b))); } TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { const char a1[][3] = {"hi", "lo"}; const char a2[][3] = {"hi", "lo"}; const char b[][3] = {"lo", "hi"}; // Tests using ContainerEq() in the first dimension. EXPECT_THAT(a1, ContainerEq(a2)); EXPECT_THAT(a1, Not(ContainerEq(b))); // Tests using ContainerEq() in the second dimension. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); } TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { const int a1[] = {1, 2, 3}; const int a2[] = {1, 2, 3}; const int b[] = {1, 2, 3, 4}; const int* const p1 = a1; EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); const int c[] = {1, 3, 2}; EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); } TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { std::string a1[][3] = { {"hi", "hello", "ciao"}, {"bye", "see you", "ciao"} }; std::string a2[][3] = { {"hi", "hello", "ciao"}, {"bye", "see you", "ciao"} }; const Matcher m = ContainerEq(a2); EXPECT_THAT(a1, m); a2[0][0] = "ha"; EXPECT_THAT(a1, m); } TEST(WhenSortedByTest, WorksForEmptyContainer) { const vector numbers; EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre())); EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1)))); } TEST(WhenSortedByTest, WorksForNonEmptyContainer) { vector numbers; numbers.push_back(3); numbers.push_back(1); numbers.push_back(2); numbers.push_back(2); EXPECT_THAT(numbers, WhenSortedBy(greater(), ElementsAre(3, 2, 2, 1))); EXPECT_THAT(numbers, Not(WhenSortedBy(greater(), ElementsAre(1, 2, 2, 3)))); } TEST(WhenSortedByTest, WorksForNonVectorContainer) { list words; words.push_back("say"); words.push_back("hello"); words.push_back("world"); EXPECT_THAT(words, WhenSortedBy(less(), ElementsAre("hello", "say", "world"))); EXPECT_THAT(words, Not(WhenSortedBy(less(), ElementsAre("say", "hello", "world")))); } TEST(WhenSortedByTest, WorksForNativeArray) { const int numbers[] = {1, 3, 2, 4}; const int sorted_numbers[] = {1, 2, 3, 4}; EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre(1, 2, 3, 4))); EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAreArray(sorted_numbers))); EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1, 3, 2, 4)))); } TEST(WhenSortedByTest, CanDescribeSelf) { const Matcher > m = WhenSortedBy(less(), ElementsAre(1, 2)); EXPECT_EQ("(when sorted) has 2 elements where\n" "element #0 is equal to 1,\n" "element #1 is equal to 2", Describe(m)); EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" "element #0 isn't equal to 1, or\n" "element #1 isn't equal to 2", DescribeNegation(m)); } TEST(WhenSortedByTest, ExplainsMatchResult) { const int a[] = {2, 1}; EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match", Explain(WhenSortedBy(less(), ElementsAre(2, 3)), a)); EXPECT_EQ("which is { 1, 2 } when sorted", Explain(WhenSortedBy(less(), ElementsAre(1, 2)), a)); } // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't // need to test it as exhaustively as we test the latter. TEST(WhenSortedTest, WorksForEmptyContainer) { const vector numbers; EXPECT_THAT(numbers, WhenSorted(ElementsAre())); EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); } TEST(WhenSortedTest, WorksForNonEmptyContainer) { list words; words.push_back("3"); words.push_back("1"); words.push_back("2"); words.push_back("2"); EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3"))); EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2")))); } TEST(WhenSortedTest, WorksForMapTypes) { map word_counts; word_counts["and"] = 1; word_counts["the"] = 1; word_counts["buffalo"] = 2; EXPECT_THAT(word_counts, WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), Pair("the", 1)))); EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), Pair("buffalo", 2))))); } TEST(WhenSortedTest, WorksForMultiMapTypes) { multimap ifib; ifib.insert(make_pair(8, 6)); ifib.insert(make_pair(2, 3)); ifib.insert(make_pair(1, 1)); ifib.insert(make_pair(3, 4)); ifib.insert(make_pair(1, 2)); ifib.insert(make_pair(5, 5)); EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3), Pair(3, 4), Pair(5, 5), Pair(8, 6)))); EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1), Pair(3, 4), Pair(1, 2), Pair(5, 5))))); } TEST(WhenSortedTest, WorksForPolymorphicMatcher) { std::deque d; d.push_back(2); d.push_back(1); EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); } TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { std::deque d; d.push_back(2); d.push_back(1); Matcher&> vector_match = ElementsAre(1, 2); EXPECT_THAT(d, WhenSorted(vector_match)); Matcher&> not_vector_match = ElementsAre(2, 1); EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); } // Deliberately bare pseudo-container. // Offers only begin() and end() accessors, yielding InputIterator. template class Streamlike { private: class ConstIter; public: typedef ConstIter const_iterator; typedef T value_type; template Streamlike(InIter first, InIter last) : remainder_(first, last) {} const_iterator begin() const { return const_iterator(this, remainder_.begin()); } const_iterator end() const { return const_iterator(this, remainder_.end()); } private: class ConstIter : public std::iterator { public: ConstIter(const Streamlike* s, typename std::list::iterator pos) : s_(s), pos_(pos) {} const value_type& operator*() const { return *pos_; } const value_type* operator->() const { return &*pos_; } ConstIter& operator++() { s_->remainder_.erase(pos_++); return *this; } // *iter++ is required to work (see std::istreambuf_iterator). // (void)iter++ is also required to work. class PostIncrProxy { public: explicit PostIncrProxy(const value_type& value) : value_(value) {} value_type operator*() const { return value_; } private: value_type value_; }; PostIncrProxy operator++(int) { PostIncrProxy proxy(**this); ++(*this); return proxy; } friend bool operator==(const ConstIter& a, const ConstIter& b) { return a.s_ == b.s_ && a.pos_ == b.pos_; } friend bool operator!=(const ConstIter& a, const ConstIter& b) { return !(a == b); } private: const Streamlike* s_; typename std::list::iterator pos_; }; friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { os << "["; typedef typename std::list::const_iterator Iter; const char* sep = ""; for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { os << sep << *it; sep = ","; } os << "]"; return os; } mutable std::list remainder_; // modified by iteration }; TEST(StreamlikeTest, Iteration) { const int a[5] = {2, 1, 4, 5, 3}; Streamlike s(a, a + 5); Streamlike::const_iterator it = s.begin(); const int* ip = a; while (it != s.end()) { SCOPED_TRACE(ip - a); EXPECT_EQ(*ip++, *it++); } } #if GTEST_HAS_STD_FORWARD_LIST_ TEST(BeginEndDistanceIsTest, WorksWithForwardList) { std::forward_list container; EXPECT_THAT(container, BeginEndDistanceIs(0)); EXPECT_THAT(container, Not(BeginEndDistanceIs(1))); container.push_front(0); EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); EXPECT_THAT(container, BeginEndDistanceIs(1)); container.push_front(0); EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); EXPECT_THAT(container, BeginEndDistanceIs(2)); } #endif // GTEST_HAS_STD_FORWARD_LIST_ TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { const int a[5] = {1, 2, 3, 4, 5}; Streamlike s(a, a + 5); EXPECT_THAT(s, BeginEndDistanceIs(5)); } TEST(BeginEndDistanceIsTest, CanDescribeSelf) { Matcher > m = BeginEndDistanceIs(2); EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m)); EXPECT_EQ("distance between begin() and end() isn't equal to 2", DescribeNegation(m)); } TEST(BeginEndDistanceIsTest, ExplainsResult) { Matcher > m1 = BeginEndDistanceIs(2); Matcher > m2 = BeginEndDistanceIs(Lt(2)); Matcher > m3 = BeginEndDistanceIs(AnyOf(0, 3)); Matcher > m4 = BeginEndDistanceIs(GreaterThan(1)); vector container; EXPECT_EQ("whose distance between begin() and end() 0 doesn't match", Explain(m1, container)); EXPECT_EQ("whose distance between begin() and end() 0 matches", Explain(m2, container)); EXPECT_EQ("whose distance between begin() and end() 0 matches", Explain(m3, container)); EXPECT_EQ( "whose distance between begin() and end() 0 doesn't match, which is 1 " "less than 1", Explain(m4, container)); container.push_back(0); container.push_back(0); EXPECT_EQ("whose distance between begin() and end() 2 matches", Explain(m1, container)); EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", Explain(m2, container)); EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", Explain(m3, container)); EXPECT_EQ( "whose distance between begin() and end() 2 matches, which is 1 more " "than 1", Explain(m4, container)); } TEST(WhenSortedTest, WorksForStreamlike) { // Streamlike 'container' provides only minimal iterator support. // Its iterators are tagged with input_iterator_tag. const int a[5] = {2, 1, 4, 5, 3}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { const int a[] = {2, 1, 4, 5, 3}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); Matcher&> vector_match = ElementsAre(1, 2, 3, 4, 5); EXPECT_THAT(s, WhenSorted(vector_match)); EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } TEST(IsSupersetOfTest, WorksForNativeArray) { const int subset[] = {1, 4}; const int superset[] = {1, 2, 4}; const int disjoint[] = {1, 0, 3}; EXPECT_THAT(subset, IsSupersetOf(subset)); EXPECT_THAT(subset, Not(IsSupersetOf(superset))); EXPECT_THAT(superset, IsSupersetOf(subset)); EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); } TEST(IsSupersetOfTest, WorksWithDuplicates) { const int not_enough[] = {1, 2}; const int enough[] = {1, 1, 2}; const int expected[] = {1, 1}; EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); EXPECT_THAT(enough, IsSupersetOf(expected)); } TEST(IsSupersetOfTest, WorksForEmpty) { vector numbers; vector expected; EXPECT_THAT(numbers, IsSupersetOf(expected)); expected.push_back(1); EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); expected.clear(); numbers.push_back(1); numbers.push_back(2); EXPECT_THAT(numbers, IsSupersetOf(expected)); expected.push_back(1); EXPECT_THAT(numbers, IsSupersetOf(expected)); expected.push_back(2); EXPECT_THAT(numbers, IsSupersetOf(expected)); expected.push_back(3); EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); } TEST(IsSupersetOfTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); vector expected; expected.push_back(1); expected.push_back(2); expected.push_back(5); EXPECT_THAT(s, IsSupersetOf(expected)); expected.push_back(0); EXPECT_THAT(s, Not(IsSupersetOf(expected))); } TEST(IsSupersetOfTest, TakesStlContainer) { const int actual[] = {3, 1, 2}; ::std::list expected; expected.push_back(1); expected.push_back(3); EXPECT_THAT(actual, IsSupersetOf(expected)); expected.push_back(4); EXPECT_THAT(actual, Not(IsSupersetOf(expected))); } TEST(IsSupersetOfTest, Describe) { typedef std::vector IntVec; IntVec expected; expected.push_back(111); expected.push_back(222); expected.push_back(333); EXPECT_THAT( Describe(IsSupersetOf(expected)), Eq("a surjection from elements to requirements exists such that:\n" " - an element is equal to 111\n" " - an element is equal to 222\n" " - an element is equal to 333")); } TEST(IsSupersetOfTest, DescribeNegation) { typedef std::vector IntVec; IntVec expected; expected.push_back(111); expected.push_back(222); expected.push_back(333); EXPECT_THAT( DescribeNegation(IsSupersetOf(expected)), Eq("no surjection from elements to requirements exists such that:\n" " - an element is equal to 111\n" " - an element is equal to 222\n" " - an element is equal to 333")); } TEST(IsSupersetOfTest, MatchAndExplain) { std::vector v; v.push_back(2); v.push_back(3); std::vector expected; expected.push_back(1); expected.push_back(2); StringMatchResultListener listener; ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("where the following matchers don't match any elements:\n" "matcher #0: is equal to 1")); v.push_back(1); listener.Clear(); ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("where:\n" " - element #0 is matched by matcher #1,\n" " - element #2 is matched by matcher #0")); } #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(IsSupersetOfTest, WorksForRhsInitializerList) { const int numbers[] = {1, 3, 6, 2, 4, 5}; EXPECT_THAT(numbers, IsSupersetOf({1, 2})); EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); } #endif TEST(IsSubsetOfTest, WorksForNativeArray) { const int subset[] = {1, 4}; const int superset[] = {1, 2, 4}; const int disjoint[] = {1, 0, 3}; EXPECT_THAT(subset, IsSubsetOf(subset)); EXPECT_THAT(subset, IsSubsetOf(superset)); EXPECT_THAT(superset, Not(IsSubsetOf(subset))); EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); } TEST(IsSubsetOfTest, WorksWithDuplicates) { const int not_enough[] = {1, 2}; const int enough[] = {1, 1, 2}; const int actual[] = {1, 1}; EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); EXPECT_THAT(actual, IsSubsetOf(enough)); } TEST(IsSubsetOfTest, WorksForEmpty) { vector numbers; vector expected; EXPECT_THAT(numbers, IsSubsetOf(expected)); expected.push_back(1); EXPECT_THAT(numbers, IsSubsetOf(expected)); expected.clear(); numbers.push_back(1); numbers.push_back(2); EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); expected.push_back(1); EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); expected.push_back(2); EXPECT_THAT(numbers, IsSubsetOf(expected)); expected.push_back(3); EXPECT_THAT(numbers, IsSubsetOf(expected)); } TEST(IsSubsetOfTest, WorksForStreamlike) { const int a[5] = {1, 2}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); vector expected; expected.push_back(1); EXPECT_THAT(s, Not(IsSubsetOf(expected))); expected.push_back(2); expected.push_back(5); EXPECT_THAT(s, IsSubsetOf(expected)); } TEST(IsSubsetOfTest, TakesStlContainer) { const int actual[] = {3, 1, 2}; ::std::list expected; expected.push_back(1); expected.push_back(3); EXPECT_THAT(actual, Not(IsSubsetOf(expected))); expected.push_back(2); expected.push_back(4); EXPECT_THAT(actual, IsSubsetOf(expected)); } TEST(IsSubsetOfTest, Describe) { typedef std::vector IntVec; IntVec expected; expected.push_back(111); expected.push_back(222); expected.push_back(333); EXPECT_THAT( Describe(IsSubsetOf(expected)), Eq("an injection from elements to requirements exists such that:\n" " - an element is equal to 111\n" " - an element is equal to 222\n" " - an element is equal to 333")); } TEST(IsSubsetOfTest, DescribeNegation) { typedef std::vector IntVec; IntVec expected; expected.push_back(111); expected.push_back(222); expected.push_back(333); EXPECT_THAT( DescribeNegation(IsSubsetOf(expected)), Eq("no injection from elements to requirements exists such that:\n" " - an element is equal to 111\n" " - an element is equal to 222\n" " - an element is equal to 333")); } TEST(IsSubsetOfTest, MatchAndExplain) { std::vector v; v.push_back(2); v.push_back(3); std::vector expected; expected.push_back(1); expected.push_back(2); StringMatchResultListener listener; ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("where the following elements don't match any matchers:\n" "element #1: 3")); expected.push_back(3); listener.Clear(); ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("where:\n" " - element #0 is matched by matcher #1,\n" " - element #1 is matched by matcher #2")); } #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(IsSubsetOfTest, WorksForRhsInitializerList) { const int numbers[] = {1, 2, 3}; EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); } #endif // Tests using ElementsAre() and ElementsAreArray() with stream-like // "containers". TEST(ElemensAreStreamTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); } TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); vector expected; expected.push_back(1); expected.push_back(2); expected.push_back(3); expected.push_back(4); expected.push_back(5); EXPECT_THAT(s, ElementsAreArray(expected)); expected[3] = 0; EXPECT_THAT(s, Not(ElementsAreArray(expected))); } TEST(ElementsAreTest, WorksWithUncopyable) { Uncopyable objs[2]; objs[0].set_value(-3); objs[1].set_value(1); EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); } TEST(ElementsAreTest, TakesStlContainer) { const int actual[] = {3, 1, 2}; ::std::list expected; expected.push_back(3); expected.push_back(1); expected.push_back(2); EXPECT_THAT(actual, ElementsAreArray(expected)); expected.push_back(4); EXPECT_THAT(actual, Not(ElementsAreArray(expected))); } // Tests for UnorderedElementsAreArray() TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { const int a[] = {0, 1, 2, 3, 4}; std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); do { StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener)) << listener.str(); } while (std::next_permutation(s.begin(), s.end())); } TEST(UnorderedElementsAreArrayTest, VectorBool) { const bool a[] = {0, 1, 0, 1, 1}; const bool b[] = {1, 0, 1, 1, 0}; std::vector expected(a, a + GTEST_ARRAY_SIZE_(a)); std::vector actual(b, b + GTEST_ARRAY_SIZE_(b)); StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual, &listener)) << listener.str(); } TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { // Streamlike 'container' provides only minimal iterator support. // Its iterators are tagged with input_iterator_tag, and it has no // size() or empty() methods. const int a[5] = {2, 1, 4, 5, 3}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); ::std::vector expected; expected.push_back(1); expected.push_back(2); expected.push_back(3); expected.push_back(4); expected.push_back(5); EXPECT_THAT(s, UnorderedElementsAreArray(expected)); expected.push_back(6); EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); } TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { const int actual[] = {3, 1, 2}; ::std::list expected; expected.push_back(1); expected.push_back(2); expected.push_back(3); EXPECT_THAT(actual, UnorderedElementsAreArray(expected)); expected.push_back(4); EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); } #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { const int a[5] = {2, 1, 4, 5, 3}; EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6}))); } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { const int a[5] = {2, 1, 4, 5, 3}; EXPECT_THAT(a, UnorderedElementsAreArray( {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); EXPECT_THAT(a, Not(UnorderedElementsAreArray( {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) { const int a[5] = {2, 1, 4, 5, 3}; // The compiler cannot infer the type of the initializer list if its // elements have different types. We must explicitly specify the // unified element type in this case. EXPECT_THAT(a, UnorderedElementsAreArray >( {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); EXPECT_THAT(a, Not(UnorderedElementsAreArray >( {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ class UnorderedElementsAreTest : public testing::Test { protected: typedef std::vector IntVec; }; TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { Uncopyable objs[2]; objs[0].set_value(-3); objs[1].set_value(1); EXPECT_THAT(objs, UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3))); } TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { const int a[] = {1, 2, 3}; std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); do { StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener)) << listener.str(); } while (std::next_permutation(s.begin(), s.end())); } TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { const int a[] = {1, 2, 3}; std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); std::vector > mv; mv.push_back(1); mv.push_back(2); mv.push_back(2); // The element with value '3' matches nothing: fail fast. StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) << listener.str(); } TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { // Streamlike 'container' provides only minimal iterator support. // Its iterators are tagged with input_iterator_tag, and it has no // size() or empty() methods. const int a[5] = {2, 1, 4, 5, 3}; Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); } // One naive implementation of the matcher runs in O(N!) time, which is too // slow for many real-world inputs. This test shows that our matcher can match // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 // iterations and obviously effectively incomputable. // [ RUN ] UnorderedElementsAreTest.Performance // [ OK ] UnorderedElementsAreTest.Performance (4 ms) TEST_F(UnorderedElementsAreTest, Performance) { std::vector s; std::vector > mv; for (int i = 0; i < 100; ++i) { s.push_back(i); mv.push_back(_); } mv[50] = Eq(0); StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) << listener.str(); } // Another variant of 'Performance' with similar expectations. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { std::vector s; std::vector > mv; for (int i = 0; i < 100; ++i) { s.push_back(i); if (i & 1) { mv.push_back(_); } else { mv.push_back(i); } } StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) << listener.str(); } TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { std::vector v; v.push_back(4); StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("which has 1 element")); } TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { std::vector v; StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) << listener.str(); EXPECT_THAT(listener.str(), Eq("")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { std::vector v; v.push_back(1); v.push_back(1); StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) << listener.str(); EXPECT_THAT( listener.str(), Eq("where the following matchers don't match any elements:\n" "matcher #1: is equal to 2")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { std::vector v; v.push_back(1); v.push_back(2); StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener)) << listener.str(); EXPECT_THAT( listener.str(), Eq("where the following elements don't match any matchers:\n" "element #1: 2")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { std::vector v; v.push_back(2); v.push_back(3); StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) << listener.str(); EXPECT_THAT( listener.str(), Eq("where" " the following matchers don't match any elements:\n" "matcher #0: is equal to 1\n" "and" " where" " the following elements don't match any matchers:\n" "element #1: 3")); } // Test helper for formatting element, matcher index pairs in expectations. static std::string EMString(int element, int matcher) { stringstream ss; ss << "(element #" << element << ", matcher #" << matcher << ")"; return ss.str(); } TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { // A situation where all elements and matchers have a match // associated with them, but the max matching is not perfect. std::vector v; v.push_back("a"); v.push_back("b"); v.push_back("c"); StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult( UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) << listener.str(); std::string prefix = "where no permutation of the elements can satisfy all matchers, " "and the closest match is 2 of 3 matchers with the " "pairings:\n"; // We have to be a bit loose here, because there are 4 valid max matches. EXPECT_THAT( listener.str(), AnyOf(prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}", prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}", prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}", prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) + "\n}")); } TEST_F(UnorderedElementsAreTest, Describe) { EXPECT_THAT(Describe(UnorderedElementsAre()), Eq("is empty")); EXPECT_THAT( Describe(UnorderedElementsAre(345)), Eq("has 1 element and that element is equal to 345")); EXPECT_THAT( Describe(UnorderedElementsAre(111, 222, 333)), Eq("has 3 elements and there exists some permutation " "of elements such that:\n" " - element #0 is equal to 111, and\n" " - element #1 is equal to 222, and\n" " - element #2 is equal to 333")); } TEST_F(UnorderedElementsAreTest, DescribeNegation) { EXPECT_THAT(DescribeNegation(UnorderedElementsAre()), Eq("isn't empty")); EXPECT_THAT( DescribeNegation(UnorderedElementsAre(345)), Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); EXPECT_THAT( DescribeNegation(UnorderedElementsAre(123, 234, 345)), Eq("doesn't have 3 elements, or there exists no permutation " "of elements such that:\n" " - element #0 is equal to 123, and\n" " - element #1 is equal to 234, and\n" " - element #2 is equal to 345")); } namespace { // Used as a check on the more complex max flow method used in the // real testing::internal::FindMaxBipartiteMatching. This method is // compatible but runs in worst-case factorial time, so we only // use it in testing for small problem sizes. template class BacktrackingMaxBPMState { public: // Does not take ownership of 'g'. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } ElementMatcherPairs Compute() { if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { return best_so_far_; } lhs_used_.assign(graph_->LhsSize(), kUnused); rhs_used_.assign(graph_->RhsSize(), kUnused); for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { matches_.clear(); RecurseInto(irhs); if (best_so_far_.size() == graph_->RhsSize()) break; } return best_so_far_; } private: static const size_t kUnused = static_cast(-1); void PushMatch(size_t lhs, size_t rhs) { matches_.push_back(ElementMatcherPair(lhs, rhs)); lhs_used_[lhs] = rhs; rhs_used_[rhs] = lhs; if (matches_.size() > best_so_far_.size()) { best_so_far_ = matches_; } } void PopMatch() { const ElementMatcherPair& back = matches_.back(); lhs_used_[back.first] = kUnused; rhs_used_[back.second] = kUnused; matches_.pop_back(); } bool RecurseInto(size_t irhs) { if (rhs_used_[irhs] != kUnused) { return true; } for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { if (lhs_used_[ilhs] != kUnused) { continue; } if (!graph_->HasEdge(ilhs, irhs)) { continue; } PushMatch(ilhs, irhs); if (best_so_far_.size() == graph_->RhsSize()) { return false; } for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { if (!RecurseInto(mi)) return false; } PopMatch(); } return true; } const Graph* graph_; // not owned std::vector lhs_used_; std::vector rhs_used_; ElementMatcherPairs matches_; ElementMatcherPairs best_so_far_; }; template const size_t BacktrackingMaxBPMState::kUnused; } // namespace // Implement a simple backtracking algorithm to determine if it is possible // to find one element per matcher, without reusing elements. template ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) { return BacktrackingMaxBPMState(&g).Compute(); } class BacktrackingBPMTest : public ::testing::Test { }; // Tests the MaxBipartiteMatching algorithm with square matrices. // The single int param is the # of nodes on each of the left and right sides. class BipartiteTest : public ::testing::TestWithParam { }; // Verify all match graphs up to some moderate number of edges. TEST_P(BipartiteTest, Exhaustive) { int nodes = GetParam(); MatchMatrix graph(nodes, nodes); do { ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph); EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) << "graph: " << graph.DebugString(); // Check that all elements of matches are in the graph. // Check that elements of first and second are unique. std::vector seen_element(graph.LhsSize()); std::vector seen_matcher(graph.RhsSize()); SCOPED_TRACE(PrintToString(matches)); for (size_t i = 0; i < matches.size(); ++i) { size_t ilhs = matches[i].first; size_t irhs = matches[i].second; EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); EXPECT_FALSE(seen_element[ilhs]); EXPECT_FALSE(seen_matcher[irhs]); seen_element[ilhs] = true; seen_matcher[irhs] = true; } } while (graph.NextGraph()); } INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest, ::testing::Range(0, 5)); // Parameterized by a pair interpreted as (LhsSize, RhsSize). class BipartiteNonSquareTest : public ::testing::TestWithParam > { }; TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { // ....... // 0:-----\ : // 1:---\ | : // 2:---\ | : // 3:-\ | | : // :.......: // 0 1 2 MatchMatrix g(4, 3); static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}}; for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) { g.SetEdge(kEdges[i][0], kEdges[i][1], true); } EXPECT_THAT(FindBacktrackingMaxBPM(g), ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2))) << g.DebugString(); } // Verify a few nonsquare matrices. TEST_P(BipartiteNonSquareTest, Exhaustive) { size_t nlhs = GetParam().first; size_t nrhs = GetParam().second; MatchMatrix graph(nlhs, nrhs); do { EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), internal::FindMaxBipartiteMatching(graph).size()) << "graph: " << graph.DebugString() << "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph)) << "\nmax flow: " << PrintToString(internal::FindMaxBipartiteMatching(graph)); } while (graph.NextGraph()); } INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest, testing::Values( std::make_pair(1, 2), std::make_pair(2, 1), std::make_pair(3, 2), std::make_pair(2, 3), std::make_pair(4, 1), std::make_pair(1, 4), std::make_pair(4, 3), std::make_pair(3, 4))); class BipartiteRandomTest : public ::testing::TestWithParam > { }; // Verifies a large sample of larger graphs. TEST_P(BipartiteRandomTest, LargerNets) { int nodes = GetParam().first; int iters = GetParam().second; MatchMatrix graph(nodes, nodes); testing::internal::Int32 seed = GTEST_FLAG(random_seed); if (seed == 0) { seed = static_cast(time(nullptr)); } for (; iters > 0; --iters, ++seed) { srand(static_cast(seed)); graph.Randomize(); EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), internal::FindMaxBipartiteMatching(graph).size()) << " graph: " << graph.DebugString() << "\nTo reproduce the failure, rerun the test with the flag" " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; } } // Test argument is a std::pair representing (nodes, iters). INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest, testing::Values( std::make_pair(5, 10000), std::make_pair(6, 5000), std::make_pair(7, 2000), std::make_pair(8, 500), std::make_pair(9, 100))); // Tests IsReadableTypeName(). TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { EXPECT_TRUE(IsReadableTypeName("int")); EXPECT_TRUE(IsReadableTypeName("const unsigned char*")); EXPECT_TRUE(IsReadableTypeName("MyMap")); EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)")); } TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName")); EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]")); EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass")); } TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { EXPECT_FALSE( IsReadableTypeName("basic_string >")); EXPECT_FALSE(IsReadableTypeName("std::vector >")); } TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); } // Tests FormatMatcherDescription(). TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { EXPECT_EQ("is even", FormatMatcherDescription(false, "IsEven", Strings())); EXPECT_EQ("not (is even)", FormatMatcherDescription(true, "IsEven", Strings())); const char* params[] = {"5"}; EXPECT_EQ("equals 5", FormatMatcherDescription(false, "Equals", Strings(params, params + 1))); const char* params2[] = {"5", "8"}; EXPECT_EQ("is in range (5, 8)", FormatMatcherDescription(false, "IsInRange", Strings(params2, params2 + 2))); } // Tests PolymorphicMatcher::mutable_impl(). TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { PolymorphicMatcher m(DivisibleByImpl(42)); DivisibleByImpl& impl = m.mutable_impl(); EXPECT_EQ(42, impl.divider()); impl.set_divider(0); EXPECT_EQ(0, m.mutable_impl().divider()); } // Tests PolymorphicMatcher::impl(). TEST(PolymorphicMatcherTest, CanAccessImpl) { const PolymorphicMatcher m(DivisibleByImpl(42)); const DivisibleByImpl& impl = m.impl(); EXPECT_EQ(42, impl.divider()); } TEST(MatcherTupleTest, ExplainsMatchFailure) { stringstream ss1; ExplainMatchFailureTupleTo( std::make_tuple(Matcher(Eq('a')), GreaterThan(5)), std::make_tuple('a', 10), &ss1); EXPECT_EQ("", ss1.str()); // Successful match. stringstream ss2; ExplainMatchFailureTupleTo( std::make_tuple(GreaterThan(5), Matcher(Eq('a'))), std::make_tuple(2, 'b'), &ss2); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n" " Expected arg #1: is equal to 'a' (97, 0x61)\n" " Actual: 'b' (98, 0x62)\n", ss2.str()); // Failed match where both arguments need explanation. stringstream ss3; ExplainMatchFailureTupleTo( std::make_tuple(GreaterThan(5), Matcher(Eq('a'))), std::make_tuple(2, 'a'), &ss3); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n", ss3.str()); // Failed match where only one argument needs // explanation. } // Tests Each(). TEST(EachTest, ExplainsMatchResultCorrectly) { set a; // empty Matcher > m = Each(2); EXPECT_EQ("", Explain(m, a)); Matcher n = Each(1); // NOLINT const int b[1] = {1}; EXPECT_EQ("", Explain(n, b)); n = Each(3); EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); a.insert(1); a.insert(2); a.insert(3); m = Each(GreaterThan(0)); EXPECT_EQ("", Explain(m, a)); m = Each(GreaterThan(10)); EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", Explain(m, a)); } TEST(EachTest, DescribesItselfCorrectly) { Matcher > m = Each(1); EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); Matcher > m2 = Not(m); EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); } TEST(EachTest, MatchesVectorWhenAllElementsMatch) { vector some_vector; EXPECT_THAT(some_vector, Each(1)); some_vector.push_back(3); EXPECT_THAT(some_vector, Not(Each(1))); EXPECT_THAT(some_vector, Each(3)); some_vector.push_back(1); some_vector.push_back(2); EXPECT_THAT(some_vector, Not(Each(3))); EXPECT_THAT(some_vector, Each(Lt(3.5))); vector another_vector; another_vector.push_back("fee"); EXPECT_THAT(another_vector, Each(std::string("fee"))); another_vector.push_back("fie"); another_vector.push_back("foe"); another_vector.push_back("fum"); EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); } TEST(EachTest, MatchesMapWhenAllElementsMatch) { map my_map; const char* bar = "a string"; my_map[bar] = 2; EXPECT_THAT(my_map, Each(make_pair(bar, 2))); map another_map; EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fee"] = 1; EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); } TEST(EachTest, AcceptsMatcher) { const int a[] = {1, 2, 3}; EXPECT_THAT(a, Each(Gt(0))); EXPECT_THAT(a, Not(Each(Gt(1)))); } TEST(EachTest, WorksForNativeArrayAsTuple) { const int a[] = {1, 2}; const int* const pointer = a; EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); } // For testing Pointwise(). class IsHalfOfMatcher { public: template bool MatchAndExplain(const std::tuple& a_pair, MatchResultListener* listener) const { if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { *listener << "where the second is " << std::get<1>(a_pair); return true; } else { *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; return false; } } void DescribeTo(ostream* os) const { *os << "are a pair where the first is half of the second"; } void DescribeNegationTo(ostream* os) const { *os << "are a pair where the first isn't half of the second"; } }; PolymorphicMatcher IsHalfOf() { return MakePolymorphicMatcher(IsHalfOfMatcher()); } TEST(PointwiseTest, DescribesSelf) { vector rhs; rhs.push_back(1); rhs.push_back(2); rhs.push_back(3); const Matcher&> m = Pointwise(IsHalfOf(), rhs); EXPECT_EQ("contains 3 values, where each value and its corresponding value " "in { 1, 2, 3 } are a pair where the first is half of the second", Describe(m)); EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " "index i where x and the i-th value of { 1, 2, 3 } are a pair " "where the first isn't half of the second", DescribeNegation(m)); } TEST(PointwiseTest, MakesCopyOfRhs) { list rhs; rhs.push_back(2); rhs.push_back(4); int lhs[] = {1, 2}; const Matcher m = Pointwise(IsHalfOf(), rhs); EXPECT_THAT(lhs, m); // Changing rhs now shouldn't affect m, which made a copy of rhs. rhs.push_back(6); EXPECT_THAT(lhs, m); } TEST(PointwiseTest, WorksForLhsNativeArray) { const int lhs[] = {1, 2, 3}; vector rhs; rhs.push_back(2); rhs.push_back(4); rhs.push_back(6); EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); } TEST(PointwiseTest, WorksForRhsNativeArray) { const int rhs[] = {1, 2, 3}; vector lhs; lhs.push_back(2); lhs.push_back(4); lhs.push_back(6); EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); } // Test is effective only with sanitizers. TEST(PointwiseTest, WorksForVectorOfBool) { vector rhs(3, false); rhs[1] = true; vector lhs = rhs; EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); rhs[0] = true; EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); } #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, WorksForRhsInitializerList) { const vector lhs{2, 4, 6}; EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; const int rhs[1] = {0}; EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs)); const int rhs2[3] = {0, 1, 2}; EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); } TEST(PointwiseTest, RejectsWrongContent) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 6, 4}; EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " "where the second/2 is 3", Explain(Pointwise(IsHalfOf(), rhs), lhs)); } TEST(PointwiseTest, AcceptsCorrectContent) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 4, 6}; EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); } TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 4, 6}; const Matcher> m1 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m1, rhs)); EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); // This type works as a std::tuple can be // implicitly cast to std::tuple. const Matcher> m2 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m2, rhs)); EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); } TEST(UnorderedPointwiseTest, DescribesSelf) { vector rhs; rhs.push_back(1); rhs.push_back(2); rhs.push_back(3); const Matcher&> m = UnorderedPointwise(IsHalfOf(), rhs); EXPECT_EQ( "has 3 elements and there exists some permutation of elements such " "that:\n" " - element #0 and 1 are a pair where the first is half of the second, " "and\n" " - element #1 and 2 are a pair where the first is half of the second, " "and\n" " - element #2 and 3 are a pair where the first is half of the second", Describe(m)); EXPECT_EQ( "doesn't have 3 elements, or there exists no permutation of elements " "such that:\n" " - element #0 and 1 are a pair where the first is half of the second, " "and\n" " - element #1 and 2 are a pair where the first is half of the second, " "and\n" " - element #2 and 3 are a pair where the first is half of the second", DescribeNegation(m)); } TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { list rhs; rhs.push_back(2); rhs.push_back(4); int lhs[] = {2, 1}; const Matcher m = UnorderedPointwise(IsHalfOf(), rhs); EXPECT_THAT(lhs, m); // Changing rhs now shouldn't affect m, which made a copy of rhs. rhs.push_back(6); EXPECT_THAT(lhs, m); } TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) { const int lhs[] = {1, 2, 3}; vector rhs; rhs.push_back(4); rhs.push_back(6); rhs.push_back(2); EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs)); EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); } TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { const int rhs[] = {1, 2, 3}; vector lhs; lhs.push_back(4); lhs.push_back(2); lhs.push_back(6); EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs)); EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); } #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { const vector lhs{2, 4, 6}; EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedPointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; const int rhs[1] = {0}; EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); EXPECT_EQ("which has 2 elements", Explain(UnorderedPointwise(Gt(), rhs), lhs)); const int rhs2[3] = {0, 1, 2}; EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2))); } TEST(UnorderedPointwiseTest, RejectsWrongContent) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 6, 6}; EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); EXPECT_EQ("where the following elements don't match any matchers:\n" "element #1: 2", Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); } TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 4, 6}; EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); } TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {6, 4, 2}; EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); } TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {4, 6, 2}; const Matcher> m1 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); // This type works as a std::tuple can be // implicitly cast to std::tuple. const Matcher> m2 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); } // Sample optional type implementation with minimal requirements for use with // Optional matcher. class SampleOptionalInt { public: typedef int value_type; explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {} SampleOptionalInt() : value_(0), has_value_(false) {} operator bool() const { return has_value_; } const int& operator*() const { return value_; } private: int value_; bool has_value_; }; TEST(OptionalTest, DescribesSelf) { const Matcher m = Optional(Eq(1)); EXPECT_EQ("value is equal to 1", Describe(m)); } TEST(OptionalTest, ExplainsSelf) { const Matcher m = Optional(Eq(1)); EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1))); EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2))); } TEST(OptionalTest, MatchesNonEmptyOptional) { const Matcher m1 = Optional(1); const Matcher m2 = Optional(Eq(2)); const Matcher m3 = Optional(Lt(3)); SampleOptionalInt opt(1); EXPECT_TRUE(m1.Matches(opt)); EXPECT_FALSE(m2.Matches(opt)); EXPECT_TRUE(m3.Matches(opt)); } TEST(OptionalTest, DoesNotMatchNullopt) { const Matcher m = Optional(1); SampleOptionalInt empty; EXPECT_FALSE(m.Matches(empty)); } class SampleVariantIntString { public: SampleVariantIntString(int i) : i_(i), has_int_(true) {} SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} template friend bool holds_alternative(const SampleVariantIntString& value) { return value.has_int_ == internal::IsSame::value; } template friend const T& get(const SampleVariantIntString& value) { return value.get_impl(static_cast(nullptr)); } private: const int& get_impl(int*) const { return i_; } const std::string& get_impl(std::string*) const { return s_; } int i_; std::string s_; bool has_int_; }; TEST(VariantTest, DescribesSelf) { const Matcher m = VariantWith(Eq(1)); EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " "'.*' and the value is equal to 1")); } TEST(VariantTest, ExplainsSelf) { const Matcher m = VariantWith(Eq(1)); EXPECT_THAT(Explain(m, SampleVariantIntString(1)), ContainsRegex("whose value 1")); EXPECT_THAT(Explain(m, SampleVariantIntString("A")), HasSubstr("whose value is not of type '")); EXPECT_THAT(Explain(m, SampleVariantIntString(2)), "whose value 2 doesn't match"); } TEST(VariantTest, FullMatch) { Matcher m = VariantWith(Eq(1)); EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); m = VariantWith(Eq("1")); EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); } TEST(VariantTest, TypeDoesNotMatch) { Matcher m = VariantWith(Eq(1)); EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); m = VariantWith(Eq("1")); EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); } TEST(VariantTest, InnerDoesNotMatch) { Matcher m = VariantWith(Eq(1)); EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); m = VariantWith(Eq("1")); EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); } class SampleAnyType { public: explicit SampleAnyType(int i) : index_(0), i_(i) {} explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} template friend const T* any_cast(const SampleAnyType* any) { return any->get_impl(static_cast(nullptr)); } private: int index_; int i_; std::string s_; const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } const std::string* get_impl(std::string*) const { return index_ == 1 ? &s_ : nullptr; } }; TEST(AnyWithTest, FullMatch) { Matcher m = AnyWith(Eq(1)); EXPECT_TRUE(m.Matches(SampleAnyType(1))); } TEST(AnyWithTest, TestBadCastType) { Matcher m = AnyWith(Eq("fail")); EXPECT_FALSE(m.Matches(SampleAnyType(1))); } #if GTEST_LANG_CXX11 TEST(AnyWithTest, TestUseInContainers) { std::vector a; a.emplace_back(1); a.emplace_back(2); a.emplace_back(3); EXPECT_THAT( a, ElementsAreArray({AnyWith(1), AnyWith(2), AnyWith(3)})); std::vector b; b.emplace_back("hello"); b.emplace_back("merhaba"); b.emplace_back("salut"); EXPECT_THAT(b, ElementsAreArray({AnyWith("hello"), AnyWith("merhaba"), AnyWith("salut")})); } #endif // GTEST_LANG_CXX11 TEST(AnyWithTest, TestCompare) { EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); } TEST(AnyWithTest, DescribesSelf) { const Matcher m = AnyWith(Eq(1)); EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " "'.*' and the value is equal to 1")); } TEST(AnyWithTest, ExplainsSelf) { const Matcher m = AnyWith(Eq(1)); EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); EXPECT_THAT(Explain(m, SampleAnyType("A")), HasSubstr("whose value is not of type '")); EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); } #if GTEST_LANG_CXX11 TEST(PointeeTest, WorksOnMoveOnlyType) { std::unique_ptr p(new int(3)); EXPECT_THAT(p, Pointee(Eq(3))); EXPECT_THAT(p, Not(Pointee(Eq(2)))); } TEST(NotTest, WorksOnMoveOnlyType) { std::unique_ptr p(new int(3)); EXPECT_THAT(p, Pointee(Eq(3))); EXPECT_THAT(p, Not(Pointee(Eq(2)))); } #endif // GTEST_LANG_CXX11 } // namespace gmock_matchers_test } // namespace testing diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 4d8373cf..79d208a6 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -1,255 +1,256 @@ // Copyright 2005, 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. // // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the Message class. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #include +#include #include "gtest/internal/gtest-port.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // Ensures that there is at least one operator<< in the global namespace. // See Message& operator<<(...) below for why. void operator<<(const testing::internal::Secret&, int); namespace testing { // The Message class works like an ostream repeater. // // Typical usage: // // 1. You stream a bunch of values to a Message object. // It will remember the text in a stringstream. // 2. Then you stream the Message object to an ostream. // This causes the text in the Message to be streamed // to the ostream. // // For example; // // testing::Message foo; // foo << 1 << " != " << 2; // std::cout << foo; // // will print "1 != 2". // // Message is not intended to be inherited from. In particular, its // destructor is not virtual. // // Note that stringstream behaves differently in gcc and in MSVC. You // can stream a NULL char pointer to it in the former, but not in the // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as // "(null)". class GTEST_API_ Message { private: // The type of basic IO manipulators (endl, ends, and flush) for // narrow streams. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); public: // Constructs an empty Message. Message(); // Copy constructor. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT *ss_ << msg.GetString(); } // Constructs a Message from a C-string. explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } #if GTEST_OS_SYMBIAN // Streams a value (either a pointer or not) to this object. template inline Message& operator <<(const T& value) { StreamHelper(typename internal::is_pointer::type(), value); return *this; } #else // Streams a non-pointer value to this object. template inline Message& operator <<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these // overloads are visible in either the std namespace or the global // namespace, but not other namespaces, including the testing // namespace which Google Test's Message class is in. // // To allow STL containers (and other types that has a << operator // defined in the global namespace) to be used in Google Test // assertions, testing::Message must access the custom << operator // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. using ::operator <<; *ss_ << val; return *this; } // Streams a pointer value to this object. // // This function is an overload of the previous one. When you // stream a pointer to a Message, this definition will be used as it // is more specialized. (The C++ Standard, section // [temp.func.order].) If you stream a non-pointer, then the // previous definition will be used. // // The reason for this overload is that streaming a NULL pointer to // ostream is undefined behavior. Depending on the compiler, you // may get "0", "(nil)", "(null)", or an access violation. To // ensure consistent result across compilers, we always treat NULL // as "(null)". template inline Message& operator <<(T* const& pointer) { // NOLINT if (pointer == nullptr) { *ss_ << "(null)"; } else { *ss_ << pointer; } return *this; } #endif // GTEST_OS_SYMBIAN // Since the basic IO manipulators are overloaded for both narrow // and wide streams, we have to provide this specialized definition // of operator <<, even though its body is the same as the // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. Message& operator <<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. Message& operator <<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& operator <<(const wchar_t* wide_c_str); Message& operator <<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::wstring& wstr); #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. std::string GetString() const; private: #if GTEST_OS_SYMBIAN // These are needed as the Nokia Symbian Compiler cannot decide between // const T& and const T* in a function template. The Nokia compiler _can_ // decide between class template specializations for T and T*, so a // tr1::type_traits-like is_pointer works, and we can overload on that. template inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { if (pointer == nullptr) { *ss_ << "(null)"; } else { *ss_ << pointer; } } template inline void StreamHelper(internal::false_type /*is_pointer*/, const T& value) { // See the comments in Message& operator <<(const T&) above for why // we need this using statement. using ::operator <<; *ss_ << value; } #endif // GTEST_OS_SYMBIAN // We'll hold the text streamed to this object here. - const internal::scoped_ptr< ::std::stringstream> ss_; + const std::unique_ptr< ::std::stringstream> ss_; // We declare (but don't implement) this to prevent the compiler // from implementing the assignment operator. void operator=(const Message&); }; // Streams a Message to an ostream. inline std::ostream& operator <<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } namespace internal { // Converts a streamable value to an std::string. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". template std::string StreamableToString(const T& streamable) { return (Message() << streamable).GetString(); } } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index c19ee2b0..e5979a9c 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -1,2373 +1,2374 @@ // Copyright 2005, 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. // // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the public API for Google Test. It should be // included by any test program that uses Google Test. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! // // Acknowledgment: Google Test borrowed the idea of automatic test // registration from Barthelemy Dagenais' (barthelemy@prologique.com) // easyUnit framework. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_ #include +#include #include #include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" #include "gtest/gtest-death-test.h" #include "gtest/gtest-message.h" #include "gtest/gtest-param-test.h" #include "gtest/gtest-printers.h" #include "gtest/gtest_prod.h" #include "gtest/gtest-test-part.h" #include "gtest/gtest-typed-test.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // Depending on the platform, different string classes are available. // On Linux, in addition to ::std::string, Google also makes use of // class ::string, which has the same interface as ::std::string, but // has a different implementation. // // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that // ::string is available AND is a distinct type to ::std::string, or // define it to 0 to indicate otherwise. // // If ::std::string and ::string are the same class on your platform // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0. // // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined // heuristically. namespace testing { // Silence C4100 (unreferenced formal parameter) and 4805 // unsafe mix of type 'const int' and type 'const bool' #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4805) # pragma warning(disable:4100) #endif // Declares the flags. // This flag temporary enables the disabled tests. GTEST_DECLARE_bool_(also_run_disabled_tests); // This flag brings the debugger on an assertion failure. GTEST_DECLARE_bool_(break_on_failure); // This flag controls whether Google Test catches all test-thrown exceptions // and logs them as failures. GTEST_DECLARE_bool_(catch_exceptions); // This flag enables using colors in terminal output. Available values are // "yes" to enable colors, "no" (disable colors), or "auto" (the default) // to let Google Test decide. GTEST_DECLARE_string_(color); // This flag sets up the filter to select by name using a glob pattern // the tests to run. If the filter is not given all tests are executed. GTEST_DECLARE_string_(filter); // This flag controls whether Google Test installs a signal handler that dumps // debugging information when fatal signals are raised. GTEST_DECLARE_bool_(install_failure_signal_handler); // This flag causes the Google Test to list tests. None of the tests listed // are actually run if the flag is provided. GTEST_DECLARE_bool_(list_tests); // This flag controls whether Google Test emits a detailed XML report to a file // in addition to its normal textual output. GTEST_DECLARE_string_(output); // This flags control whether Google Test prints the elapsed time for each // test. GTEST_DECLARE_bool_(print_time); // This flags control whether Google Test prints UTF8 characters as text. GTEST_DECLARE_bool_(print_utf8); // This flag specifies the random number seed. GTEST_DECLARE_int32_(random_seed); // This flag sets how many times the tests are repeated. The default value // is 1. If the value is -1 the tests are repeating forever. GTEST_DECLARE_int32_(repeat); // This flag controls whether Google Test includes Google Test internal // stack frames in failure stack traces. GTEST_DECLARE_bool_(show_internal_stack_frames); // When this flag is specified, tests' order is randomized on every iteration. GTEST_DECLARE_bool_(shuffle); // This flag specifies the maximum number of stack frames to be // printed in a failure message. GTEST_DECLARE_int32_(stack_trace_depth); // When this flag is specified, a failed assertion will throw an // exception if exceptions are enabled, or exit the program with a // non-zero code otherwise. For use with an external test framework. GTEST_DECLARE_bool_(throw_on_failure); // When this flag is set with a "host:port" string, on supported // platforms test results are streamed to the specified port on // the specified host machine. GTEST_DECLARE_string_(stream_result_to); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DECLARE_string_(flagfile); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; namespace internal { class AssertHelper; class DefaultGlobalTestPartResultReporter; class ExecDeathTest; class NoExecDeathTest; class FinalSuccessChecker; class GTestFlagSaver; class StreamingListenerTest; class TestResultAccessor; class TestEventListenersAccessor; class TestEventRepeater; class UnitTestRecordPropertyTestHelper; class WindowsDeathTest; class FuchsiaDeathTest; class UnitTestImpl* GetUnitTestImpl(); void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message); } // namespace internal // The friend relationship of some of these classes is cyclic. // If we don't forward declare them the compiler might confuse the classes // in friendship clauses with same named classes on the scope. class Test; class TestCase; class TestInfo; class UnitTest; // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object // remembers a non-empty message that describes how it failed. // // To create an instance of this class, use one of the factory functions // (AssertionSuccess() and AssertionFailure()). // // This class is useful for two purposes: // 1. Defining predicate functions to be used with Boolean test assertions // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts // 2. Defining predicate-format functions to be // used with predicate assertions (ASSERT_PRED_FORMAT*, etc). // // For example, if you define IsEven predicate: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) // will print the message // // Value of: IsEven(Fib(5)) // Actual: false (5 is odd) // Expected: true // // instead of a more opaque // // Value of: IsEven(Fib(5)) // Actual: false // Expected: true // // in case IsEven is a simple Boolean predicate. // // If you expect your predicate to be reused and want to support informative // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up // about half as often as positive ones in our tests), supply messages for // both success and failure cases: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess() << n << " is even"; // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print // // Value of: IsEven(Fib(6)) // Actual: true (8 is even) // Expected: false // // NB: Predicates that support negative Boolean assertions have reduced // performance in positive ones so be careful not to use them in tests // that have lots (tens of thousands) of positive Boolean assertions. // // To use this class with EXPECT_PRED_FORMAT assertions such as: // // // Verifies that Foo() returns an even number. // EXPECT_PRED_FORMAT1(IsEven, Foo()); // // you need to define: // // testing::AssertionResult IsEven(const char* expr, int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() // << "Expected: " << expr << " is even\n Actual: it's " << n; // } // // If Foo() returns 5, you will see the following message: // // Expected: Foo() is even // Actual: it's 5 // class GTEST_API_ AssertionResult { public: // Copy constructor. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult(const AssertionResult& other); #if defined(_MSC_VER) && _MSC_VER < 1910 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) #endif // Used in the EXPECT_TRUE/FALSE(bool_expression). // // T must be contextually convertible to bool. // // The second parameter prevents this overload from being considered if // the argument is implicitly convertible to AssertionResult. In that case // we want AssertionResult's copy constructor to be used. template explicit AssertionResult( const T& success, typename internal::EnableIf< !internal::ImplicitlyConvertible::value>::type* /*enabler*/ = nullptr) : success_(success) {} #if defined(_MSC_VER) && _MSC_VER < 1910 GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Assignment operator. AssertionResult& operator=(AssertionResult other) { swap(other); return *this; } // Returns true iff the assertion succeeded. operator bool() const { return success_; } // NOLINT // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult operator!() const; // Returns the text streamed into this AssertionResult. Test assertions // use it when they fail (i.e., the predicate's outcome doesn't match the // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. const char* message() const { return message_.get() != nullptr ? message_->c_str() : ""; } // FIXME: Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } // Streams a custom failure message into this object. template AssertionResult& operator<<(const T& value) { AppendMessage(Message() << value); return *this; } // Allows streaming basic output manipulators such as endl or flush into // this object. AssertionResult& operator<<( ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { AppendMessage(Message() << basic_manipulator); return *this; } private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { if (message_.get() == nullptr) message_.reset(new ::std::string); message_->append(a_message.GetString().c_str()); } // Swap the contents of this AssertionResult with other. void swap(AssertionResult& other); // Stores result of the assertion predicate. bool success_; // Stores the message describing the condition in case the expectation // construct is not satisfied with the predicate's outcome. // Referenced via a pointer to avoid taking too much stack frame space // with test assertions. - internal::scoped_ptr< ::std::string> message_; + std::unique_ptr< ::std::string> message_; }; // Makes a successful assertion result. GTEST_API_ AssertionResult AssertionSuccess(); // Makes a failed assertion result. GTEST_API_ AssertionResult AssertionFailure(); // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << msg. GTEST_API_ AssertionResult AssertionFailure(const Message& msg); } // namespace testing // Includes the auto-generated header that implements a family of generic // predicate assertion macros. This include comes late because it relies on // APIs declared above. #include "gtest/gtest_pred_impl.h" namespace testing { // The abstract class that all tests inherit from. // // In Google Test, a unit test program contains one or many TestCases, and // each TestCase contains one or many Tests. // // When you define a test using the TEST macro, you don't need to // explicitly derive from Test - the TEST macro automatically does // this for you. // // The only time you derive from Test is when defining a test fixture // to be used in a TEST_F. For example: // // class FooTest : public testing::Test { // protected: // void SetUp() override { ... } // void TearDown() override { ... } // ... // }; // // TEST_F(FooTest, Bar) { ... } // TEST_F(FooTest, Baz) { ... } // // Test is not copyable. class GTEST_API_ Test { public: friend class TestInfo; // Defines types for pointers to functions that set up and tear down // a test case. typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; // The d'tor is virtual as we intend to inherit from Test. virtual ~Test(); // Sets up the stuff shared by all tests in this test case. // // Google Test will call Foo::SetUpTestCase() before running the first // test in test case Foo. Hence a sub-class can define its own // SetUpTestCase() method to shadow the one defined in the super // class. static void SetUpTestCase() {} // Tears down the stuff shared by all tests in this test case. // // Google Test will call Foo::TearDownTestCase() after running the last // test in test case Foo. Hence a sub-class can define its own // TearDownTestCase() method to shadow the one defined in the super // class. static void TearDownTestCase() {} // Returns true iff the current test has a fatal failure. static bool HasFatalFailure(); // Returns true iff the current test has a non-fatal failure. static bool HasNonfatalFailure(); // Returns true iff the current test was skipped. static bool IsSkipped(); // Returns true iff the current test has a (either fatal or // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } // Logs a property for the current test, test case, or for the entire // invocation of the test program when used outside of the context of a // test case. Only the last value for a given key is remembered. These // are public static so they can be called from utility functions that are // not members of the test fixture. Calls to RecordProperty made during // lifespan of the test (from the moment its constructor starts to the // moment its destructor finishes) will be output in XML as attributes of // the element. Properties recorded from fixture's // SetUpTestCase or TearDownTestCase are logged as attributes of the // corresponding element. Calls to RecordProperty made in the // global context (before or after invocation of RUN_ALL_TESTS and from // SetUp/TearDown method of Environment objects registered with Google // Test) will be output as attributes of the element. static void RecordProperty(const std::string& key, const std::string& value); static void RecordProperty(const std::string& key, int value); protected: // Creates a Test object. Test(); // Sets up the test fixture. virtual void SetUp(); // Tears down the test fixture. virtual void TearDown(); private: // Returns true iff the current test has the same fixture class as // the first test in the current test case. static bool HasSameFixtureClass(); // Runs the test after the test fixture has been set up. // // A sub-class must implement this to define the test logic. // // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. // Instead, use the TEST or TEST_F macro. virtual void TestBody() = 0; // Sets up, executes, and tears down the test. void Run(); // Deletes self. We deliberately pick an unusual name for this // internal method to avoid clashing with names used in user TESTs. void DeleteSelf_() { delete this; } - const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; + const std::unique_ptr gtest_flag_saver_; // Often a user misspells SetUp() as Setup() and spends a long time // wondering why it is never called by Google Test. The declaration of // the following method is solely for catching such an error at // compile time: // // - The return type is deliberately chosen to be not void, so it // will be a conflict if void Setup() is declared in the user's // test fixture. // // - This method is private, so it will be another compiler error // if the method is called from the user's test fixture. // // DO NOT OVERRIDE THIS FUNCTION. // // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; } // We disallow copying Tests. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); }; typedef internal::TimeInMillis TimeInMillis; // A copyable object representing a user specified test property which can be // output as a key/value string pair. // // Don't inherit from TestProperty as its destructor is not virtual. class TestProperty { public: // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. TestProperty(const std::string& a_key, const std::string& a_value) : key_(a_key), value_(a_value) { } // Gets the user supplied key. const char* key() const { return key_.c_str(); } // Gets the user supplied value. const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. std::string key_; // The value supplied by the user. std::string value_; }; // The result of a single Test. This includes a list of // TestPartResults, a list of TestProperties, a count of how many // death tests there are in the Test, and how much time it took to run // the Test. // // TestResult is not copyable. class GTEST_API_ TestResult { public: // Creates an empty TestResult. TestResult(); // D'tor. Do not inherit from TestResult. ~TestResult(); // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int total_part_count() const; // Returns the number of the test properties. int test_property_count() const; // Returns true iff the test passed (i.e. no test part failed). bool Passed() const { return !Skipped() && !Failed(); } // Returns true iff the test was skipped. bool Skipped() const; // Returns true iff the test failed. bool Failed() const; // Returns true iff the test fatally failed. bool HasFatalFailure() const; // Returns true iff the test has a non-fatal failure. bool HasNonfatalFailure() const; // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test part result among all the results. i can range from 0 // to total_part_count() - 1. If i is not in that range, aborts the program. const TestPartResult& GetTestPartResult(int i) const; // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& GetTestProperty(int i) const; private: friend class TestInfo; friend class TestCase; friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; friend class internal::TestResultAccessor; friend class internal::UnitTestImpl; friend class internal::WindowsDeathTest; friend class internal::FuchsiaDeathTest; // Gets the vector of TestPartResults. const std::vector& test_part_results() const { return test_part_results_; } // Gets the vector of TestProperties. const std::vector& test_properties() const { return test_properties_; } // Sets the elapsed time. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } // Adds a test property to the list. The property is validated and may add // a non-fatal failure if invalid (e.g., if it conflicts with reserved // key names). If a property is already recorded for the same key, the // value will be updated, rather than storing multiple values for the same // key. xml_element specifies the element for which the property is being // recorded and is used for validation. void RecordProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. // FIXME: Validate attribute names are legal and human readable. static bool ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a test part result to the list. void AddTestPartResult(const TestPartResult& test_part_result); // Returns the death test count. int death_test_count() const { return death_test_count_; } // Increments the death test count, returning the new count. int increment_death_test_count() { return ++death_test_count_; } // Clears the test part results. void ClearTestPartResults(); // Clears the object. void Clear(); // Protects mutable state of the property vector and of owned // properties, whose values may be updated. internal::Mutex test_properites_mutex_; // The vector of TestPartResults std::vector test_part_results_; // The vector of TestProperties std::vector test_properties_; // Running count of death tests. int death_test_count_; // The elapsed time, in milliseconds. TimeInMillis elapsed_time_; // We disallow copying TestResult. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); }; // class TestResult // A TestInfo object stores the following information about a test: // // Test case name // Test name // Whether the test should be run // A function pointer that creates the test object when invoked // Test result // // The constructor of TestInfo registers itself with the UnitTest // singleton such that the RUN_ALL_TESTS() macro knows which tests to // run. class GTEST_API_ TestInfo { public: // Destructs a TestInfo object. This function is not virtual, so // don't inherit from TestInfo. ~TestInfo(); // Returns the test case name. const char* test_case_name() const { return test_case_name_.c_str(); } // Returns the test name. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a typed // or a type-parameterized test. const char* type_param() const { if (type_param_.get() != nullptr) return type_param_->c_str(); return nullptr; } // Returns the text representation of the value parameter, or NULL if this // is not a value-parameterized test. const char* value_param() const { if (value_param_.get() != nullptr) return value_param_->c_str(); return nullptr; } // Returns the file name where this test is defined. const char* file() const { return location_.file.c_str(); } // Returns the line where this test is defined. int line() const { return location_.line; } // Return true if this test should not be run because it's in another shard. bool is_in_another_shard() const { return is_in_another_shard_; } // Returns true if this test should run, that is if the test is not // disabled (or it is disabled but the also_run_disabled_tests flag has // been specified) and its full name matches the user-specified filter. // // Google Test allows the user to filter the tests by their full names. // The full name of a test Bar in test case Foo is defined as // "Foo.Bar". Only the tests that match the filter will run. // // A filter is a colon-separated list of glob (not regex) patterns, // optionally followed by a '-' and a colon-separated list of // negative patterns (tests to exclude). A test is run if it // matches one of the positive patterns and does not match any of // the negative patterns. // // For example, *A*:Foo.* is a filter that matches any string that // contains the character 'A' or starts with "Foo.". bool should_run() const { return should_run_; } // Returns true iff this test will appear in the XML report. bool is_reportable() const { // The XML report includes tests matching the filter, excluding those // run in other shards. return matches_filter_ && !is_in_another_shard_; } // Returns the result of the test. const TestResult* result() const { return &result_; } private: #if GTEST_HAS_DEATH_TEST friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; friend class TestCase; friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, internal::CodeLocation code_location, internal::TypeId fixture_class_id, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, internal::TestFactoryBase* factory); // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. TestInfo(const std::string& test_case_name, const std::string& name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); // Increments the number of death tests encountered in this test so // far. int increment_death_test_count() { return result_.increment_death_test_count(); } // Creates the test object, runs it, records its result, and then // deletes it. void Run(); static void ClearTestResult(TestInfo* test_info) { test_info->result_.Clear(); } // These fields are immutable properties of the test. const std::string test_case_name_; // Test case name const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. - const internal::scoped_ptr type_param_; + const std::unique_ptr type_param_; // Text representation of the value parameter, or NULL if this is not a // value-parameterized test. - const internal::scoped_ptr value_param_; + const std::unique_ptr value_param_; internal::CodeLocation location_; const internal::TypeId fixture_class_id_; // ID of the test fixture class bool should_run_; // True iff this test should run bool is_disabled_; // True iff this test is disabled bool matches_filter_; // True if this test matches the // user-specified filter. bool is_in_another_shard_; // Will be run in another shard. internal::TestFactoryBase* const factory_; // The factory that creates // the test object // This field is mutable and needs to be reset before running the // test for the second time. TestResult result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); }; // A test case, which consists of a vector of TestInfos. // // TestCase is not copyable. class GTEST_API_ TestCase { public: // Creates a TestCase with the given name. // // TestCase does NOT have a default constructor. Always use this // constructor to create a TestCase object. // // Arguments: // // name: name of the test case // a_type_param: the name of the test's type parameter, or NULL if // this is not a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase(const char* name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Destructor of TestCase. virtual ~TestCase(); // Gets the name of the TestCase. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a // type-parameterized test case. const char* type_param() const { if (type_param_.get() != nullptr) return type_param_->c_str(); return nullptr; } // Returns true if any test in this test case should run. bool should_run() const { return should_run_; } // Gets the number of successful tests in this test case. int successful_test_count() const; // Gets the number of skipped tests in this test case. int skipped_test_count() const; // Gets the number of failed tests in this test case. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests in this test case. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Get the number of tests in this test case that should run. int test_to_run_count() const; // Gets the number of all tests in this test case. int total_test_count() const; // Returns true iff the test case passed. bool Passed() const { return !Failed(); } // Returns true iff the test case failed. bool Failed() const { return failed_test_count() > 0; } // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* GetTestInfo(int i) const; // Returns the TestResult that holds test properties recorded during // execution of SetUpTestCase and TearDownTestCase. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } private: friend class Test; friend class internal::UnitTestImpl; // Gets the (mutable) vector of TestInfos in this TestCase. std::vector& test_info_list() { return test_info_list_; } // Gets the (immutable) vector of TestInfos in this TestCase. const std::vector& test_info_list() const { return test_info_list_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* GetMutableTestInfo(int i); // Sets the should_run member. void set_should_run(bool should) { should_run_ = should; } // Adds a TestInfo to this test case. Will delete the TestInfo upon // destruction of the TestCase object. void AddTestInfo(TestInfo * test_info); // Clears the results of all tests in this test case. void ClearResult(); // Clears the results of all tests in the given test case. static void ClearTestCaseResult(TestCase* test_case) { test_case->ClearResult(); } // Runs every test in this TestCase. void Run(); // Runs SetUpTestCase() for this TestCase. This wrapper is needed // for catching exceptions thrown from SetUpTestCase(). void RunSetUpTestCase() { (*set_up_tc_)(); } // Runs TearDownTestCase() for this TestCase. This wrapper is // needed for catching exceptions thrown from TearDownTestCase(). void RunTearDownTestCase() { (*tear_down_tc_)(); } // Returns true iff test passed. static bool TestPassed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Passed(); } // Returns true iff test skipped. static bool TestSkipped(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Skipped(); } // Returns true iff test failed. static bool TestFailed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Failed(); } // Returns true iff the test is disabled and will be reported in the XML // report. static bool TestReportableDisabled(const TestInfo* test_info) { return test_info->is_reportable() && test_info->is_disabled_; } // Returns true iff test is disabled. static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } // Returns true iff this test will appear in the XML report. static bool TestReportable(const TestInfo* test_info) { return test_info->is_reportable(); } // Returns true if the given test should run. static bool ShouldRunTest(const TestInfo* test_info) { return test_info->should_run(); } // Shuffles the tests in this test case. void ShuffleTests(internal::Random* random); // Restores the test order to before the first shuffle. void UnshuffleTests(); // Name of the test case. std::string name_; // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. - const internal::scoped_ptr type_param_; + const std::unique_ptr type_param_; // The vector of TestInfos in their original order. It owns the // elements in the vector. std::vector test_info_list_; // Provides a level of indirection for the test list to allow easy // shuffling and restoring the test order. The i-th element in this // vector is the index of the i-th test in the shuffled test list. std::vector test_indices_; // Pointer to the function that sets up the test case. Test::SetUpTestCaseFunc set_up_tc_; // Pointer to the function that tears down the test case. Test::TearDownTestCaseFunc tear_down_tc_; // True iff any test in this test case should run. bool should_run_; // Elapsed time, in milliseconds. TimeInMillis elapsed_time_; // Holds test properties recorded during execution of SetUpTestCase and // TearDownTestCase. TestResult ad_hoc_test_result_; // We disallow copying TestCases. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); }; // An Environment object is capable of setting up and tearing down an // environment. You should subclass this to define your own // environment(s). // // An Environment object does the set-up and tear-down in virtual // methods SetUp() and TearDown() instead of the constructor and the // destructor, as: // // 1. You cannot safely throw from a destructor. This is a problem // as in some cases Google Test is used where exceptions are enabled, and // we may want to implement ASSERT_* using exceptions where they are // available. // 2. You cannot use ASSERT_* directly in a constructor or // destructor. class Environment { public: // The d'tor is virtual as we need to subclass Environment. virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} // Override this to define how to tear down the environment. virtual void TearDown() {} private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; } }; #if GTEST_HAS_EXCEPTIONS // Exception which can be thrown from TestEventListener::OnTestPartResult. class GTEST_API_ AssertionException : public internal::GoogleTestFailureException { public: explicit AssertionException(const TestPartResult& result) : GoogleTestFailureException(result) {} }; #endif // GTEST_HAS_EXCEPTIONS // The interface for tracing execution of tests. The methods are organized in // the order the corresponding events are fired. class TestEventListener { public: virtual ~TestEventListener() {} // Fired before any test activity starts. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; // Fired before each iteration of tests starts. There may be more than // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration // index, starting from 0. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration) = 0; // Fired before environment set-up for each iteration of tests starts. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; // Fired after environment set-up for each iteration of tests ends. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; // Fired before the test case starts. virtual void OnTestCaseStart(const TestCase& test_case) = 0; // Fired before the test starts. virtual void OnTestStart(const TestInfo& test_info) = 0; // Fired after a failed assertion or a SUCCEED() invocation. // If you want to throw an exception from this function to skip to the next // TEST, it must be AssertionException defined above, or inherited from it. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; // Fired after the test ends. virtual void OnTestEnd(const TestInfo& test_info) = 0; // Fired after the test case ends. virtual void OnTestCaseEnd(const TestCase& test_case) = 0; // Fired before environment tear-down for each iteration of tests starts. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; // Fired after environment tear-down for each iteration of tests ends. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; }; // The convenience class for users who need to override just one or two // methods and are not concerned that a possible change to a signature of // the methods they override will not be caught during the build. For // comments about each method please see the definition of TestEventListener // above. class EmptyTestEventListener : public TestEventListener { public: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} virtual void OnTestStart(const TestInfo& /*test_info*/) {} virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} virtual void OnTestEnd(const TestInfo& /*test_info*/) {} virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} }; // TestEventListeners lets users add listeners to track events in Google Test. class GTEST_API_ TestEventListeners { public: TestEventListeners(); ~TestEventListeners(); // Appends an event listener to the end of the list. Google Test assumes // the ownership of the listener (i.e. it will delete the listener when // the test program finishes). void Append(TestEventListener* listener); // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* Release(TestEventListener* listener); // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the caller and makes this // function return NULL the next time. TestEventListener* default_result_printer() const { return default_result_printer_; } // Returns the standard listener responsible for the default XML output // controlled by the --gtest_output=xml flag. Can be removed from the // listeners list by users who want to shut down the default XML output // controlled by this flag and substitute it with custom one. Note that // removing this object from the listener list with Release transfers its // ownership to the caller and makes this function return NULL the next // time. TestEventListener* default_xml_generator() const { return default_xml_generator_; } private: friend class TestCase; friend class TestInfo; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::NoExecDeathTest; friend class internal::TestEventListenersAccessor; friend class internal::UnitTestImpl; // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* repeater(); // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultResultPrinter(TestEventListener* listener); // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultXmlGenerator(TestEventListener* listener); // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool EventForwardingEnabled() const; void SuppressEventForwarding(); // The actual list of listeners. internal::TestEventRepeater* repeater_; // Listener responsible for the standard result output. TestEventListener* default_result_printer_; // Listener responsible for the creation of the XML output file. TestEventListener* default_xml_generator_; // We disallow copying TestEventListeners. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); }; // A UnitTest consists of a vector of TestCases. // // This is a singleton class. The only instance of UnitTest is // created when UnitTest::GetInstance() is first called. This // instance is never deleted. // // UnitTest is not copyable. // // This class is thread-safe as long as the methods are called // according to their specification. class GTEST_API_ UnitTest { public: // Gets the singleton UnitTest object. The first time this method // is called, a UnitTest object is constructed and returned. // Consecutive calls will return the same object. static UnitTest* GetInstance(); // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // This method can only be called from the main thread. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. int Run() GTEST_MUST_USE_RESULT_; // Returns the working directory when the first TEST() or TEST_F() // was executed. The UnitTest object owns the string. const char* original_working_dir() const; // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; // Returns the ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_); // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of skipped tests. int skipped_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const; // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const; // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const; // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const; // Returns the TestResult containing information on test failures and // properties logged outside of individual test cases. const TestResult& ad_hoc_test_result() const; // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& listeners(); private: // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in // the order they were registered. After all tests in the program // have finished, all global test environments will be torn-down in // the *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // This method can only be called from the main thread. Environment* AddEnvironment(Environment* env); // Adds a TestPartResult to the current TestResult object. All // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. void AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_); // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestCase's ad_hoc_test_result_ when invoked // from SetUpTestCase or TearDownTestCase, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void RecordProperty(const std::string& key, const std::string& value); // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i); // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; } // These classes and functions are friends as they need to access private // members of UnitTest. friend class ScopedTrace; friend class Test; friend class internal::AssertHelper; friend class internal::StreamingListenerTest; friend class internal::UnitTestRecordPropertyTestHelper; friend Environment* AddGlobalTestEnvironment(Environment* env); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend void internal::ReportFailureInUnknownLocation( TestPartResult::Type result_type, const std::string& message); // Creates an empty UnitTest. UnitTest(); // D'tor virtual ~UnitTest(); // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. mutable internal::Mutex mutex_; // Opaque implementation object. This field is never changed once // the object is constructed. We don't mark it as const here, as // doing so will cause a warning in the constructor of UnitTest. // Mutable state in *impl_ is protected by mutex_. internal::UnitTestImpl* impl_; // We disallow copying UnitTest. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); }; // A convenient wrapper for adding an environment for the test // program. // // You should call this before RUN_ALL_TESTS() is called, probably in // main(). If you use gtest_main, you need to call this before main() // starts for it to take effect. For example, you can define a global // variable like this: // // testing::Environment* const foo_env = // testing::AddGlobalTestEnvironment(new FooEnvironment); // // However, we strongly recommend you to write your own main() and // call AddGlobalTestEnvironment() there, as relying on initialization // of global variables makes the code harder to read and may cause // problems when you register multiple environments from different // translation units and the environments have dependencies among them // (remember that the compiler doesn't guarantee the order in which // global variables from different translation units are initialized). inline Environment* AddGlobalTestEnvironment(Environment* env) { return UnitTest::GetInstance()->AddEnvironment(env); } // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. GTEST_API_ void InitGoogleTest(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { // Separate the error generating code from the code path to reduce the stack // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers // when calling EXPECT_* in a tight loop. template AssertionResult CmpHelperEQFailure(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(rhs, lhs), false); } // This block of code defines operator==/!= // to block lexical scope lookup. // It prevents using invalid operator==/!= defined at namespace scope. struct faketype {}; inline bool operator==(faketype, faketype) { return true; } inline bool operator!=(faketype, faketype) { return false; } // The helper function for {ASSERT|EXPECT}_EQ. template AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { if (lhs == rhs) { return AssertionSuccess(); } return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs); // The helper class for {ASSERT|EXPECT}_EQ. The template argument // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() // is a null pointer literal. The following default implementation is // for lhs_is_null_literal being false. template class EqHelper { public: // This templatized version is for the general case. template static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous // enums can be implicitly cast to BiggestInt. // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } }; // This specialization is used when the first argument to ASSERT_EQ() // is a null pointer literal, like NULL, false, or 0. template <> class EqHelper { public: // We define two overloaded versions of Compare(). The first // version will be picked when the second argument to ASSERT_EQ() is // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or // EXPECT_EQ(false, a_bool). template static AssertionResult Compare( const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs, // The following line prevents this overload from being considered if T2 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) // expands to Compare("", "", NULL, my_ptr), which requires a conversion // to match the Secret* in the other overload, which would otherwise make // this template match better. typename EnableIf::value>::type* = nullptr) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // This version will be picked when the second argument to ASSERT_EQ() is a // pointer, e.g. ASSERT_EQ(NULL, a_pointer). template static AssertionResult Compare( const char* lhs_expression, const char* rhs_expression, // We used to have a second template parameter instead of Secret*. That // template parameter would deduce to 'long', making this a better match // than the first overload even without the first overload's EnableIf. // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to // non-pointer argument" (even a deduced integral argument), so the old // implementation caused warnings in user code. Secret* /* lhs (NULL) */, T* rhs) { // We already know that 'lhs' is a null pointer. return CmpHelperEQ(lhs_expression, rhs_expression, static_cast(nullptr), rhs); } }; // Separate the error generating code from the code path to reduce the stack // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers // when calling EXPECT_OP in a tight loop. template AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, const T1& val1, const T2& val2, const char* op) { return AssertionFailure() << "Expected: (" << expr1 << ") " << op << " (" << expr2 << "), actual: " << FormatForComparisonFailureMessage(val1, val2) << " vs " << FormatForComparisonFailureMessage(val2, val1); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste // of similar code. // // For each templatized helper function, we also define an overloaded // version for BiggestInt in order to reduce code bloat and allow // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled // with gcc 4. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ template \ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ const T1& val1, const T2& val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // Implements the helper function for {ASSERT|EXPECT}_NE GTEST_IMPL_CMP_HELPER_(NE, !=); // Implements the helper function for {ASSERT|EXPECT}_LE GTEST_IMPL_CMP_HELPER_(LE, <=); // Implements the helper function for {ASSERT|EXPECT}_LT GTEST_IMPL_CMP_HELPER_(LT, <); // Implements the helper function for {ASSERT|EXPECT}_GE GTEST_IMPL_CMP_HELPER_(GE, >=); // Implements the helper function for {ASSERT|EXPECT}_GT GTEST_IMPL_CMP_HELPER_(GT, >); #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); } // namespace internal // IsSubstring() and IsNotSubstring() are intended to be used as the // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by // themselves. They check whether needle is a substring of haystack // (NULL is considered a substring of itself only), and return an // appropriate error message when they fail. // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { // Helper template function for comparing floating-points. // // Template parameter: // // RawType: the raw floating-point type (either float or double) // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, const char* rhs_expression, RawType lhs_value, RawType rhs_value) { const FloatingPoint lhs(lhs_value), rhs(rhs_value); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } ::std::stringstream lhs_ss; lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) << lhs_value; ::std::stringstream rhs_ss; rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) << rhs_value; return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), false); } // Helper function for implementing ASSERT_NEAR. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // A class that enables one to stream messages to assertion macros class GTEST_API_ AssertHelper { public: // Constructor. AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); // Message assignment is a semantic trick to enable assertion // streaming; see the GTEST_MESSAGE_ macro below. void operator=(const Message& message) const; private: // We put our data in a struct so that the size of the AssertHelper class can // be as small as possible. This is important because gcc is incapable of // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) : type(t), file(srcfile), line(line_num), message(msg) { } TestPartResult::Type const type; const char* const file; int const line; std::string const message; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); }; AssertHelperData* const data_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); }; enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color, const char* fmt, ...); } // namespace internal // The pure interface class that all value-parameterized tests inherit from. // A value-parameterized class must inherit from both ::testing::Test and // ::testing::WithParamInterface. In most cases that just means inheriting // from ::testing::TestWithParam, but more complicated test hierarchies // may need to inherit from Test and WithParamInterface at different levels. // // This interface has support for accessing the test parameter value via // the GetParam() method. // // Use it with one of the parameter generator defining functions, like Range(), // Values(), ValuesIn(), Bool(), and Combine(). // // class FooTest : public ::testing::TestWithParam { // protected: // FooTest() { // // Can use GetParam() here. // } // virtual ~FooTest() { // // Can use GetParam() here. // } // virtual void SetUp() { // // Can use GetParam() here. // } // virtual void TearDown { // // Can use GetParam() here. // } // }; // TEST_P(FooTest, DoesBar) { // // Can use GetParam() method here. // Foo foo; // ASSERT_TRUE(foo.DoesBar(GetParam())); // } // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); template class WithParamInterface { public: typedef T ParamType; virtual ~WithParamInterface() {} // The current parameter value. Is also available in the test fixture's // constructor. static const ParamType& GetParam() { GTEST_CHECK_(parameter_ != nullptr) << "GetParam() can only be called inside a value-parameterized test " << "-- did you intend to write TEST_P instead of TEST_F?"; return *parameter_; } private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface and Test. template friend class internal::ParameterizedTestFactory; }; template const T* WithParamInterface::parameter_ = nullptr; // Most value-parameterized classes can ignore the existence of // WithParamInterface, and can just inherit from ::testing::TestWithParam. template class TestWithParam : public Test, public WithParamInterface { }; // Macros for indicating success/failure in test code. // Skips test in runtime. // Skipping test aborts current function. // Skipped tests are neither successful nor failed. #define GTEST_SKIP() GTEST_SKIP_("Skipped") // ADD_FAILURE unconditionally adds a failure to the current test. // SUCCEED generates a success - it doesn't automatically make the // current test successful, as a test is only successful when it has // no failure. // // EXPECT_* verifies that a certain condition is satisfied. If not, // it behaves like ADD_FAILURE. In particular: // // EXPECT_TRUE verifies that a Boolean condition is true. // EXPECT_FALSE verifies that a Boolean condition is false. // // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except // that they will also abort the current function on failure. People // usually want the fail-fast behavior of FAIL and ASSERT_*, but those // writing data-driven tests often find themselves using ADD_FAILURE // and EXPECT_* more. // Generates a nonfatal failure with a generic message. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") // Generates a nonfatal failure at the given source file location with // a generic message. #define ADD_FAILURE_AT(file, line) \ GTEST_MESSAGE_AT_(file, line, "Failed", \ ::testing::TestPartResult::kNonFatalFailure) // Generates a fatal failure with a generic message. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL # define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED # define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. // // * {ASSERT|EXPECT}_THROW(statement, expected_exception): // Tests that the statement throws the expected exception. // * {ASSERT|EXPECT}_NO_THROW(statement): // Tests that the statement doesn't throw any exception. // * {ASSERT|EXPECT}_ANY_THROW(statement): // Tests that the statement throws an exception. #define EXPECT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) #define EXPECT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define EXPECT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define ASSERT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) #define ASSERT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) #define ASSERT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. #define EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_NONFATAL_FAILURE_) #define EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define ASSERT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_FATAL_FAILURE_) #define ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_FATAL_FAILURE_) // Macros for testing equalities and inequalities. // // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 // // When they are not, Google Test prints both the tested expressions and // their actual values. The values must be compatible built-in types, // or you will get a compiler error. By "compatible" we mean that the // values can be compared by the respective operator. // // Note: // // 1. It is possible to make a user-defined type work with // {ASSERT|EXPECT}_??(), but that requires overloading the // comparison operators and is thus discouraged by the Google C++ // Usage Guide. Therefore, you are advised to use the // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are // equal. // // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on // pointers (in particular, C strings). Therefore, if you use it // with two C strings, you are testing how their locations in memory // are related, not how their content is related. To compare two C // strings by content, use {ASSERT|EXPECT}_STR*(). // // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you // what the actual value is when it fails, and similarly for the // other comparisons. // // 4. Do not depend on the order in which {ASSERT|EXPECT}_??() // evaluate their arguments, which is undefined. // // 5. These macros evaluate their arguments exactly once. // // Examples: // // EXPECT_NE(Foo(), 5); // EXPECT_EQ(a_pointer, NULL); // ASSERT_LT(i, array_size); // ASSERT_GT(records.size(), 0) << "There is no record left."; #define EXPECT_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal:: \ EqHelper::Compare, \ val1, val2) #define EXPECT_NE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define EXPECT_LE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define EXPECT_LT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define EXPECT_GE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define EXPECT_GT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) #define GTEST_ASSERT_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal:: \ EqHelper::Compare, \ val1, val2) #define GTEST_ASSERT_NE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define GTEST_ASSERT_LE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define GTEST_ASSERT_LT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define GTEST_ASSERT_GE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define GTEST_ASSERT_GT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C-string Comparisons. All tests treat NULL and any non-NULL string // as different. Two NULLs are equal. // // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case // // For wide or narrow string objects, you can use the // {ASSERT|EXPECT}_??() macros. // // Don't depend on the order in which the arguments are evaluated, // which is undefined. // // These macros evaluate their arguments exactly once. #define EXPECT_STREQ(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define EXPECT_STRNE(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define EXPECT_STRCASEEQ(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define EXPECT_STRCASENE(s1, s2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) #define ASSERT_STREQ(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define ASSERT_STRNE(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define ASSERT_STRCASEEQ(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define ASSERT_STRCASENE(s1, s2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. // // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2): // Tests that two float values are almost equal. // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2): // Tests that two double values are almost equal. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): // Tests that v1 and v2 are within the given distance to each other. // // Google Test uses ULP-based comparison to automatically pick a default // error bound that is appropriate for the operands. See the // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. #define EXPECT_FLOAT_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) #define EXPECT_DOUBLE_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) #define ASSERT_FLOAT_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) #define ASSERT_DOUBLE_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) #define EXPECT_NEAR(val1, val2, abs_error)\ EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) #define ASSERT_NEAR(val1, val2, abs_error)\ ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) // These predicate format functions work on floating-point values, and // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. // // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2); GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); #if GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful // on Windows, and rely on Windows SDK macros and APIs to compile. // // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) // // When expr unexpectedly fails or succeeds, Google Test prints the // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. # define EXPECT_HRESULT_SUCCEEDED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define ASSERT_HRESULT_SUCCEEDED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define EXPECT_HRESULT_FAILED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) # define ASSERT_HRESULT_FAILED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS // Macros that execute statement and check that it doesn't generate new fatal // failures in the current thread. // // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); // // Examples: // // EXPECT_NO_FATAL_FAILURE(Process()); // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // #define ASSERT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) #define EXPECT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the given source file path and line number, // and the given message) to be included in every test failure message generated // by code in the scope of the lifetime of an instance of this class. The effect // is undone with the destruction of the instance. // // The message argument can be anything streamable to std::ostream. // // Example: // testing::ScopedTrace trace("file.cc", 123, "message"); // class GTEST_API_ ScopedTrace { public: // The c'tor pushes the given source file location and message onto // a trace stack maintained by Google Test. // Template version. Uses Message() to convert the values into strings. // Slow, but flexible. template ScopedTrace(const char* file, int line, const T& message) { PushTrace(file, line, (Message() << message).GetString()); } // Optimize for some known types. ScopedTrace(const char* file, int line, const char* message) { PushTrace(file, line, message ? message : "(null)"); } #if GTEST_HAS_GLOBAL_STRING ScopedTrace(const char* file, int line, const ::string& message) { PushTrace(file, line, message); } #endif ScopedTrace(const char* file, int line, const std::string& message) { PushTrace(file, line, message); } // The d'tor pops the info pushed by the c'tor. // // Note that the d'tor is not virtual in order to be efficient. // Don't inherit from ScopedTrace! ~ScopedTrace(); private: void PushTrace(const char* file, int line, std::string message); GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its // c'tor and d'tor. Therefore it doesn't // need to be used otherwise. // Causes a trace (including the source file path, the current line // number, and the given message) to be included in every test failure // message generated by code in the current scope. The effect is // undone when the control leaves the current scope. // // The message argument can be anything streamable to std::ostream. // // In the implementation, we include the current line number as part // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s // to appear in the same block - as long as they are on different // lines. // // Assuming that each thread maintains its own stack of traces. // Therefore, a SCOPED_TRACE() would (correctly) only affect the // assertions in its own thread. #define SCOPED_TRACE(message) \ ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ __FILE__, __LINE__, (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq() compiles iff type1 and type2 are // the same type. The value it returns is not interesting. // // Instead of making StaticAssertTypeEq a class template, we make it a // function template that invokes a helper class template. This // prevents a user from misusing StaticAssertTypeEq by // defining objects of that type. // // CAVEAT: // // When used inside a method of a class template, // StaticAssertTypeEq() is effective ONLY IF the method is // instantiated. For example, given: // // template class Foo { // public: // void Bar() { testing::StaticAssertTypeEq(); } // }; // // the code: // // void Test1() { Foo foo; } // // will NOT generate a compiler error, as Foo::Bar() is never // actually instantiated. Instead, you need: // // void Test2() { Foo foo; foo.Bar(); } // // to cause a compiler error. template bool StaticAssertTypeEq() { (void)internal::StaticAssertTypeEqHelper(); return true; } // Defines a test. // // The first parameter is the name of the test case, and the second // parameter is the name of the test within the test case. // // The convention is to end the test case name with "Test". For // example, a test case for the Foo class can be named FooTest. // // Test code should appear between braces after an invocation of // this macro. Example: // // TEST(FooTest, InitializesCorrectly) { // Foo foo; // EXPECT_TRUE(foo.StatusIsOK()); // } // Note that we call GetTestTypeId() instead of GetTypeId< // ::testing::Test>() here to get the type ID of testing::Test. This // is to work around a suspected linker bug when using Google Test as // a framework on Mac OS X. The bug causes GetTypeId< // ::testing::Test>() to return different values depending on whether // the call is from the Google Test framework itself or from user test // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. #define GTEST_TEST(test_case_name, test_name)\ GTEST_TEST_(test_case_name, test_name, \ ::testing::Test, ::testing::internal::GetTestTypeId()) // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_TEST # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) #endif // Defines a test that uses a test fixture. // // The first parameter is the name of the test fixture class, which // also doubles as the test case name. The second parameter is the // name of the test within the test case. // // A test fixture class must be declared earlier. The user should put // the test code between braces after using this macro. Example: // // class FooTest : public testing::Test { // protected: // virtual void SetUp() { b_.AddElement(3); } // // Foo a_; // Foo b_; // }; // // TEST_F(FooTest, InitializesCorrectly) { // EXPECT_TRUE(a_.StatusIsOK()); // } // // TEST_F(FooTest, ReturnsElementCountCorrectly) { // EXPECT_EQ(a_.size(), 0); // EXPECT_EQ(b_.size(), 1); // } #define TEST_F(test_fixture, test_name)\ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId()) // Returns a path to temporary directory. // Tries to determine an appropriate directory for the platform. GTEST_API_ std::string TempDir(); #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace testing // Use this function in main() to run all tests. It returns 0 if all // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been // parsed by InitGoogleTest(). // // This function was formerly a macro; thus, it is in the global // namespace and has an all-caps name. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); } GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index f06cef2d..c9d59088 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -1,280 +1,281 @@ // Copyright 2005, 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. // // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #include "gtest/internal/gtest-internal.h" #include +#include namespace testing { namespace internal { GTEST_DECLARE_string_(internal_run_death_test); // Names of the flags (needed for parsing Google Test flags). const char kDeathTestStyleFlag[] = "death_test_style"; const char kDeathTestUseFork[] = "death_test_use_fork"; const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; #if GTEST_HAS_DEATH_TEST GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // DeathTest is a class that hides much of the complexity of the // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method // returns a concrete class that depends on the prevailing death test // style, as defined by the --gtest_death_test_style and/or // --gtest_internal_run_death_test flags. // In describing the results of death tests, these terms are used with // the corresponding definitions: // // exit status: The integer exit information in the format specified // by wait(2) // exit code: The integer code passed to exit(3), _exit(2), or // returned from main() class GTEST_API_ DeathTest { public: // Create returns false if there was an error determining the // appropriate action to take for the current death test; for example, // if the gtest_death_test_style flag is set to an invalid value. // The LastMessage method will return a more detailed message in that // case. Otherwise, the DeathTest pointer pointed to by the "test" // argument is set. If the death test should be skipped, the pointer // is set to NULL; otherwise, it is set to the address of a new concrete // DeathTest object that controls the execution of the current test. static bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); DeathTest(); virtual ~DeathTest() { } // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: explicit ReturnSentinel(DeathTest* test) : test_(test) { } ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } private: DeathTest* const test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); } GTEST_ATTRIBUTE_UNUSED_; // An enumeration of possible roles that may be taken when a death // test is encountered. EXECUTE means that the death test logic should // be executed immediately. OVERSEE means that the program should prepare // the appropriate environment for a child process to execute the death // test, then wait for it to complete. enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; // An enumeration of the three reasons that a test might be aborted. enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_THREW_EXCEPTION, TEST_DID_NOT_DIE }; // Assumes one of the above roles. virtual TestRole AssumeRole() = 0; // Waits for the death test to finish and returns its status. virtual int Wait() = 0; // Returns true if the death test passed; that is, the test process // exited during the test, its exit status matches a user-supplied // predicate, and its stderr output matches a user-supplied regular // expression. // The user-supplied predicate may be a macro expression rather // than a function pointer or functor, or else Wait and Passed could // be combined. virtual bool Passed(bool exit_status_ok) = 0; // Signals that the death test did not die as expected. virtual void Abort(AbortReason reason) = 0; // Returns a human-readable outcome message regarding the outcome of // the last death test. static const char* LastMessage(); static void set_last_death_test_message(const std::string& message); private: // A string containing a description of the outcome of the last death test. static std::string last_death_test_message_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); }; GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: virtual ~DeathTestFactory() { } virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) = 0; }; // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); }; // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. # if GTEST_HAS_EXCEPTIONS # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } catch (const ::std::exception& gtest_exception) { \ fprintf(\ stderr, \ "\n%s: Caught std::exception-derived exception escaping the " \ "death test statement. Exception message: %s\n", \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ gtest_exception.what()); \ fflush(stderr); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } catch (...) { \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } # else # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) # endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. #define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ const ::testing::internal::RE& gtest_regex = (regex); \ ::testing::internal::DeathTest* gtest_dt; \ if (!::testing::internal::DeathTest::Create( \ #statement, >est_regex, __FILE__, __LINE__, >est_dt)) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ if (gtest_dt != nullptr) { \ - ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ + std::unique_ptr< ::testing::internal::DeathTest> \ gtest_dt_ptr(gtest_dt); \ switch (gtest_dt->AssumeRole()) { \ case ::testing::internal::DeathTest::OVERSEE_TEST: \ if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ break; \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \ ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \ gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ default: \ break; \ } \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \ : fail(::testing::internal::DeathTest::LastMessage()) // The symbol "fail" here expands to something into which a message // can be streamed. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in // NDEBUG mode. In this case we need the statements to be executed and the macro // must accept a streamed message even though the message is never printed. // The regex object is not evaluated, but it is used to prevent "unused" // warnings and to avoid an expression that doesn't compile in debug mode. #define GTEST_EXECUTE_STATEMENT_(statement, regex) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } else if (!::testing::internal::AlwaysTrue()) { \ const ::testing::internal::RE& gtest_regex = (regex); \ static_cast(gtest_regex); \ } else \ ::testing::Message() // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { if (write_fd_ >= 0) posix::Close(write_fd_); } const std::string& file() const { return file_; } int line() const { return line_; } int index() const { return index_; } int write_fd() const { return write_fd_; } private: std::string file_; int line_; int index_; int write_fd_; GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); }; // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); #endif // GTEST_HAS_DEATH_TEST } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 9eb98b16..e1554830 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -1,750 +1,750 @@ // Copyright 2008 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. // Type and function utilities for implementing parameterized tests. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #include #include #include #include #include #include #include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" namespace testing { // Input to a parameterized test name generator, describing a test parameter. // Consists of the parameter value and the integer parameter index. template struct TestParamInfo { TestParamInfo(const ParamType& a_param, size_t an_index) : param(a_param), index(an_index) {} ParamType param; size_t index; }; // A builtin parameterized test name generator which returns the result of // testing::PrintToString. struct PrintToStringParamName { template std::string operator()(const TestParamInfo& info) const { return PrintToString(info.param); } }; namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // Utility Functions // Outputs a message explaining invalid registration of different // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location); template class ParamGeneratorInterface; template class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface. template class ParamIteratorInterface { public: virtual ~ParamIteratorInterface() {} // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. virtual const ParamGeneratorInterface* BaseGenerator() const = 0; // Advances iterator to point to the next element // provided by the generator. The caller is responsible // for not calling Advance() on an iterator equal to // BaseGenerator()->End(). virtual void Advance() = 0; // Clones the iterator object. Used for implementing copy semantics // of ParamIterator. virtual ParamIteratorInterface* Clone() const = 0; // Dereferences the current iterator and provides (read-only) access // to the pointed value. It is the caller's responsibility not to call // Current() on an iterator equal to BaseGenerator()->End(). // Used for implementing ParamGenerator::operator*(). virtual const T* Current() const = 0; // Determines whether the given iterator and other point to the same // element in the sequence generated by the generator. // Used for implementing ParamGenerator::operator==(). virtual bool Equals(const ParamIteratorInterface& other) const = 0; }; // Class iterating over elements provided by an implementation of // ParamGeneratorInterface. It wraps ParamIteratorInterface // and implements the const forward iterator concept. template class ParamIterator { public: typedef T value_type; typedef const T& reference; typedef ptrdiff_t difference_type; // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } const T& operator*() const { return *impl_->Current(); } const T* operator->() const { return impl_->Current(); } // Prefix version of operator++. ParamIterator& operator++() { impl_->Advance(); return *this; } // Postfix version of operator++. ParamIterator operator++(int /*unused*/) { ParamIteratorInterface* clone = impl_->Clone(); impl_->Advance(); return ParamIterator(clone); } bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator; explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} - scoped_ptr > impl_; + std::unique_ptr > impl_; }; // ParamGeneratorInterface is the binary interface to access generators // defined in other translation units. template class ParamGeneratorInterface { public: typedef T ParamType; virtual ~ParamGeneratorInterface() {} // Generator interface definition virtual ParamIteratorInterface* Begin() const = 0; virtual ParamIteratorInterface* End() const = 0; }; // Wraps ParamGeneratorInterface and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface instance is shared among all copies // of the original object. This is possible because that instance is immutable. template class ParamGenerator { public: typedef ParamIterator iterator; explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} ParamGenerator& operator=(const ParamGenerator& other) { impl_ = other.impl_; return *this; } iterator begin() const { return iterator(impl_->Begin()); } iterator end() const { return iterator(impl_->End()); } private: std::shared_ptr > impl_; }; // Generates values from a range of two comparable values. Can be used to // generate sequences of user-defined types that implement operator+() and // operator<(). // This class is used in the Range() function. template class RangeGenerator : public ParamGeneratorInterface { public: RangeGenerator(T begin, T end, IncrementT step) : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} virtual ~RangeGenerator() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, begin_, 0, step_); } virtual ParamIteratorInterface* End() const { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { value_ = static_cast(value_ + step_); index_++; } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const T* Current() const { return &value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const int other_index = CheckedDowncastToActualType(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : ParamIteratorInterface(), base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; T value_; int index_; const IncrementT step_; }; // class RangeGenerator::Iterator static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; for (T i = begin; i < end; i = static_cast(i + step)) end_index++; return end_index; } // No implementation - assignment is unsupported. void operator=(const RangeGenerator& other); const T begin_; const T end_; const IncrementT step_; // The index for the end() iterator. All the elements in the generated // sequence are indexed (0-based) to aid iterator comparison. const int end_index_; }; // class RangeGenerator // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator // is likely to persist beyond that stack frame. template class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { public: template ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} virtual ~ValuesInIteratorRangeGenerator() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, container_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector ContainerType; class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { ++iterator_; value_.reset(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. // value_ is updated here and not in Advance() because Advance() // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. virtual const T* Current() const { if (value_.get() == nullptr) value_.reset(new T(*iterator_)); return value_.get(); } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == CheckedDowncastToActualType(&other)->iterator_; } private: Iterator(const Iterator& other) // The explicit constructor call suppresses a false warning // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface* const base_; typename ContainerType::const_iterator iterator_; // A cached value of *iterator_. We keep it here to allow access by // pointer in the wrapping iterator's operator->(). // value_ needs to be mutable to be accessed in Current(). - // Use of scoped_ptr helps manage cached value's lifetime, + // Use of std::unique_ptr helps manage cached value's lifetime, // which is bound by the lifespan of the iterator itself. - mutable scoped_ptr value_; + mutable std::unique_ptr value_; }; // class ValuesInIteratorRangeGenerator::Iterator // No implementation - assignment is unsupported. void operator=(const ValuesInIteratorRangeGenerator& other); const ContainerType container_; }; // class ValuesInIteratorRangeGenerator // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Default parameterized test name generator, returns a string containing the // integer test parameter index. template std::string DefaultParamName(const TestParamInfo& info) { Message name_stream; name_stream << info.index; return name_stream.GetString(); } // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Parameterized test name overload helpers, which help the // INSTANTIATE_TEST_CASE_P macro choose between the default parameterized // test name generator and user param name generator. template ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) { return func; } template struct ParamNameGenFunc { typedef std::string Type(const TestParamInfo&); }; template typename ParamNameGenFunc::Type *GetParamNameGen() { return DefaultParamName; } // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Stores a parameter value and later creates tests parameterized with that // value. template class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} virtual Test* CreateTest() { TestClass::SetParam(¶meter_); return new TestClass(); } private: const ParamType parameter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactoryBase is a base class for meta-factories that create // test factories for passing into MakeAndRegisterTestInfo function. template class TestMetaFactoryBase { public: virtual ~TestMetaFactoryBase() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed // into that method twice. But ParameterizedTestCaseInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template class TestMetaFactory : public TestMetaFactoryBase { public: typedef typename TestCase::ParamType ParamType; TestMetaFactory() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { return new ParameterizedTestFactory(parameter); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfoBase is a generic interface // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase // accumulates test information provided by TEST_P macro invocations // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations // and uses that information to register all resulting test instances // in RegisterTests method. The ParameterizeTestCaseRegistry class holds // a collection of pointers to the ParameterizedTestCaseInfo objects // and calls RegisterTests() on each of them when asked. class ParameterizedTestCaseInfoBase { public: virtual ~ParameterizedTestCaseInfoBase() {} // Base part of test case name for display purposes. virtual const std::string& GetTestCaseName() const = 0; // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const = 0; // UnitTest class invokes this method to register tests in this // test case right before running them in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. virtual void RegisterTests() = 0; protected: ParameterizedTestCaseInfoBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P // macro invocations for a particular test case and generators // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that // test case. It registers tests with all values generated by all // generators when asked. template class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and // AddTestCaseInstantiation(). typedef typename TestCase::ParamType ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator(GeneratorCreationFunc)(); typedef typename ParamNameGenFunc::Type ParamNameGeneratorFunc; explicit ParameterizedTestCaseInfo( const char* name, CodeLocation code_location) : test_case_name_(name), code_location_(code_location) {} // Test case base name for display purposes. virtual const std::string& GetTestCaseName() const { return test_case_name_; } // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_case_name is the base name of the test case (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test case base name and DoBar is test base name. void AddTestPattern(const char* test_case_name, const char* test_base_name, TestMetaFactoryBase* meta_factory) { tests_.push_back(std::shared_ptr( new TestInfo(test_case_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // about a generator. int AddTestCaseInstantiation(const std::string& instantiation_name, GeneratorCreationFunc* func, ParamNameGeneratorFunc* name_func, const char* file, int line) { instantiations_.push_back( InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case // test cases right before running tests in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. virtual void RegisterTests() { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { std::shared_ptr test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { const std::string& instantiation_name = gen_it->name; ParamGenerator generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; const char* file = gen_it->file; int line = gen_it->line; std::string test_case_name; if ( !instantiation_name.empty() ) test_case_name = instantiation_name + "/"; test_case_name += test_info->test_case_base_name; size_t i = 0; std::set test_param_names; for (typename ParamGenerator::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; std::string param_name = name_func( TestParamInfo(*param_it, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name << "' is invalid, in " << file << " line " << line << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name << "', in " << file << " line " << line << std::endl; test_param_names.insert(param_name); test_name_stream << test_info->test_base_name << "/" << param_name; MakeAndRegisterTestInfo( test_case_name.c_str(), test_name_stream.GetString().c_str(), nullptr, // No type parameter. PrintToString(*param_it).c_str(), code_location_, GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it } // for test_it } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { TestInfo(const char* a_test_case_base_name, const char* a_test_base_name, TestMetaFactoryBase* a_test_meta_factory) : test_case_base_name(a_test_case_base_name), test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory) {} const std::string test_case_base_name; const std::string test_base_name; - const scoped_ptr > test_meta_factory; + const std::unique_ptr > test_meta_factory; }; using TestInfoContainer = ::std::vector >; // Records data received from INSTANTIATE_TEST_CASE_P macros: // struct InstantiationInfo { InstantiationInfo(const std::string &name_in, GeneratorCreationFunc* generator_in, ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) : name(name_in), generator(generator_in), name_func(name_func_in), file(file_in), line(line_in) {} std::string name; GeneratorCreationFunc* generator; ParamNameGeneratorFunc* name_func; const char* file; int line; }; typedef ::std::vector InstantiationContainer; static bool IsValidParamName(const std::string& name) { // Check for empty string if (name.empty()) return false; // Check for invalid characters for (std::string::size_type index = 0; index < name.size(); ++index) { if (!isalnum(name[index]) && name[index] != '_') return false; } return true; } const std::string test_case_name_; CodeLocation code_location_; TestInfoContainer tests_; InstantiationContainer instantiations_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); }; // class ParameterizedTestCaseInfo // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P // macros use it to locate their corresponding ParameterizedTestCaseInfo // descriptors. class ParameterizedTestCaseRegistry { public: ParameterizedTestCaseRegistry() {} ~ParameterizedTestCaseRegistry() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { delete *it; } } // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test case. template ParameterizedTestCaseInfo* GetTestCasePatternHolder( const char* test_case_name, CodeLocation code_location) { ParameterizedTestCaseInfo* typed_test_info = nullptr; for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { if ((*it)->GetTestCaseName() == test_case_name) { if ((*it)->GetTestCaseTypeId() != GetTypeId()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test case setup and tear-down in this case. ReportInvalidTestCaseType(test_case_name, code_location); posix::Abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< ParameterizedTestCaseInfo >(*it); } break; } } if (typed_test_info == nullptr) { typed_test_info = new ParameterizedTestCaseInfo( test_case_name, code_location); test_case_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { (*it)->RegisterTests(); } } private: typedef ::std::vector TestCaseInfoContainer; TestCaseInfoContainer test_case_infos_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); }; } // namespace internal // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template internal::ParamGenerator ValuesIn( const Container& container); namespace internal { // Used in the Values() function to provide polymorphic capabilities. template class ValueArray { public: ValueArray(Ts... v) : v_{std::move(v)...} {} template operator ParamGenerator() const { // NOLINT return ValuesIn(MakeVector(MakeIndexSequence())); } private: template std::vector MakeVector(IndexSequence) const { return std::vector{static_cast(v_.template Get())...}; } FlatTuple v_; }; } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 5e302ae5..b6182890 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1,2501 +1,2459 @@ // Copyright 2005, 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. // // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Test's public API and can be used by // code outside Google Test. // // This file is fundamental to Google Test. All other Google Test source // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // Environment-describing macros // ----------------------------- // // Google Test can be used in many different environments. Macros in // this section tell Google Test what kind of environment it is being // used in, such that Google Test can provide environment-specific // features and implementations. // // Google Test tries to automatically detect the properties of its // environment, so users usually don't need to worry about these // macros. However, the automatic detection is not perfect. // Sometimes it's necessary for a user to define some of the following // macros in the build script to override Google Test's decisions. // // If the user doesn't define a macro in the list, Google Test will // provide a default definition. After this header is #included, all // macros in this list will be defined to either 1 or 0. // // Notes to maintainers: // - Each macro here is a user-tweakable knob; do not grow the list // lightly. // - Use #if to key off these macros. Don't use #ifdef or "#if // defined(...)", which will not work as these macros are ALWAYS // defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::wstring // is/isn't available // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test // is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // GTEST_DEFAULT_DEATH_TEST_STYLE // - The default value of --gtest_death_test_style. // The legacy default has been "fast" in the open // source version since 2008. The recommended value // is "threadsafe", and can be set in // custom/gtest-port.h. // Platform-indicating macros // -------------------------- // // Macros indicating the platform on which Google Test is being used // (a macro is defined to 1 if compiled on the given platform; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_FUCHSIA - Fuchsia // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_IOS - iOS // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_NETBSD - NetBSD // GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_OS2 - OS/2 // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_WINDOWS_PHONE - Windows Phone // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // googletestframework@googlegroups.com (patches for fixing them are // even more welcome!). // // It is possible that none of the GTEST_OS_* macros are defined. // Feature-indicating macros // ------------------------- // // Macros indicating which Google Test features are available (a macro // is defined to 1 if the corresponding feature is supported; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // These macros are public so that portable tests can be written. // Such tests typically surround code using a feature with an #if // which controls that code. For example: // // #if GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. // GOOGLETEST_CM0007 DO NOT DELETE // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above RE\b(s) are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // Misc public macros // ------------------ // // GTEST_FLAG(flag_name) - references the variable corresponding to // the given Google Test flag. // Internal utilities // ------------------ // // The following macros and utilities are for Google Test's INTERNAL // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // is suppressed. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // -// Smart pointers: -// scoped_ptr - as in TR2. // // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like platforms // GOOGLETEST_CM0008 DO NOT DELETE // or a reduced regular exception syntax on other // platforms, including Windows. // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. // GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. #include // for isspace, etc #include // for ptrdiff_t -#include #include +#include #include +#include + #ifndef _WIN32_WCE # include # include #endif // !_WIN32_WCE #if defined __APPLE__ # include # include #endif // Brings in the definition of HAS_GLOBAL_STRING. This must be done // BEFORE we test HAS_GLOBAL_STRING. #include // NOLINT #include // NOLINT #include // NOLINT #include // NOLINT #include #include #include // NOLINT #include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/custom/gtest-port.h" #if !defined(GTEST_DEV_EMAIL_) # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" # define GTEST_FLAG_PREFIX_ "gtest_" # define GTEST_FLAG_PREFIX_DASH_ "gtest-" # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" # define GTEST_NAME_ "Google Test" # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. # define GTEST_GCC_VER_ \ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. // // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if _MSC_VER >= 1400 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) \ __pragma(warning(disable: warnings)) # define GTEST_DISABLE_MSC_WARNINGS_POP_() \ __pragma(warning(pop)) #else // Older versions of MSVC don't have __pragma. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) # define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Clang on Windows does not understand MSVC's pragma warning. // We need clang-specific way to disable function deprecation warning. #ifdef __clang__ # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ _Pragma("clang diagnostic pop") #else # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #define GTEST_LANG_CXX11 1 // Distinct from C++11 language support, some environments don't provide // proper C++11 library support. Notably, it's possible to build in // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ // with no C++11 support. // // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ // 20110325, but maintenance releases in the 4.4 and 4.5 series followed // this date, so check for those versions by their date stamps. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning #if GTEST_LANG_CXX11 && \ (!defined(__GLIBCXX__) || ( \ __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ /* Blacklist of patch releases of older branches: */ \ __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ # define GTEST_STDLIB_CXX11 1 #endif // Only use C++11 library features if the library provides them. #if GTEST_STDLIB_CXX11 # define GTEST_HAS_STD_BEGIN_AND_END_ 1 # define GTEST_HAS_STD_FORWARD_LIST_ 1 # if !defined(_MSC_VER) || (_MSC_FULL_VER >= 190023824) // works only with VS2015U2 and better # define GTEST_HAS_STD_FUNCTION_ 1 # endif # define GTEST_HAS_STD_INITIALIZER_LIST_ 1 # define GTEST_HAS_STD_MOVE_ 1 # define GTEST_HAS_STD_UNIQUE_PTR_ 1 # define GTEST_HAS_STD_SHARED_PTR_ 1 # define GTEST_HAS_UNORDERED_MAP_ 1 # define GTEST_HAS_UNORDERED_SET_ 1 #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS # if !GTEST_OS_WINDOWS_MOBILE # include # include # endif // In order to avoid having to include , use forward declaration #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two // separate (equivalent) structs, instead of using typedef typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; #else // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif #else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include # include #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. # include // NOLINT #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE # if GTEST_OS_LINUX_ANDROID // On Android, is only available starting with Gingerbread. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) # else # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) # endif #endif #if GTEST_USES_PCRE // The appropriate headers have already been included. #elif GTEST_HAS_POSIX_RE // On some platforms, needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included , which is guaranteed to define size_t through // . # include // NOLINT # define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // is not available on Windows. Use our own simple regex // implementation instead. # define GTEST_USES_SIMPLE_RE 1 #else // may not be available on this platform. Use our own // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) && defined(_CPPUNWIND) // MSVC defines _CPPUNWIND to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__BORLANDC__) // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. # ifndef _HAS_EXCEPTIONS # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__clang__) // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // but iff cleanups are enabled after that. In Obj-C++ files, there can be // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ // exceptions starting at clang r206352, but which checked for cleanups prior to // that. To reliably check for C++ exception availability with clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. # define GTEST_HAS_EXCEPTIONS 1 # else // For other compilers, we assume exceptions are disabled to be // conservative. # define GTEST_HAS_EXCEPTIONS 0 # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. # define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. # error "::std::string isn't available." #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING # define GTEST_HAS_GLOBAL_STRING 0 #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // FIXME: uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). # define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_WSTRING \ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. # ifdef _MSC_VER # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ !defined(__EXCEPTIONS) # define GTEST_HAS_RTTI 0 # else # define GTEST_HAS_RTTI 1 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. # elif defined(__clang__) # define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) # ifdef __RTTI_ALL__ # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif # else // For all other compilers, we assume RTTI is enabled. # define GTEST_HAS_RTTI 1 # endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include when RTTI // is enabled. #if GTEST_HAS_RTTI # include #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we make reasonable assumptions about // which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. #define GTEST_HAS_PTHREAD \ (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is // true. # include // NOLINT // For timespec and nanosleep, used below. # include // NOLINT #endif // Determines if hash_map/hash_set are available. // Only used for testing against those containers. #if !defined(GTEST_HAS_HASH_MAP_) # if defined(_MSC_VER) && (_MSC_VER < 1900) # define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. # define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. # endif // _MSC_VER #endif // !defined(GTEST_HAS_HASH_MAP_) // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) # if GTEST_OS_LINUX_ANDROID // On Android, clone() became available at different API levels for each 32-bit // architecture. # if defined(__LP64__) || \ (defined(__arm__) && __ANDROID_API__ >= 9) || \ (defined(__mips__) && __ANDROID_API__ >= 12) || \ (defined(__i386__) && __ANDROID_API__ >= 17) # define GTEST_HAS_CLONE 1 # else # define GTEST_HAS_CLONE 0 # endif # else # define GTEST_HAS_CLONE 1 # endif # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_FUCHSIA) # define GTEST_HAS_DEATH_TEST 1 #endif // Determines whether to support type-driven tests. // Typed tests need and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) # define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || \ GTEST_OS_AIX || GTEST_OS_OS2) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX # define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) #elif defined(__clang__) # if __has_attribute(unused) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) # endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_ #endif #if GTEST_LANG_CXX11 # define GTEST_CXX11_EQUALS_DELETE_ = delete #else // GTEST_LANG_CXX11 # define GTEST_CXX11_EQUALS_DELETE_ #endif // GTEST_LANG_CXX11 // Use this annotation before a function that takes a printf format string. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC) # if defined(__MINGW_PRINTF_FORMAT) // MinGW has two different printf implementations. Ensure the format macro // matches the selected implementation. See // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \ first_to_check))) # else # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) # endif #else # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type) \ void operator=(type const &) GTEST_CXX11_EQUALS_DELETE_ // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \ type(type const &) GTEST_CXX11_EQUALS_DELETE_; \ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be // suppressed. Use the following two macros in such cases: // // GTEST_INTENTIONAL_CONST_COND_PUSH_() // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) # define GTEST_INTENTIONAL_CONST_COND_POP_() \ GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. # define GTEST_HAS_SEH 1 # else // Assume no SEH. # define GTEST_HAS_SEH 0 # endif #define GTEST_IS_THREADSAFE \ (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ || GTEST_HAS_PTHREAD) #endif // GTEST_HAS_SEH // GTEST_API_ qualifies all symbols that must be exported. The definitions below // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in // gtest/internal/custom/gtest-port.h #ifndef GTEST_API_ #ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif #elif __GNUC__ >= 4 || defined(__clang__) # define GTEST_API_ __attribute__((visibility ("default"))) #endif // _MSC_VER #endif // GTEST_API_ #ifndef GTEST_API_ # define GTEST_API_ #endif // GTEST_API_ #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" #endif // GTEST_DEFAULT_DEATH_TEST_STYLE #ifdef __GNUC__ // Ask the compiler to never inline a given function. # define GTEST_NO_INLINE_ __attribute__((noinline)) #else # define GTEST_NO_INLINE_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if !defined(GTEST_HAS_CXXABI_H_) # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) # define GTEST_HAS_CXXABI_H_ 1 # else # define GTEST_HAS_CXXABI_H_ 0 # endif #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) # if __has_feature(memory_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ __attribute__((no_sanitize_memory)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ # endif // __has_feature(memory_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) # if __has_feature(address_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ __attribute__((no_sanitize_address)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ # endif // __has_feature(address_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) # if __has_feature(thread_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ __attribute__((no_sanitize_thread)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ # endif // __has_feature(thread_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { class Message; // Legacy imports for backwards compatibility. // New code should use std:: names directly. using std::get; using std::make_tuple; using std::tuple; using std::tuple_element; using std::tuple_size; namespace internal { // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. #if GTEST_LANG_CXX11 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) #else // !GTEST_LANG_CXX11 template struct CompileAssert { }; # define GTEST_COMPILE_ASSERT_(expr, msg) \ typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ #endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: // // (In C++11, we simply use static_assert instead of the following) // // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outter parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert // // instead, these compilers will refuse to compile // // GTEST_COMPILE_ASSERT_(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // // This template is declared, but intentionally undefined. template struct StaticAssertTypeEqHelper; template struct StaticAssertTypeEqHelper { enum { value = true }; }; // Same as std::is_same<>. template struct IsSame { enum { value = false }; }; template struct IsSame { enum { value = true }; }; // Evaluates to the number of elements in 'array'. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #if GTEST_HAS_GLOBAL_STRING typedef ::string string; #else typedef ::std::string string; #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING typedef ::wstring wstring; #elif GTEST_HAS_STD_WSTRING typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); -// Defines scoped_ptr. - -// This implementation of scoped_ptr is PARTIAL - it only contains -// enough stuff to satisfy Google Test's need. -template -class scoped_ptr { - public: - typedef T element_type; - - explicit scoped_ptr(T* p = nullptr) : ptr_(p) {} - ~scoped_ptr() { reset(); } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - T* get() const { return ptr_; } - - T* release() { - T* const ptr = ptr_; - ptr_ = nullptr; - return ptr; - } - - void reset(T* p = nullptr) { - if (p != ptr_) { - if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. - delete ptr_; - } - ptr_ = p; - } - } - - friend void swap(scoped_ptr& a, scoped_ptr& b) { - using std::swap; - swap(a.ptr_, b.ptr_); - } - - private: - T* ptr_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); -}; - // Defines RE. #if GTEST_USES_PCRE // if used, PCRE is injected by custom/gtest-port.h #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE // A simple C++ wrapper for . It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT # if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT # endif // GTEST_HAS_GLOBAL_STRING RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true iff regular expression re matches // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // // FIXME: make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } # if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } # endif // GTEST_HAS_GLOBAL_STRING static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); // We use a const char* instead of an std::string, as Google Test used to be // used where std::string is not available. FIXME: change to // std::string. const char* pattern_; bool is_valid_; # if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). # else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); # endif GTEST_DISALLOW_ASSIGN_(RE); }; #endif // GTEST_USES_PCRE // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; #if !defined(GTEST_LOG_) # define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(nullptr); } #endif // !defined(GTEST_LOG_) #if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsys: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. # define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error // Adds reference to a type if it is not a reference type, // otherwise leaves it unchanged. This is the same as // tr1::add_reference, which is not widely available yet. template struct AddReference { typedef T& type; }; // NOLINT template struct AddReference { typedef T& type; }; // NOLINT // A handy wrapper around AddReference that works when the argument T // depends on template parameters. #define GTEST_ADD_REFERENCE_(T) \ typename ::testing::internal::AddReference::type // Transforms "T" into "const T&" according to standard reference collapsing // rules (this is only needed as a backport for C++98 compilers that do not // support reference collapsing). Specifically, it transforms: // // char ==> const char& // const char ==> const char& // char& ==> char& // const char& ==> const char& // // Note that the non-const reference will not have "const" added. This is // standard, and necessary so that "T" can always bind to "const T&". template struct ConstRef { typedef const T& type; }; template struct ConstRef { typedef T& type; }; // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ typename ::testing::internal::ConstRef::type // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertable to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast(foo)) HandleASubclass1Object(foo); // if (dynamic_cast(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template // use like this: DownCast_(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { GTEST_INTENTIONAL_CONST_COND_POP_() const To to = nullptr; ::testing::internal::ImplicitCast_(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == nullptr || dynamic_cast(f) != nullptr); #endif return static_cast(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); #endif #if GTEST_HAS_DOWNCAST_ return ::down_cast(base); #elif GTEST_HAS_RTTI return dynamic_cast(base); // NOLINT #else return static_cast(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION // Returns the size (in bytes) of a file. GTEST_API_ size_t GetFileSize(FILE* file); // Reads the entire content of a file as a string. GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ std::vector GetArgvs(); #if GTEST_HAS_DEATH_TEST std::vector GetInjectableArgvs(); // Deprecated: pass the args vector by value instead. void SetInjectableArgvs(const std::vector* new_argvs); void SetInjectableArgvs(const std::vector& new_argvs); #if GTEST_HAS_GLOBAL_STRING void SetInjectableArgvs(const std::vector< ::string>& new_argvs); #endif // GTEST_HAS_GLOBAL_STRING void ClearInjectableArgvs(); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE # if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milliseconds. This function is only for testing // Google Test's own constructs. Don't use it in user tests, either // directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. n * 1000L * 1000L, // And n ms. }; nanosleep(&time, nullptr); } # endif // GTEST_HAS_PTHREAD # if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. # elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class Notification { public: Notification() : notified_(false) { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); } ~Notification() { pthread_mutex_destroy(&mutex_); } // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { pthread_mutex_lock(&mutex_); notified_ = true; pthread_mutex_unlock(&mutex_); } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { for (;;) { pthread_mutex_lock(&mutex_); const bool notified = notified_; pthread_mutex_unlock(&mutex_); if (notified) break; SleepMilliseconds(10); } } private: pthread_mutex_t mutex_; bool notified_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT GTEST_API_ void SleepMilliseconds(int n); // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { public: // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to // avoid including in this header file. Including is // undesirable because it defines a lot of symbols and macros that tend to // conflict with client code. This assumption is verified by // WindowsTypesTest.HANDLEIsVoidStar. typedef void* Handle; AutoHandle(); explicit AutoHandle(Handle handle); ~AutoHandle(); Handle Get() const; void Reset(); void Reset(Handle handle); private: // Returns true iff the handle is a valid handle object that can be closed. bool IsCloseable() const; Handle handle_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class GTEST_API_ Notification { public: Notification(); void Notify(); void WaitForNotification(); private: AutoHandle event_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast(thread)->Run(); return nullptr; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr)); finished_ = true; } } virtual void Run() { if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the // // end of the current scope. // // A static Mutex *must* be defined or declared using one of the following // macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // (A non-static Mutex is defined/declared in the usual way). class GTEST_API_ Mutex { public: enum MutexType { kStatic = 0, kDynamic = 1 }; // We rely on kStaticMutex being 0 as it is to what the linker initializes // type_ in static mutexes. critical_section_ will be initialized lazily // in ThreadSafeLazyInit(). enum StaticConstructorSelector { kStaticMutex = 0 }; // This constructor intentionally does nothing. It relies on type_ being // statically initialized to 0 (effectively setting it to kStatic) and on // ThreadSafeLazyInit() to lazily initialize the rest of the members. explicit Mutex(StaticConstructorSelector /*dummy*/) {} Mutex(); ~Mutex(); void Lock(); void Unlock(); // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld(); private: // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; // For static mutexes, we rely on these members being initialized to zeros // by the linker. MutexType type_; long critical_section_init_phase_; // NOLINT GTEST_CRITICAL_SECTION* critical_section_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: Mutex* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Base class for ValueHolder. Allows a caller to hold and delete a value // without knowing its type. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Provides a way for a thread to send notifications to a ThreadLocal // regardless of its parameter type. class ThreadLocalBase { public: // Creates a new ValueHolder object holding a default value passed to // this ThreadLocal's constructor and returns it. It is the caller's // responsibility not to call this when the ThreadLocal instance already // has a value on the current thread. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; protected: ThreadLocalBase() {} virtual ~ThreadLocalBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); }; // Maps a thread to a set of ThreadLocals that have values instantiated on that // thread and notifies them when the thread exits. A ThreadLocal instance is // expected to persist until all threads it has values on have terminated. class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { public: void Join(); protected: class Runnable { public: virtual ~Runnable() {} virtual void Run() = 0; }; ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: AutoHandle thread_; }; // Helper class for testing Google Test's multi-threading constructs. template class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { } virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) { } virtual ~RunnableImpl() {} virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; const T param_; GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); }; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; // Implements thread-local storage on Windows systems. // // // Thread 1 // ThreadLocal tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // The users of a TheadLocal instance have to make sure that all but one // threads (including the main one) using that instance have exited before // destroying it. Otherwise, the per-thread objects managed for them by the // ThreadLocal instance are not guaranteed to be destroyed on all platforms. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of T. Can be deleted via its base class without the caller // knowing the type of T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; T* GetOrCreateValue() const { return static_cast( ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); } virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; - scoped_ptr default_factory_; + std::unique_ptr default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); has_owner_ = true; } // Releases this mutex. void Unlock() { // Since the lock is being released the owner_ field should no longer be // considered valid. We don't protect writing to has_owner_ here, as it's // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. // has_owner_ indicates whether the owner_ field below contains a valid thread // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All // accesses to the owner_ field should be protected by a check of this field. // An alternative might be to memset() owner_ to all zeros, but there's no // guarantee that a zero'd pthread_t is necessarily invalid or even different // from pthread_self(). bool has_owner_; pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. // The initialization list here does not explicitly initialize each field, // instead relying on default initialization for the unspecified fields. In // particular, the owner_ field (a pthread_t) is not explicitly initialized. // This allows initialization to work whether pthread_t is a scalar or struct. // The flag -Wmissing-field-initializers must not be specified for this to work. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0} // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast(value_holder); } // Implements thread-local storage on pthreads-based systems. template class GTEST_API_ ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast(pthread_getspecific(key_)); if (holder != nullptr) { return CheckedDowncastToActualType(holder)->pointer(); } ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; - scoped_ptr default_factory_; + std::unique_ptr default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void Lock() {} void Unlock() {} void AssertHeld() const {} }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template class GTEST_API_ ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; #endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM // compiler and generates a warning in Sun Studio before 12u4. The Nokia Symbian // and the IBM XL C/C++ compiler try to instantiate a copy constructor // for objects passed through ellipsis (...), failing for uncopyable // objects. We define this to ensure that only POD is passed through // ellipsis on these systems. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || \ (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5130) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else # define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) # define GTEST_NEEDS_IS_POINTER_ 1 #endif template struct bool_constant { typedef bool_constant type; static const bool value = bool_value; }; template const bool bool_constant::value; typedef bool_constant false_type; typedef bool_constant true_type; template struct is_same : public false_type {}; template struct is_same : public true_type {}; template struct is_pointer : public false_type {}; template struct is_pointer : public true_type {}; template struct IteratorTraits { typedef typename Iterator::value_type value_type; }; template struct IteratorTraits { typedef T value_type; }; template struct IteratorTraits { typedef T value_type; }; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast(ch)) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline char ToLower(char ch) { return static_cast(tolower(static_cast(ch))); } inline char ToUpper(char ch) { return static_cast(toupper(static_cast(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; # ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } # else // !__BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } # else inline int IsATTY(int fd) { return _isatty(fd); } # endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } # endif // __BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. # else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } # endif // GTEST_OS_WINDOWS_MOBILE #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS // Functions deprecated by MSVC 8.0. GTEST_DISABLE_MSC_DEPRECATED_PUSH_() inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT // We are on Windows CE, which has no environment variables. static_cast(name); // To prevent 'unused argument' warning. return nullptr; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != nullptr && env[0] != '\0') ? env : nullptr; #else return getenv(name); #endif } GTEST_DISABLE_MSC_DEPRECATED_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. [[noreturn]] void Abort(); #else [[noreturn]] inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // MSVC "deprecates" snprintf and issues warnings wherever it is used. In // order to avoid these warnings, we need to use _snprintf or _snprintf_s on // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. # define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // complain about _snprintf. # define GTEST_SNPRINTF_ _snprintf #else # define GTEST_SNPRINTF_ snprintf #endif // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. // // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. const BiggestInt kMaxBiggestInt = ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template class TypeWithSize { public: // This prevents the user from using TypeWithSize with incorrect // values of N. typedef void UInt; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: // unsigned int has size 4 in both gcc and MSVC. // // As base/basictypes.h doesn't compile on Windows, we cannot use // uint32, uint64, and etc here. typedef int Int; typedef unsigned int UInt; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; #else typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; // Integer types of known sizes. typedef TypeWithSize<4>::Int Int32; typedef TypeWithSize<4>::UInt UInt32; typedef TypeWithSize<8>::Int Int64; typedef TypeWithSize<8>::UInt UInt64; typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #if !defined(GTEST_FLAG) # define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) # define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. # define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) # define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) # define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) #endif // !defined(GTEST_DECLARE_bool_) // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) # define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. // FIXME: Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); std::string OutputFlagAlsoCheckEnvVar(); const char* StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index f05de045..91f923d7 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -1,1189 +1,1190 @@ // Copyright 2005, 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. // Utility functions and classes used by the Google C++ testing framework.// // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ #define GTEST_SRC_GTEST_INTERNAL_INL_H_ #ifndef _WIN32_WCE # include #endif // !_WIN32_WCE #include #include // For strtoll/_strtoul64/malloc/free. #include // For memmove. #include +#include #include #include #include "gtest/internal/gtest-port.h" #if GTEST_CAN_STREAM_RESULTS_ # include // NOLINT # include // NOLINT #endif #if GTEST_OS_WINDOWS # include // NOLINT #endif // GTEST_OS_WINDOWS #include "gtest/gtest.h" #include "gtest/gtest-spi.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // Declares the flags. // // We don't want the users to modify this flag in the code, but want // Google Test's own unit tests to be able to access it. Therefore we // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; const char kBreakOnFailureFlag[] = "break_on_failure"; const char kCatchExceptionsFlag[] = "catch_exceptions"; const char kColorFlag[] = "color"; const char kFilterFlag[] = "filter"; const char kListTestsFlag[] = "list_tests"; const char kOutputFlag[] = "output"; const char kPrintTimeFlag[] = "print_time"; const char kPrintUTF8Flag[] = "print_utf8"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true iff Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 // format, without the timezone information. N.B.: due to the use the // non-reentrant localtime() function, this function is not thread safe. Do // not use it in any code that can be called from multiple threads. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast(GetTimeInMillis()) : static_cast(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast((raw_seed - 1U) % static_cast(kMaxRandomSeed)) + 1; return normalized_seed; } // Returns the first valid random seed after 'seed'. The behavior is // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } // This class saves the values of all Google Test flags in its c'tor, and // restores them in its d'tor. class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); break_on_failure_ = GTEST_FLAG(break_on_failure); catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); print_time_ = GTEST_FLAG(print_time); print_utf8_ = GTEST_FLAG(print_utf8); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; GTEST_FLAG(break_on_failure) = break_on_failure_; GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(print_utf8) = print_utf8_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: // Fields for saving the original values of flags. bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; std::string color_; std::string death_test_style_; bool death_test_use_fork_; std::string filter_; std::string internal_run_death_test_; bool list_tests_; std::string output_; bool print_time_; bool print_utf8_; internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded(); // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (e.g., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); // STL container utilities. // Returns the number of elements in the given container that satisfy // the given predicate. template inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } return count; } // Applies a function/functor to each element in the container. template void ForEach(const Container& c, Functor functor) { std::for_each(c.begin(), c.end(), functor); } // Returns the i-th element of the vector, or default_value if i is not // in range [0, v.size()). template inline E GetElementOr(const std::vector& v, int i, E default_value) { return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; } // Performs an in-place shuffle of a range of the vector's elements. // 'begin' and 'end' are element indices as an STL-style range; // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template void ShuffleRange(internal::Random* random, int begin, int end, std::vector* v) { const int size = static_cast(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = begin + random->Generate(range_width); std::swap((*v)[selected], (*v)[last_in_range]); } } // Performs an in-place shuffle of the vector's elements. template inline void Shuffle(internal::Random* random, std::vector* v) { ShuffleRange(random, 0, static_cast(v->size()), v); } // A function for deleting an object. Handy for being used as a // functor. template static void Delete(T* x) { delete x; } // A predicate that checks the key of a TestProperty against a known key. // // TestPropertyKeyIs is copyable. class TestPropertyKeyIs { public: // Constructor. // // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } private: std::string key_; }; // Class UnitTestOptions. // // This class contains functions for processing options the user // specifies when running the tests. It has only static members. // // In most cases, the user can specify an option using either an // environment variable or a command line flag. E.g. you can set the // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. static std::string GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. static std::string GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); // Returns true iff the user-specified filter matches the test case // name and the test name. static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. static int GTestShouldProcessSEH(DWORD exception_code); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". static bool MatchesFilter(const std::string& name, const char* filter); }; // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {} // Returns the current OS stack trace as an std::string. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; // This string is inserted in place of stack frames that are part of // Google Test's implementation. static const char* const kElidedFramesMarker; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: OsStackTraceGetter() {} virtual std::string CurrentStackTrace(int max_depth, int skip_count); virtual void UponLeavingGTest(); private: #if GTEST_HAS_ABSL Mutex mutex_; // Protects all internal state. // We save the stack frame below the frame that calls user code. // We do this because the address of the frame immediately below // the user code changes between the call to UponLeavingGTest() // and any calls to the stack trace code from within the user code. void* caller_frame_ = nullptr; #endif // GTEST_HAS_ABSL GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; // Information about a Google Test trace point. struct TraceInfo { const char* file; int line; std::string message; }; // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); }; // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); }; // The private implementation of the UnitTest class. We don't protect // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); // There are two different ways to register your own TestPartResultReporter. // You can register your own repoter to listen either only for test results // from the current thread or for results from all threads. // By default, each per-thread test result repoter just passes a new // TestPartResult to the global test result reporter, which registers the // test part result for the currently running test. // Returns the global test part result reporter. TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. void SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of skipped tests. int skipped_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const { return start_timestamp_; } // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const { return !Failed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const { return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? nullptr : test_cases_[i]; } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i) { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? nullptr : test_cases_[index]; } // Provides access to the event listener list. TestEventListeners* listeners() { return &listeners_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* current_test_result(); // Returns the TestResult for the ad hoc test. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter // are the same; otherwise, deletes the old getter and makes the // input the current getter. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Adds a TestInfo to the unit test. // // Arguments: // // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // test_info: the TestInfo object void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as // the user may have changed the current directory before calling // RUN_ALL_TESTS(). Therefore we capture the current directory in // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc, tear_down_tc)->AddTestInfo(test_info); } // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { return parameterized_test_registry_; } // Sets the TestCase object for the test that's currently running. void set_current_test_case(TestCase* a_current_test_case) { current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, this test is considered to be failed, but // the rest of the tests will still be run. bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); } // Clears the results of ad-hoc test assertions. void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test case, or to the global property set. If the // result already contains a property with the same key, the value will be // updated. void RecordProperty(const TestProperty& test_property); enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the // result in each TestCase and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. int FilterTests(ReactionToSharding shard_tests); // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); const TestCase* current_test_case() const { return current_test_case_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. std::vector& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } const std::vector& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); friend class ReplaceDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST // Initializes the event listener performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Initializes the event listener for streaming test results to a socket. // Must not be called before InitGoogleTest. void ConfigureStreamingOutput(); #endif // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void PostFlagParsingInit(); // Gets the random seed used at the start of the current test iteration. int random_seed() const { return random_seed_; } // Gets the random number generator. internal::Random* random() { return &random_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void ShuffleTests(); // Restores the test cases and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment // UnitTest::Run() starts. bool catch_exceptions() const { return catch_exceptions_; } private: friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } // The UnitTest object that owns this implementation object. UnitTest* const parent_; // The working directory when the first TEST() or TEST_F() was // executed. internal::FilePath original_working_dir_; // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; // Protects read and write access to global_test_part_result_reporter_. internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. internal::ThreadLocal per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector environments_; // The vector of TestCases in their original order. It owns the // elements in the vector. std::vector test_cases_; // Provides a level of indirection for the test case list to allow // easy shuffling and restoring the test case order. The i-th // element of this vector is the index of the i-th test case in the // shuffled order. std::vector test_case_indices_; // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestCaseRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; // Index of the last death test case registered. Initially -1. int last_death_test_case_; // This points to the TestCase for the currently running test. It // changes as Google Test goes through one test case after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. TestCase* current_test_case_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When // no test is running, this is set to NULL and Google Test stores // assertion results in ad_hoc_test_result_. Initially NULL. TestInfo* current_test_info_; // Normally, a user only writes assertions inside a TEST or TEST_F, // or inside a function called by a TEST or TEST_F. Since Google // Test keeps track of which test is current running, it can // associate such an assertion with the test it belongs to. // // If an assertion is encountered when no TEST or TEST_F is running, // Google Test attributes the assertion result to an imaginary "ad hoc" // test, and records the result in ad_hoc_test_result_. TestResult ad_hoc_test_result_; // The list of event listeners that can be used to track events inside // Google Test. TestEventListeners listeners_; // The OS stack trace getter. Will be deleted when the UnitTest // object is destructed. By default, an OsStackTraceGetter is used, // but the user can set this field to use a custom getter if that is // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; // True iff PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. int random_seed_; // Our random number generator. internal::Random random_; // The time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp_; // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; #if GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. - internal::scoped_ptr internal_run_death_test_flag_; - internal::scoped_ptr death_test_factory_; + std::unique_ptr internal_run_death_test_flag_; + std::unique_ptr death_test_factory_; #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal > gtest_trace_stack_; // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() // starts. bool catch_exceptions_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl // Convenience function for accessing the global UnitTest // implementation object. inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); GTEST_API_ bool IsAsciiDigit(char ch); GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); GTEST_API_ bool IsAsciiWhiteSpace(char ch); GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. GTEST_API_ std::string GetLastErrnoDescription(); // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use // it here. template bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. # if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); # else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; // FIXME: Convert this to compile time assertion when it is // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast(parsed); if (parse_success && static_cast(result) == parsed) { *number = result; return true; } return false; } #endif // GTEST_HAS_DEATH_TEST // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. // // This class is supplied only for the purpose of testing Google Test's own // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, const std::string& xml_element, const TestProperty& property) { test_result->RecordProperty(xml_element, property); } static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } static const std::vector& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } }; #if GTEST_CAN_STREAM_RESULTS_ // Streams test results to the given port on the given host machine. class StreamingListener : public EmptyTestEventListener { public: // Abstract base class for writing strings to a socket. class AbstractSocketWriter { public: virtual ~AbstractSocketWriter() {} // Sends a string to the socket. virtual void Send(const std::string& message) = 0; // Closes the socket. virtual void CloseConnection() {} // Sends a string and a newline to the socket. void SendLn(const std::string& message) { Send(message + "\n"); } }; // Concrete class for actually writing strings to a socket. class SocketWriter : public AbstractSocketWriter { public: SocketWriter(const std::string& host, const std::string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); } virtual ~SocketWriter() { if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. virtual void Send(const std::string& message) { GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast(message.length()); if (write(sockfd_, message.c_str(), len) != len) { GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } private: // Creates a client socket and connects to the server. void MakeConnection(); // Closes the socket. void CloseConnection() { GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; } int sockfd_; // socket file descriptor const std::string host_name_; const std::string port_num_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); }; // class SocketWriter // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static std::string UrlEncode(const char* str); StreamingListener(const std::string& host, const std::string& port) : socket_writer_(new SocketWriter(host, port)) { Start(); } explicit StreamingListener(AbstractSocketWriter* socket_writer) : socket_writer_(socket_writer) { Start(); } void OnTestProgramStart(const UnitTest& /* unit_test */) { SendLn("event=TestProgramStart"); } void OnTestProgramEnd(const UnitTest& unit_test) { // Note that Google Test current only report elapsed time for each // test iteration, not for the entire test program. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); // Notify the streaming server to stop. socket_writer_->CloseConnection(); } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { SendLn("event=TestIterationStart&iteration=" + StreamableToString(iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + "ms"); } void OnTestCaseStart(const TestCase& test_case) { SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); } void OnTestCaseEnd(const TestCase& test_case) { SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + "ms"); } void OnTestStart(const TestInfo& test_info) { SendLn(std::string("event=TestStart&name=") + test_info.name()); } void OnTestEnd(const TestInfo& test_info) { SendLn("event=TestEnd&passed=" + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } void OnTestPartResult(const TestPartResult& test_part_result) { const char* file_name = test_part_result.file_name(); if (file_name == nullptr) file_name = ""; SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + "&line=" + StreamableToString(test_part_result.line_number()) + "&message=" + UrlEncode(test_part_result.message())); } private: // Sends the given message and a newline to the socket. void SendLn(const std::string& message) { socket_writer_->SendLn(message); } // Called at the start of streaming to notify the receiver what // protocol we are using. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } std::string FormatBool(bool value) { return value ? "1" : "0"; } - const scoped_ptr socket_writer_; + const std::unique_ptr socket_writer_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); }; // class StreamingListener #endif // GTEST_CAN_STREAM_RESULTS_ } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 2cac34e4..950c16b6 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -1,1322 +1,1322 @@ // Copyright 2008, 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. #include "gtest/internal/gtest-port.h" #include #include #include #include #include #include #if GTEST_OS_WINDOWS # include # include # include # include // Used in ThreadLocal. # ifdef _MSC_VER # include # endif // _MSC_VER #else # include #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC # include # include # include #endif // GTEST_OS_MAC #if GTEST_OS_QNX # include # include # include #endif // GTEST_OS_QNX #if GTEST_OS_AIX # include # include #endif // GTEST_OS_AIX #if GTEST_OS_FUCHSIA # include # include #endif // GTEST_OS_FUCHSIA #include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" #include "src/gtest-internal-inl.h" namespace testing { namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER #if GTEST_OS_LINUX namespace { template T ReadProcFileField(const std::string& filename, int field) { std::string dummy; std::ifstream file(filename.c_str()); while (field-- > 0) { file >> dummy; } T output = 0; file >> output; return output; } } // namespace // Returns the number of active threads, or 0 when there is an error. size_t GetThreadCount() { const std::string filename = (Message() << "/proc/" << getpid() << "/stat").GetString(); return ReadProcFileField(filename, 19); } #elif GTEST_OS_MAC size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; thread_act_array_t thread_list; const kern_return_t status = task_threads(task, &thread_list, &thread_count); if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. vm_deallocate(task, reinterpret_cast(thread_list), sizeof(thread_t) * thread_count); return static_cast(thread_count); } else { return 0; } } #elif GTEST_OS_QNX // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { const int fd = open("/proc/self/as", O_RDONLY); if (fd < 0) { return 0; } procfs_info process_info; const int status = devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr); close(fd); if (status == EOK) { return static_cast(process_info.num_threads); } else { return 0; } } #elif GTEST_OS_AIX size_t GetThreadCount() { struct procentry64 entry; pid_t pid = getpid(); int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1); if (status == 1) { return entry.pi_thcount; } else { return 0; } } #elif GTEST_OS_FUCHSIA size_t GetThreadCount() { int dummy_buffer; size_t avail; zx_status_t status = zx_object_get_info( zx_process_self(), ZX_INFO_PROCESS_THREADS, &dummy_buffer, 0, nullptr, &avail); if (status == ZX_OK) { return avail; } else { return 0; } } #else size_t GetThreadCount() { // There's no portable way to detect the number of threads, so we just // return 0 to indicate that we cannot detect it. return 0; } #endif // GTEST_OS_LINUX #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS void SleepMilliseconds(int n) { ::Sleep(n); } AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} AutoHandle::~AutoHandle() { Reset(); } AutoHandle::Handle AutoHandle::Get() const { return handle_; } void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. if (handle_ != handle) { if (IsCloseable()) { ::CloseHandle(handle_); } handle_ = handle; } else { GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " "and thus not allowed."; } } bool AutoHandle::IsCloseable() const { // Different Windows APIs may use either of these values to represent an // invalid handle. return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE; } Notification::Notification() : event_(::CreateEvent(nullptr, // Default security attributes. TRUE, // Do not reset automatically. FALSE, // Initially unset. nullptr)) { // Anonymous event. GTEST_CHECK_(event_.Get() != nullptr); } void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); } void Notification::WaitForNotification() { GTEST_CHECK_( ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); } Mutex::Mutex() : owner_thread_id_(0), type_(kDynamic), critical_section_init_phase_(0), critical_section_(new CRITICAL_SECTION) { ::InitializeCriticalSection(critical_section_); } Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // to clean them up. // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires // nothing to clean it up but is available only on Vista and later. // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; critical_section_ = nullptr; } } void Mutex::Lock() { ThreadSafeLazyInit(); ::EnterCriticalSection(critical_section_); owner_thread_id_ = ::GetCurrentThreadId(); } void Mutex::Unlock() { ThreadSafeLazyInit(); // We don't protect writing to owner_thread_id_ here, as it's the // caller's responsibility to ensure that the current thread holds the // mutex when this is called. owner_thread_id_ = 0; ::LeaveCriticalSection(critical_section_); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void Mutex::AssertHeld() { ThreadSafeLazyInit(); GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) << "The current thread is not holding the mutex @" << this; } namespace { // Use the RAII idiom to flag mem allocs that are intentionally never // deallocated. The motivation is to silence the false positive mem leaks // that are reported by the debug version of MS's CRT which can only detect // if an alloc is missing a matching deallocation. // Example: // MemoryIsNotDeallocated memory_is_not_deallocated; // critical_section_ = new CRITICAL_SECTION; // class MemoryIsNotDeallocated { public: MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { #ifdef _MSC_VER old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT // doesn't report mem leak if there's no matching deallocation. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); #endif // _MSC_VER } ~MemoryIsNotDeallocated() { #ifdef _MSC_VER // Restore the original _CRTDBG_ALLOC_MEM_DF flag _CrtSetDbgFlag(old_crtdbg_flag_); #endif // _MSC_VER } private: int old_crtdbg_flag_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); }; } // namespace // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. if (type_ == kStatic) { switch ( ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { case 0: // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. owner_thread_id_ = 0; { // Use RAII to flag that following mem alloc is never deallocated. MemoryIsNotDeallocated memory_is_not_deallocated; critical_section_ = new CRITICAL_SECTION; } ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. GTEST_CHECK_(::InterlockedCompareExchange( &critical_section_init_phase_, 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. ::Sleep(0); } break; case 2: break; // The mutex is already initialized and ready for use. default: GTEST_CHECK_(false) << "Unexpected value of critical_section_init_phase_ " << "while initializing a static mutex."; } } } namespace { class ThreadWithParamSupport : public ThreadWithParamBase { public: static HANDLE CreateThread(Runnable* runnable, Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; // FIXME: Consider to use _beginthreadex instead. HANDLE thread_handle = ::CreateThread( nullptr, // Default security. 0, // Default stack size. &ThreadWithParamSupport::ThreadMain, param, // Parameter to ThreadMainStatic 0x0, // Default creation flags. &thread_id); // Need a valid pointer for the call to work under Win98. GTEST_CHECK_(thread_handle != nullptr) << "CreateThread failed with error " << ::GetLastError() << "."; if (thread_handle == nullptr) { delete param; } return thread_handle; } private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) : runnable_(runnable), thread_can_start_(thread_can_start) { } - scoped_ptr runnable_; + std::unique_ptr runnable_; // Does not own. Notification* thread_can_start_; }; static DWORD WINAPI ThreadMain(void* ptr) { // Transfers ownership. - scoped_ptr param(static_cast(ptr)); + std::unique_ptr param(static_cast(ptr)); if (param->thread_can_start_ != nullptr) param->thread_can_start_->WaitForNotification(); param->runnable_->Run(); return 0; } // Prohibit instantiation. ThreadWithParamSupport(); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); }; } // namespace ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start) : thread_(ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) { } ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) << "Failed to join the thread with error " << ::GetLastError() << "."; } // Maps a thread to a set of ThreadIdToThreadLocals that have values // instantiated on that thread and notifies them when the thread exits. A // ThreadLocal instance is expected to persist until all threads it has // values on have terminated. class ThreadLocalRegistryImpl { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { thread_local_pos = thread_to_thread_locals->insert( std::make_pair(current_thread, ThreadLocalValues())).first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos == thread_local_values.end()) { value_pos = thread_local_values .insert(std::make_pair( thread_local_instance, std::shared_ptr( thread_local_instance->NewValueForCurrentThread()))) .first; } return value_pos->second.get(); } static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { std::vector > value_holders; // Clean up the ThreadLocalValues data structure while holding the lock, but // defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); for (ThreadIdToThreadLocals::iterator it = thread_to_thread_locals->begin(); it != thread_to_thread_locals->end(); ++it) { ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos != thread_local_values.end()) { value_holders.push_back(value_pos->second); thread_local_values.erase(value_pos); // This 'if' can only be successful at most once, so theoretically we // could break out of the loop here, but we don't bother doing so. } } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } static void OnThreadExit(DWORD thread_id) { GTEST_CHECK_(thread_id != 0) << ::GetLastError(); std::vector > value_holders; // Clean up the ThreadIdToThreadLocals data structure while holding the // lock, but defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(thread_id); if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; for (ThreadLocalValues::iterator value_pos = thread_local_values.begin(); value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } private: // In a particular thread, maps a ThreadLocal object to its value. typedef std::map > ThreadLocalValues; // Stores all ThreadIdToThreadLocals having values in a thread, indexed by // thread's ID. typedef std::map ThreadIdToThreadLocals; // Holds the thread id and thread handle that we pass from // StartWatcherThreadFor to WatcherThreadFunc. typedef std::pair ThreadIdAndHandle; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != nullptr); // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; HANDLE watcher_thread = ::CreateThread( nullptr, // Default security. 0, // Default stack size &ThreadLocalRegistryImpl::WatcherThreadFunc, reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != nullptr); // Give the watcher thread the same priority as ours to avoid being // blocked by it. ::SetThreadPriority(watcher_thread, ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast(param); GTEST_CHECK_( ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; return 0; } // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); MemoryIsNotDeallocated memory_is_not_deallocated; static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); return map; } // Protects access to GetThreadLocalsMapLocked() and its return value. static Mutex mutex_; // Protects access to GetThreadMapLocked() and its return value. static Mutex thread_map_mutex_; }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. RE::~RE() { if (is_valid_) { // regfree'ing an invalid regex might crash because the content // of the regex is undefined. Since the regex's are essentially // the same, one cannot be valid (or invalid) without the other // being so too. regfree(&partial_regex_); regfree(&full_regex_); } free(const_cast(pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = posix::StrDup(regex); // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's // freed. // // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } #elif GTEST_USES_SIMPLE_RE // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != nullptr; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in , these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { case 'd': return IsAsciiDigit(ch); case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; case 's': return IsAsciiWhiteSpace(ch); case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; case 'w': return IsAsciiWordChar(ch); case 'W': return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; } // Helper function used by ValidateRegex() to format error messages. static std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } // Generates non-fatal failures and returns false if regex is invalid; // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == nullptr) { // FIXME: fix the source file location in the // assertion failures to match where the regex is used in user // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } bool is_valid = true; // True iff ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; } else { // Not an escape sequence. const char ch = regex[i]; if (ch == '^' && i > 0) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } prev_repeatable = !IsInSet(ch, "^$?*+"); } } return is_valid; } // Matches a repeated regex atom followed by a valid simple regular // expression. The regex atom is defined as c if escaped is false, // or \c otherwise. repeat is the repetition meta character (?, *, // or +). The behavior is undefined if str contains too many // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. bool MatchRepetitionAndRegexAtHead( bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; const size_t max_count = (repeat == '?') ? 1 : static_cast(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. for (size_t i = 0; i <= max_count; ++i) { // We know that the atom matches each of the first i characters in str. if (i >= min_count && MatchRegexAtHead(regex, str + i)) { // We have enough matches at the head, and the tail matches too. // Since we only care about *whether* the pattern matches str // (as opposed to *how* it matches), there is no need to find a // greedy match. return true; } if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } // Returns true iff regex matches a prefix of str. regex must be a // valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. return true; // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. return MatchRepetitionAndRegexAtHead( escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } // Returns true iff regex matches any substring of str. regex must be // a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of // stack space normally. In rare cases the time complexity can be // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == nullptr || str == nullptr) return false; if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } // Implements the RE class. RE::~RE() { free(const_cast(pattern_)); free(const_cast(full_pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = full_pattern_ = nullptr; if (regex != nullptr) { pattern_ = posix::StrDup(regex); } is_valid_ = ValidateRegex(regex); if (!is_valid_) { // No need to calculate the full pattern when the regex is invalid. return; } const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a // full match: we need space to prepend a '^', append a '$', and // terminate the string with '\0'. char* buffer = static_cast(malloc(len + 3)); full_pattern_ = buffer; if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } #endif // GTEST_USES_POSIX_RE const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { const std::string file_name(file == nullptr ? kUnknownFile : file); if (line < 0) { return file_name + ":"; } #ifdef _MSC_VER return file_name + "(" + StreamableToString(line) + "):"; #else return file_name + ":" + StreamableToString(line) + ":"; #endif // _MSC_VER } // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { const std::string file_name(file == nullptr ? kUnknownFile : file); if (line < 0) return file_name; else return file_name + ":" + StreamableToString(line); } GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = severity == GTEST_INFO ? "[ INFO ]" : severity == GTEST_WARNING ? "[WARNING]" : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. GTestLog::~GTestLog() { GetStream() << ::std::endl; if (severity_ == GTEST_FATAL) { fflush(stderr); posix::Abort(); } } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_DEPRECATED_PUSH_() #if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; # else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in the /tmp directory // instead. We use /tmp on most systems, and /sdcard on Android. // That's because Android doesn't have /tmp. # if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, // this requires a Context handle, which cannot be retrieved // globally from native code. Doing so also precludes running the // code as part of a regular standalone executable, which doesn't // run in a Dalvik process (e.g. when running it through 'adb shell'). // // The location /sdcard is directly accessible from native code // and is the only location (unofficially) supported by the Android // team. It's generally a symlink to the real SD Card mount point // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or // other OEM-customized locations. Never rely on these, and always // use /sdcard. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; # else char name_template[] = "/tmp/captured_stream.XXXXXX"; # endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS fflush(nullptr); dup2(captured_fd, fd_); close(captured_fd); } ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(nullptr); dup2(uncaptured_fd_, fd_); close(uncaptured_fd_); uncaptured_fd_ = -1; } FILE* const file = posix::FOpen(filename_.c_str(), "r"); const std::string content = ReadEntireFile(file); posix::FClose(file); return content; } private: const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. ::std::string filename_; GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; GTEST_DISABLE_MSC_DEPRECATED_POP_() static CapturedStream* g_captured_stderr = nullptr; static CapturedStream* g_captured_stdout = nullptr; // Starts capturing an output stream (stdout/stderr). static void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != nullptr) { GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } // Stops capturing the output stream and returns the captured string. static std::string GetCapturedStream(CapturedStream** captured_stream) { const std::string content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = nullptr; return content; } // Starts capturing stdout. void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. std::string GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. std::string GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast(ftell(file)); } std::string ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far fseek(file, 0, SEEK_SET); // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); const std::string content(buffer, bytes_read); delete[] buffer; return content; } #if GTEST_HAS_DEATH_TEST static const std::vector* g_injected_test_argvs = nullptr; // Owned. std::vector GetInjectableArgvs() { if (g_injected_test_argvs != nullptr) { return *g_injected_test_argvs; } return GetArgvs(); } void SetInjectableArgvs(const std::vector* new_argvs) { if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs; g_injected_test_argvs = new_argvs; } void SetInjectableArgvs(const std::vector& new_argvs) { SetInjectableArgvs( new std::vector(new_argvs.begin(), new_argvs.end())); } #if GTEST_HAS_GLOBAL_STRING void SetInjectableArgvs(const std::vector< ::string>& new_argvs) { SetInjectableArgvs( new std::vector(new_argvs.begin(), new_argvs.end())); } #endif // GTEST_HAS_GLOBAL_STRING void ClearInjectableArgvs() { delete g_injected_test_argvs; g_injected_test_argvs = nullptr; } #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } } // namespace posix #endif // GTEST_OS_WINDOWS_MOBILE // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static std::string FlagToEnvVar(const char* flag) { const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); } // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Parses the environment variable as a decimal integer. char* end = nullptr; const long long_value = strtol(str, &end, 10); // NOLINT // Has strtol() consumed all characters in the string? if (*end != '\0') { // No - an invalid character was encountered. Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } // Is the parsed value in the range of an Int32? const Int32 result = static_cast(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } *value = result; return true; } // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { #if defined(GTEST_GET_BOOL_FROM_ENV_) return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == nullptr ? default_value : strcmp(string_value, "0") != 0; #endif // defined(GTEST_GET_BOOL_FROM_ENV_) } // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { #if defined(GTEST_GET_INT32_FROM_ENV_) return GTEST_GET_INT32_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == nullptr) { // The environment variable is not set. return default_value; } Int32 result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } return result; #endif // defined(GTEST_GET_INT32_FROM_ENV_) } // As a special case for the 'output' flag, if GTEST_OUTPUT is not // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build // system. The value of XML_OUTPUT_FILE is a filename without the // "xml:" prefix of GTEST_OUTPUT. // Note that this is meant to be called at the call site so it does // not check that the flag is 'output' // In essence this checks an env variable called XML_OUTPUT_FILE // and if it is set we prepend "xml:" to its value, if it not set we return "" std::string OutputFlagAlsoCheckEnvVar(){ std::string default_value_for_output_flag = ""; const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); if (nullptr != xml_output_file_env) { default_value_for_output_flag = std::string("xml:") + xml_output_file_env; } return default_value_for_output_flag; } // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. const char* StringFromGTestEnv(const char* flag, const char* default_value) { #if defined(GTEST_GET_STRING_FROM_ENV_) return GTEST_GET_STRING_FROM_ENV_(flag, default_value); #else const std::string env_var = FlagToEnvVar(flag); const char* const value = posix::GetEnv(env_var.c_str()); return value == nullptr ? default_value : value; #endif // defined(GTEST_GET_STRING_FROM_ENV_) } } // namespace internal } // namespace testing diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index a24dfce8..e3cebf4d 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -1,1108 +1,1107 @@ // Copyright 2005, 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. // // The purpose of this file is to generate Google Test output under // various conditions. The output will then be verified by // googletest-output-test.py to ensure that Google Test generates the // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" #include #if _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) #endif // _MSC_VER #if GTEST_IS_THREADSAFE using testing::ScopedFakeTestPartResultReporter; using testing::TestPartResultArray; using testing::internal::Notification; using testing::internal::ThreadWithParam; #endif namespace posix = ::testing::internal::posix; // Tests catching fatal failures. // A subroutine used by the following test. void TestEq1(int x) { ASSERT_EQ(1, x); } // This function calls a test subroutine, catches the fatal failure it // generates, and then returns early. void TryTestSubroutine() { // Calls a subrountine that yields a fatal failure. TestEq1(2); // Catches the fatal failure and aborts the test. // // The testing::Test:: prefix is necessary when calling // HasFatalFailure() outside of a TEST, TEST_F, or test fixture. if (testing::Test::HasFatalFailure()) return; // If we get here, something is wrong. FAIL() << "This should never be reached."; } TEST(PassingTest, PassingTest1) { } TEST(PassingTest, PassingTest2) { } // Tests that parameters of failing parameterized tests are printed in the // failing test summary. class FailingParamTest : public testing::TestWithParam {}; TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); } // This generates a test which will fail. Google Test is expected to print // its parameter when it outputs the list of all failed tests. INSTANTIATE_TEST_CASE_P(PrintingFailingParams, FailingParamTest, testing::Values(2)); static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; TEST(NonfatalFailureTest, EscapesStringOperands) { std::string actual = "actual \"string\""; EXPECT_EQ(kGoldenString, actual); const char* golden = kGoldenString; EXPECT_EQ(golden, actual); } TEST(NonfatalFailureTest, DiffForLongStrings) { std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1); EXPECT_EQ(golden_str, "Line 2"); } // Tests catching a fatal failure in a subroutine. TEST(FatalFailureTest, FatalFailureInSubroutine) { printf("(expecting a failure that x should be 1)\n"); TryTestSubroutine(); } // Tests catching a fatal failure in a nested subroutine. TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { printf("(expecting a failure that x should be 1)\n"); // Calls a subrountine that yields a fatal failure. TryTestSubroutine(); // Catches the fatal failure and aborts the test. // // When calling HasFatalFailure() inside a TEST, TEST_F, or test // fixture, the testing::Test:: prefix is not needed. if (HasFatalFailure()) return; // If we get here, something is wrong. FAIL() << "This should never be reached."; } // Tests HasFatalFailure() after a failed EXPECT check. TEST(FatalFailureTest, NonfatalFailureInSubroutine) { printf("(expecting a failure on false)\n"); EXPECT_TRUE(false); // Generates a nonfatal failure ASSERT_FALSE(HasFatalFailure()); // This should succeed. } // Tests interleaving user logging and Google Test assertions. TEST(LoggingTest, InterleavingLoggingAndAssertions) { static const int a[4] = { 3, 9, 2, 6 }; printf("(expecting 2 failures on (3) >= (a[i]))\n"); for (int i = 0; i < static_cast(sizeof(a)/sizeof(*a)); i++) { printf("i == %d\n", i); EXPECT_GE(3, a[i]); } } // Tests the SCOPED_TRACE macro. // A helper function for testing SCOPED_TRACE. void SubWithoutTrace(int n) { EXPECT_EQ(1, n); ASSERT_EQ(2, n); } // Another helper function for testing SCOPED_TRACE. void SubWithTrace(int n) { SCOPED_TRACE(testing::Message() << "n = " << n); SubWithoutTrace(n); } TEST(SCOPED_TRACETest, AcceptedValues) { SCOPED_TRACE("literal string"); SCOPED_TRACE(std::string("std::string")); SCOPED_TRACE(1337); // streamable type const char* null_value = nullptr; SCOPED_TRACE(null_value); ADD_FAILURE() << "Just checking that all these values work fine."; } // Tests that SCOPED_TRACE() obeys lexical scopes. TEST(SCOPED_TRACETest, ObeysScopes) { printf("(expected to fail)\n"); // There should be no trace before SCOPED_TRACE() is invoked. ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; { SCOPED_TRACE("Expected trace"); // After SCOPED_TRACE(), a failure in the current scope should contain // the trace. ADD_FAILURE() << "This failure is expected, and should have a trace."; } // Once the control leaves the scope of the SCOPED_TRACE(), there // should be no trace again. ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; } // Tests that SCOPED_TRACE works inside a loop. TEST(SCOPED_TRACETest, WorksInLoop) { printf("(expected to fail)\n"); for (int i = 1; i <= 2; i++) { SCOPED_TRACE(testing::Message() << "i = " << i); SubWithoutTrace(i); } } // Tests that SCOPED_TRACE works in a subroutine. TEST(SCOPED_TRACETest, WorksInSubroutine) { printf("(expected to fail)\n"); SubWithTrace(1); SubWithTrace(2); } // Tests that SCOPED_TRACE can be nested. TEST(SCOPED_TRACETest, CanBeNested) { printf("(expected to fail)\n"); SCOPED_TRACE(""); // A trace without a message. SubWithTrace(2); } // Tests that multiple SCOPED_TRACEs can be used in the same scope. TEST(SCOPED_TRACETest, CanBeRepeated) { printf("(expected to fail)\n"); SCOPED_TRACE("A"); ADD_FAILURE() << "This failure is expected, and should contain trace point A."; SCOPED_TRACE("B"); ADD_FAILURE() << "This failure is expected, and should contain trace point A and B."; { SCOPED_TRACE("C"); ADD_FAILURE() << "This failure is expected, and should " << "contain trace point A, B, and C."; } SCOPED_TRACE("D"); ADD_FAILURE() << "This failure is expected, and should " << "contain trace point A, B, and D."; } #if GTEST_IS_THREADSAFE // Tests that SCOPED_TRACE()s can be used concurrently from multiple // threads. Namely, an assertion should be affected by // SCOPED_TRACE()s in its own thread only. // Here's the sequence of actions that happen in the test: // // Thread A (main) | Thread B (spawned) // ===============================|================================ // spawns thread B | // -------------------------------+-------------------------------- // waits for n1 | SCOPED_TRACE("Trace B"); // | generates failure #1 // | notifies n1 // -------------------------------+-------------------------------- // SCOPED_TRACE("Trace A"); | waits for n2 // generates failure #2 | // notifies n2 | // -------------------------------|-------------------------------- // waits for n3 | generates failure #3 // | trace B dies // | generates failure #4 // | notifies n3 // -------------------------------|-------------------------------- // generates failure #5 | finishes // trace A dies | // generates failure #6 | // -------------------------------|-------------------------------- // waits for thread B to finish | struct CheckPoints { Notification n1; Notification n2; Notification n3; }; static void ThreadWithScopedTrace(CheckPoints* check_points) { { SCOPED_TRACE("Trace B"); ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive)."; check_points->n1.Notify(); check_points->n2.WaitForNotification(); ADD_FAILURE() << "Expected failure #3 (in thread B, trace A & B both alive)."; } // Trace B dies here. ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive)."; check_points->n3.Notify(); } TEST(SCOPED_TRACETest, WorksConcurrently) { printf("(expecting 6 failures)\n"); CheckPoints check_points; ThreadWithParam thread(&ThreadWithScopedTrace, &check_points, nullptr); check_points.n1.WaitForNotification(); { SCOPED_TRACE("Trace A"); ADD_FAILURE() << "Expected failure #2 (in thread A, trace A & B both alive)."; check_points.n2.Notify(); check_points.n3.WaitForNotification(); ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive)."; } // Trace A dies here. ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive)."; thread.Join(); } #endif // GTEST_IS_THREADSAFE // Tests basic functionality of the ScopedTrace utility (most of its features // are already tested in SCOPED_TRACETest). TEST(ScopedTraceTest, WithExplicitFileAndLine) { testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message"); ADD_FAILURE() << "Check that the trace is attached to a particular location."; } TEST(DisabledTestsWarningTest, DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) { // This test body is intentionally empty. Its sole purpose is for // verifying that the --gtest_also_run_disabled_tests flag // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of // the test output. } // Tests using assertions outside of TEST and TEST_F. // // This function creates two failures intentionally. void AdHocTest() { printf("The non-test part of the code is expected to have 2 failures.\n\n"); EXPECT_TRUE(false); EXPECT_EQ(2, 3); } // Runs all TESTs, all TEST_Fs, and the ad hoc test. int RunAllTests() { AdHocTest(); return RUN_ALL_TESTS(); } // Tests non-fatal failures in the fixture constructor. class NonFatalFailureInFixtureConstructorTest : public testing::Test { protected: NonFatalFailureInFixtureConstructorTest() { printf("(expecting 5 failures)\n"); ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor."; } ~NonFatalFailureInFixtureConstructorTest() { ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor."; } virtual void SetUp() { ADD_FAILURE() << "Expected failure #2, in SetUp()."; } virtual void TearDown() { ADD_FAILURE() << "Expected failure #4, in TearDown."; } }; TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) { ADD_FAILURE() << "Expected failure #3, in the test body."; } // Tests fatal failures in the fixture constructor. class FatalFailureInFixtureConstructorTest : public testing::Test { protected: FatalFailureInFixtureConstructorTest() { printf("(expecting 2 failures)\n"); Init(); } ~FatalFailureInFixtureConstructorTest() { ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor."; } virtual void SetUp() { ADD_FAILURE() << "UNEXPECTED failure in SetUp(). " << "We should never get here, as the test fixture c'tor " << "had a fatal failure."; } virtual void TearDown() { ADD_FAILURE() << "UNEXPECTED failure in TearDown(). " << "We should never get here, as the test fixture c'tor " << "had a fatal failure."; } private: void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; } }; TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { ADD_FAILURE() << "UNEXPECTED failure in the test body. " << "We should never get here, as the test fixture c'tor " << "had a fatal failure."; } // Tests non-fatal failures in SetUp(). class NonFatalFailureInSetUpTest : public testing::Test { protected: virtual ~NonFatalFailureInSetUpTest() { Deinit(); } virtual void SetUp() { printf("(expecting 4 failures)\n"); ADD_FAILURE() << "Expected failure #1, in SetUp()."; } virtual void TearDown() { FAIL() << "Expected failure #3, in TearDown()."; } private: void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; } }; TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { FAIL() << "Expected failure #2, in the test function."; } // Tests fatal failures in SetUp(). class FatalFailureInSetUpTest : public testing::Test { protected: virtual ~FatalFailureInSetUpTest() { Deinit(); } virtual void SetUp() { printf("(expecting 3 failures)\n"); FAIL() << "Expected failure #1, in SetUp()."; } virtual void TearDown() { FAIL() << "Expected failure #2, in TearDown()."; } private: void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; } }; TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { FAIL() << "UNEXPECTED failure in the test function. " << "We should never get here, as SetUp() failed."; } TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) { ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc"; } #if GTEST_IS_THREADSAFE // A unary function that may die. void DieIf(bool should_die) { GTEST_CHECK_(!should_die) << " - death inside DieIf()."; } // Tests running death tests in a multi-threaded context. // Used for coordination between the main and the spawn thread. struct SpawnThreadNotifications { SpawnThreadNotifications() {} Notification spawn_thread_started; Notification spawn_thread_ok_to_terminate; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications); }; // The function to be executed in the thread spawn by the // MultipleThreads test (below). static void ThreadRoutine(SpawnThreadNotifications* notifications) { // Signals the main thread that this thread has started. notifications->spawn_thread_started.Notify(); // Waits for permission to finish from the main thread. notifications->spawn_thread_ok_to_terminate.WaitForNotification(); } // This is a death-test test, but it's not named with a DeathTest // suffix. It starts threads which might interfere with later // death tests, so it must run after all other death tests. class DeathTestAndMultiThreadsTest : public testing::Test { protected: // Starts a thread and waits for it to begin. virtual void SetUp() { thread_.reset(new ThreadWithParam( &ThreadRoutine, ¬ifications_, nullptr)); notifications_.spawn_thread_started.WaitForNotification(); } // Tells the thread to finish, and reaps it. // Depending on the version of the thread library in use, // a manager thread might still be left running that will interfere // with later death tests. This is unfortunate, but this class // cleans up after itself as best it can. virtual void TearDown() { notifications_.spawn_thread_ok_to_terminate.Notify(); } private: SpawnThreadNotifications notifications_; - testing::internal::scoped_ptr > - thread_; + std::unique_ptr > thread_; }; #endif // GTEST_IS_THREADSAFE // The MixedUpTestCaseTest test case verifies that Google Test will fail a // test if it uses a different fixture class than what other tests in // the same test case use. It deliberately contains two fixture // classes with the same name but defined in different namespaces. // The MixedUpTestCaseWithSameTestNameTest test case verifies that // when the user defines two tests with the same test case name AND // same test name (but in different namespaces), the second test will // fail. namespace foo { class MixedUpTestCaseTest : public testing::Test { }; TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {} class MixedUpTestCaseWithSameTestNameTest : public testing::Test { }; TEST_F(MixedUpTestCaseWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} } // namespace foo namespace bar { class MixedUpTestCaseTest : public testing::Test { }; // The following two tests are expected to fail. We rely on the // golden file to check that Google Test generates the right error message. TEST_F(MixedUpTestCaseTest, ThisShouldFail) {} TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {} class MixedUpTestCaseWithSameTestNameTest : public testing::Test { }; // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. TEST_F(MixedUpTestCaseWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} } // namespace bar // The following two test cases verify that Google Test catches the user // error of mixing TEST and TEST_F in the same test case. The first // test case checks the scenario where TEST_F appears before TEST, and // the second one checks where TEST appears before TEST_F. class TEST_F_before_TEST_in_same_test_case : public testing::Test { }; TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} class TEST_before_TEST_F_in_same_test_case : public testing::Test { }; TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { } // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). int global_integer = 0; // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; }, "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables // (static or not). TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { int m = 0; static int n; n = 1; EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; }, "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // one non-fatal failure and no fatal failure. TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // non-fatal failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { printf("(expecting a failure)\n"); EXPECT_NONFATAL_FAILURE({ }, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // non-fatal failures. TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { printf("(expecting a failure)\n"); EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure 1."; ADD_FAILURE() << "Expected non-fatal failure 2."; }, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal // failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { printf("(expecting a failure)\n"); EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); EXPECT_NONFATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // tested throws. TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { EXPECT_NONFATAL_FAILURE({ throw 0; }, ""); } catch(int) { // NOLINT } } #endif // GTEST_HAS_EXCEPTIONS // Tests that EXPECT_FATAL_FAILURE() can reference global variables. TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; EXPECT_FATAL_FAILURE({ ASSERT_EQ(1, global_integer) << "Expected fatal failure."; }, "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() can reference local static // variables. TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { static int n; n = 1; EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; }, "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // one fatal failure and no non-fatal failure. TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { printf("(expecting a failure)\n"); EXPECT_FATAL_FAILURE({ }, ""); } // A helper for generating a fatal failure. void FatalFailure() { FAIL() << "Expected fatal failure."; } // Tests that EXPECT_FATAL_FAILURE() fails when there are two // fatal failures. TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { printf("(expecting a failure)\n"); EXPECT_FATAL_FAILURE({ FatalFailure(); FatalFailure(); }, ""); } // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { printf("(expecting a failure)\n"); EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, ""); } // Tests that EXPECT_FATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); EXPECT_FATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS // Tests that EXPECT_FATAL_FAILURE() fails when the statement being // tested throws. TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { EXPECT_FATAL_FAILURE({ throw 0; }, ""); } catch(int) { // NOLINT } } #endif // GTEST_HAS_EXCEPTIONS // This #ifdef block tests the output of value-parameterized tests. std::string ParamNameFunc(const testing::TestParamInfo& info) { return info.param; } class ParamTest : public testing::TestWithParam { }; TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); } TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; } INSTANTIATE_TEST_CASE_P(PrintingStrings, ParamTest, testing::Values(std::string("a")), ParamNameFunc); // This #ifdef block tests the output of typed tests. #if GTEST_HAS_TYPED_TEST template class TypedTest : public testing::Test { }; TYPED_TEST_CASE(TypedTest, testing::Types); TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST(TypedTest, Failure) { EXPECT_EQ(1, TypeParam()) << "Expected failure"; } typedef testing::Types TypesForTestWithNames; template class TypedTestWithNames : public testing::Test {}; class TypedTestNames { public: template static std::string GetName(int i) { if (testing::internal::IsSame::value) return std::string("char") + ::testing::PrintToString(i); if (testing::internal::IsSame::value) return std::string("int") + ::testing::PrintToString(i); } }; TYPED_TEST_CASE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames); TYPED_TEST(TypedTestWithNames, Success) {} TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } #endif // GTEST_HAS_TYPED_TEST // This #ifdef block tests the output of type-parameterized tests. #if GTEST_HAS_TYPED_TEST_P template class TypedTestP : public testing::Test { }; TYPED_TEST_CASE_P(TypedTestP); TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); } TYPED_TEST_P(TypedTestP, Failure) { EXPECT_EQ(1U, TypeParam()) << "Expected failure"; } REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure); typedef testing::Types UnsignedTypes; INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes); class TypedTestPNames { public: template static std::string GetName(int i) { if (testing::internal::IsSame::value) { return std::string("unsignedChar") + ::testing::PrintToString(i); } if (testing::internal::IsSame::value) { return std::string("unsignedInt") + ::testing::PrintToString(i); } } }; INSTANTIATE_TYPED_TEST_CASE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, TypedTestPNames); #endif // GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_DEATH_TEST // We rely on the golden file to verify that tests whose test case // name ends with DeathTest are run first. TEST(ADeathTest, ShouldRunFirst) { } # if GTEST_HAS_TYPED_TEST // We rely on the golden file to verify that typed tests whose test // case name ends with DeathTest are run first. template class ATypedDeathTest : public testing::Test { }; typedef testing::Types NumericTypes; TYPED_TEST_CASE(ATypedDeathTest, NumericTypes); TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { } # endif // GTEST_HAS_TYPED_TEST # if GTEST_HAS_TYPED_TEST_P // We rely on the golden file to verify that type-parameterized tests // whose test case name ends with DeathTest are run first. template class ATypeParamDeathTest : public testing::Test { }; TYPED_TEST_CASE_P(ATypeParamDeathTest); TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { } REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst); INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes); # endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_HAS_DEATH_TEST // Tests various failure conditions of // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. class ExpectFailureTest : public testing::Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { FAIL() << "Expected fatal failure."; } else { ADD_FAILURE() << "Expected non-fatal failure."; } } }; TEST_F(ExpectFailureTest, ExpectFatalFailure) { // Expected fatal failure, but succeeds. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); // Expected fatal failure, but got a non-fatal failure. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " "failure."); // Wrong message. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " "expected."); } TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { // Expected non-fatal failure, but succeeds. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure."); // Expected non-fatal failure, but got a fatal failure. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); // Wrong message. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " "failure."); } #if GTEST_IS_THREADSAFE class ExpectFailureWithThreadsTest : public ExpectFailureTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam thread(&AddFailure, failure, nullptr); thread.Join(); } }; TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) { // We only intercept the current thread. printf("(expecting 2 failures)\n"); EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE), "Expected fatal failure."); } TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) { // We only intercept the current thread. printf("(expecting 2 failures)\n"); EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); } typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest; // Tests that the ScopedFakeTestPartResultReporter only catches failures from // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) { printf("(expecting 2 failures)\n"); TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, &results); AddFailureInOtherThread(FATAL_FAILURE); AddFailureInOtherThread(NONFATAL_FAILURE); } // The two failures should not have been intercepted. EXPECT_EQ(0, results.size()) << "This shouldn't fail."; } #endif // GTEST_IS_THREADSAFE TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { // Expected fatal failure, but succeeds. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure."); // Expected fatal failure, but got a non-fatal failure. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), "Expected non-fatal failure."); // Wrong message. printf("(expecting 1 failure)\n"); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), "Some other fatal failure expected."); } TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { // Expected non-fatal failure, but succeeds. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " "failure."); // Expected non-fatal failure, but got a fatal failure. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), "Expected fatal failure."); // Wrong message. printf("(expecting 1 failure)\n"); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), "Some other non-fatal failure."); } // Two test environments for testing testing::AddGlobalTestEnvironment(). class FooEnvironment : public testing::Environment { public: virtual void SetUp() { printf("%s", "FooEnvironment::SetUp() called.\n"); } virtual void TearDown() { printf("%s", "FooEnvironment::TearDown() called.\n"); FAIL() << "Expected fatal failure."; } }; class BarEnvironment : public testing::Environment { public: virtual void SetUp() { printf("%s", "BarEnvironment::SetUp() called.\n"); } virtual void TearDown() { printf("%s", "BarEnvironment::TearDown() called.\n"); ADD_FAILURE() << "Expected non-fatal failure."; } }; // The main function. // // The idea is to use Google Test to run all the tests we have defined (some // of them are intended to fail), and then compare the test results // with the "golden" file. int main(int argc, char **argv) { testing::GTEST_FLAG(print_time) = false; // We just run the tests, knowing some of them are intended to fail. // We will use a separate Python script to compare the output of // this program with the golden file. // It's hard to test InitGoogleTest() directly, as it has many // global side effects. The following line serves as a sanity test // for it. testing::InitGoogleTest(&argc, argv); bool internal_skip_environment_and_ad_hoc_tests = std::count(argv, argv + argc, std::string("internal_skip_environment_and_ad_hoc_tests")) > 0; #if GTEST_HAS_DEATH_TEST if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") { // Skip the usual output capturing if we're running as the child // process of an threadsafe-style death test. # if GTEST_OS_WINDOWS posix::FReopen("nul:", "w", stdout); # else posix::FReopen("/dev/null", "w", stdout); # endif // GTEST_OS_WINDOWS return RUN_ALL_TESTS(); } #endif // GTEST_HAS_DEATH_TEST if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS(); // Registers two global test environments. // The golden file verifies that they are set up in the order they // are registered, and torn down in the reverse order. testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment); #if _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 #endif // _MSC_VER return RunAllTests(); } diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 2de35e0e..e6a227b3 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -1,1300 +1,1293 @@ // Copyright 2008, 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. // // This file tests the internal cross-platform support utilities. #include #include "gtest/internal/gtest-port.h" #if GTEST_OS_MAC # include #endif // GTEST_OS_MAC #include +#include #include // For std::pair and std::make_pair. #include #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #include "src/gtest-internal-inl.h" using std::make_pair; using std::pair; namespace testing { namespace internal { TEST(IsXDigitTest, WorksForNarrowAscii) { EXPECT_TRUE(IsXDigit('0')); EXPECT_TRUE(IsXDigit('9')); EXPECT_TRUE(IsXDigit('A')); EXPECT_TRUE(IsXDigit('F')); EXPECT_TRUE(IsXDigit('a')); EXPECT_TRUE(IsXDigit('f')); EXPECT_FALSE(IsXDigit('-')); EXPECT_FALSE(IsXDigit('g')); EXPECT_FALSE(IsXDigit('G')); } TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { EXPECT_FALSE(IsXDigit(static_cast('\x80'))); EXPECT_FALSE(IsXDigit(static_cast('0' | '\x80'))); } TEST(IsXDigitTest, WorksForWideAscii) { EXPECT_TRUE(IsXDigit(L'0')); EXPECT_TRUE(IsXDigit(L'9')); EXPECT_TRUE(IsXDigit(L'A')); EXPECT_TRUE(IsXDigit(L'F')); EXPECT_TRUE(IsXDigit(L'a')); EXPECT_TRUE(IsXDigit(L'f')); EXPECT_FALSE(IsXDigit(L'-')); EXPECT_FALSE(IsXDigit(L'g')); EXPECT_FALSE(IsXDigit(L'G')); } TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { EXPECT_FALSE(IsXDigit(static_cast(0x80))); EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x80))); EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x100))); } class Base { public: // Copy constructor and assignment operator do exactly what we need, so we // use them. Base() : member_(0) {} explicit Base(int n) : member_(n) {} virtual ~Base() {} int member() { return member_; } private: int member_; }; class Derived : public Base { public: explicit Derived(int n) : Base(n) {} }; TEST(ImplicitCastTest, ConvertsPointers) { Derived derived(0); EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_(&derived)); } TEST(ImplicitCastTest, CanUseInheritance) { Derived derived(1); Base base = ::testing::internal::ImplicitCast_(derived); EXPECT_EQ(derived.member(), base.member()); } class Castable { public: explicit Castable(bool* converted) : converted_(converted) {} operator Base() { *converted_ = true; return Base(); } private: bool* converted_; }; TEST(ImplicitCastTest, CanUseNonConstCastOperator) { bool converted = false; Castable castable(&converted); Base base = ::testing::internal::ImplicitCast_(castable); EXPECT_TRUE(converted); } class ConstCastable { public: explicit ConstCastable(bool* converted) : converted_(converted) {} operator Base() const { *converted_ = true; return Base(); } private: bool* converted_; }; TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { bool converted = false; const ConstCastable const_castable(&converted); Base base = ::testing::internal::ImplicitCast_(const_castable); EXPECT_TRUE(converted); } class ConstAndNonConstCastable { public: ConstAndNonConstCastable(bool* converted, bool* const_converted) : converted_(converted), const_converted_(const_converted) {} operator Base() { *converted_ = true; return Base(); } operator Base() const { *const_converted_ = true; return Base(); } private: bool* converted_; bool* const_converted_; }; TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { bool converted = false; bool const_converted = false; ConstAndNonConstCastable castable(&converted, &const_converted); Base base = ::testing::internal::ImplicitCast_(castable); EXPECT_TRUE(converted); EXPECT_FALSE(const_converted); converted = false; const_converted = false; const ConstAndNonConstCastable const_castable(&converted, &const_converted); base = ::testing::internal::ImplicitCast_(const_castable); EXPECT_FALSE(converted); EXPECT_TRUE(const_converted); } class To { public: To(bool* converted) { *converted = true; } // NOLINT }; TEST(ImplicitCastTest, CanUseImplicitConstructor) { bool converted = false; To to = ::testing::internal::ImplicitCast_(&converted); (void)to; EXPECT_TRUE(converted); } TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { StaticAssertTypeEq::const_iterator>::value_type>(); StaticAssertTypeEq::iterator>::value_type>(); } TEST(IteratorTraitsTest, WorksForPointerToNonConst) { StaticAssertTypeEq::value_type>(); StaticAssertTypeEq::value_type>(); } TEST(IteratorTraitsTest, WorksForPointerToConst) { StaticAssertTypeEq::value_type>(); StaticAssertTypeEq::value_type>(); } -// Tests that the element_type typedef is available in scoped_ptr and refers -// to the parameter type. -TEST(ScopedPtrTest, DefinesElementType) { - StaticAssertTypeEq::element_type>(); -} - -// FIXME: Implement THE REST of scoped_ptr tests. - TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) GTEST_CHECK_(false) << "This should never be executed; " "It's a compilation test only."; if (AlwaysTrue()) GTEST_CHECK_(true); else ; // NOLINT if (AlwaysFalse()) ; // NOLINT else GTEST_CHECK_(true) << ""; } TEST(GtestCheckSyntaxTest, WorksWithSwitch) { switch (0) { case 1: break; default: GTEST_CHECK_(true); } switch (0) case 0: GTEST_CHECK_(true) << "Check failed in switch case"; } // Verifies behavior of FormatFileLocation. TEST(FormatFileLocationTest, FormatsFileLocation) { EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); } TEST(FormatFileLocationTest, FormatsUnknownFile) { EXPECT_PRED_FORMAT2(IsSubstring, "unknown file", FormatFileLocation(nullptr, 42)); EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42)); } TEST(FormatFileLocationTest, FormatsUknownLine) { EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); } TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1)); } // Verifies behavior of FormatCompilerIndependentFileLocation. TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { EXPECT_EQ("unknown file:42", FormatCompilerIndependentFileLocation(nullptr, 42)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1)); } #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast(data); mutex->Lock(); mutex->Unlock(); return nullptr; } TEST(GetThreadCountTest, ReturnsCorrectValue) { const size_t starting_count = GetThreadCount(); pthread_t thread_id; internal::Mutex mutex; { internal::MutexLock lock(&mutex); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); ASSERT_EQ(0, pthread_attr_destroy(&attr)); ASSERT_EQ(0, status); EXPECT_EQ(starting_count + 1, GetThreadCount()); } void* dummy; ASSERT_EQ(0, pthread_join(thread_id, &dummy)); // The OS may not immediately report the updated thread count after // joining a thread, causing flakiness in this test. To counter that, we // wait for up to .5 seconds for the OS to report the correct value. for (int i = 0; i < 5; ++i) { if (GetThreadCount() == starting_count) break; SleepMilliseconds(100); } EXPECT_EQ(starting_count, GetThreadCount()); } #else TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { EXPECT_EQ(0U, GetThreadCount()); } #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const bool a_false_condition = false; const char regex[] = #ifdef _MSC_VER "googletest-port-test\\.cc\\(\\d+\\):" #elif GTEST_USES_POSIX_RE "googletest-port-test\\.cc:[0-9]+" #else "googletest-port-test\\.cc:\\d+" #endif // _MSC_VER ".*a_false_condition.*Extra info.*"; EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", regex); } #if GTEST_HAS_DEATH_TEST TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { EXPECT_EXIT({ GTEST_CHECK_(true) << "Extra info"; ::std::cerr << "Success\n"; exit(0); }, ::testing::ExitedWithCode(0), "Success"); } #endif // GTEST_HAS_DEATH_TEST // Verifies that Google Test choose regular expression engine appropriate to // the platform. The test will produce compiler errors in case of failure. // For simplicity, we only cover the most important platforms here. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { #if !GTEST_USES_PCRE # if GTEST_HAS_POSIX_RE EXPECT_TRUE(GTEST_USES_POSIX_RE); # else EXPECT_TRUE(GTEST_USES_SIMPLE_RE); # endif #endif // !GTEST_USES_PCRE } #if GTEST_USES_POSIX_RE # if GTEST_HAS_TYPED_TEST template class RETest : public ::testing::Test {}; // Defines StringTypes as the list of all string types that class RE // supports. typedef testing::Types< ::std::string, # if GTEST_HAS_GLOBAL_STRING ::string, # endif // GTEST_HAS_GLOBAL_STRING const char*> StringTypes; TYPED_TEST_CASE(RETest, StringTypes); // Tests RE's implicit constructors. TYPED_TEST(RETest, ImplicitConstructorWorks) { const RE empty(TypeParam("")); EXPECT_STREQ("", empty.pattern()); const RE simple(TypeParam("hello")); EXPECT_STREQ("hello", simple.pattern()); const RE normal(TypeParam(".*(\\w+)")); EXPECT_STREQ(".*(\\w+)", normal.pattern()); } // Tests that RE's constructors reject invalid regular expressions. TYPED_TEST(RETest, RejectsInvalidRegex) { EXPECT_NONFATAL_FAILURE({ const RE invalid(TypeParam("?")); }, "\"?\" is not a valid POSIX Extended regular expression."); } // Tests RE::FullMatch(). TYPED_TEST(RETest, FullMatchWorks) { const RE empty(TypeParam("")); EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); const RE re(TypeParam("a.*z")); EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); } // Tests RE::PartialMatch(). TYPED_TEST(RETest, PartialMatchWorks) { const RE empty(TypeParam("")); EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); const RE re(TypeParam("a.*z")); EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); } # endif // GTEST_HAS_TYPED_TEST #elif GTEST_USES_SIMPLE_RE TEST(IsInSetTest, NulCharIsNotInAnySet) { EXPECT_FALSE(IsInSet('\0', "")); EXPECT_FALSE(IsInSet('\0', "\0")); EXPECT_FALSE(IsInSet('\0', "a")); } TEST(IsInSetTest, WorksForNonNulChars) { EXPECT_FALSE(IsInSet('a', "Ab")); EXPECT_FALSE(IsInSet('c', "")); EXPECT_TRUE(IsInSet('b', "bcd")); EXPECT_TRUE(IsInSet('b', "ab")); } TEST(IsAsciiDigitTest, IsFalseForNonDigit) { EXPECT_FALSE(IsAsciiDigit('\0')); EXPECT_FALSE(IsAsciiDigit(' ')); EXPECT_FALSE(IsAsciiDigit('+')); EXPECT_FALSE(IsAsciiDigit('-')); EXPECT_FALSE(IsAsciiDigit('.')); EXPECT_FALSE(IsAsciiDigit('a')); } TEST(IsAsciiDigitTest, IsTrueForDigit) { EXPECT_TRUE(IsAsciiDigit('0')); EXPECT_TRUE(IsAsciiDigit('1')); EXPECT_TRUE(IsAsciiDigit('5')); EXPECT_TRUE(IsAsciiDigit('9')); } TEST(IsAsciiPunctTest, IsFalseForNonPunct) { EXPECT_FALSE(IsAsciiPunct('\0')); EXPECT_FALSE(IsAsciiPunct(' ')); EXPECT_FALSE(IsAsciiPunct('\n')); EXPECT_FALSE(IsAsciiPunct('a')); EXPECT_FALSE(IsAsciiPunct('0')); } TEST(IsAsciiPunctTest, IsTrueForPunct) { for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { EXPECT_PRED1(IsAsciiPunct, *p); } } TEST(IsRepeatTest, IsFalseForNonRepeatChar) { EXPECT_FALSE(IsRepeat('\0')); EXPECT_FALSE(IsRepeat(' ')); EXPECT_FALSE(IsRepeat('a')); EXPECT_FALSE(IsRepeat('1')); EXPECT_FALSE(IsRepeat('-')); } TEST(IsRepeatTest, IsTrueForRepeatChar) { EXPECT_TRUE(IsRepeat('?')); EXPECT_TRUE(IsRepeat('*')); EXPECT_TRUE(IsRepeat('+')); } TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { EXPECT_FALSE(IsAsciiWhiteSpace('\0')); EXPECT_FALSE(IsAsciiWhiteSpace('a')); EXPECT_FALSE(IsAsciiWhiteSpace('1')); EXPECT_FALSE(IsAsciiWhiteSpace('+')); EXPECT_FALSE(IsAsciiWhiteSpace('_')); } TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { EXPECT_TRUE(IsAsciiWhiteSpace(' ')); EXPECT_TRUE(IsAsciiWhiteSpace('\n')); EXPECT_TRUE(IsAsciiWhiteSpace('\r')); EXPECT_TRUE(IsAsciiWhiteSpace('\t')); EXPECT_TRUE(IsAsciiWhiteSpace('\v')); EXPECT_TRUE(IsAsciiWhiteSpace('\f')); } TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { EXPECT_FALSE(IsAsciiWordChar('\0')); EXPECT_FALSE(IsAsciiWordChar('+')); EXPECT_FALSE(IsAsciiWordChar('.')); EXPECT_FALSE(IsAsciiWordChar(' ')); EXPECT_FALSE(IsAsciiWordChar('\n')); } TEST(IsAsciiWordCharTest, IsTrueForLetter) { EXPECT_TRUE(IsAsciiWordChar('a')); EXPECT_TRUE(IsAsciiWordChar('b')); EXPECT_TRUE(IsAsciiWordChar('A')); EXPECT_TRUE(IsAsciiWordChar('Z')); } TEST(IsAsciiWordCharTest, IsTrueForDigit) { EXPECT_TRUE(IsAsciiWordChar('0')); EXPECT_TRUE(IsAsciiWordChar('1')); EXPECT_TRUE(IsAsciiWordChar('7')); EXPECT_TRUE(IsAsciiWordChar('9')); } TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { EXPECT_TRUE(IsAsciiWordChar('_')); } TEST(IsValidEscapeTest, IsFalseForNonPrintable) { EXPECT_FALSE(IsValidEscape('\0')); EXPECT_FALSE(IsValidEscape('\007')); } TEST(IsValidEscapeTest, IsFalseForDigit) { EXPECT_FALSE(IsValidEscape('0')); EXPECT_FALSE(IsValidEscape('9')); } TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { EXPECT_FALSE(IsValidEscape(' ')); EXPECT_FALSE(IsValidEscape('\n')); } TEST(IsValidEscapeTest, IsFalseForSomeLetter) { EXPECT_FALSE(IsValidEscape('a')); EXPECT_FALSE(IsValidEscape('Z')); } TEST(IsValidEscapeTest, IsTrueForPunct) { EXPECT_TRUE(IsValidEscape('.')); EXPECT_TRUE(IsValidEscape('-')); EXPECT_TRUE(IsValidEscape('^')); EXPECT_TRUE(IsValidEscape('$')); EXPECT_TRUE(IsValidEscape('(')); EXPECT_TRUE(IsValidEscape(']')); EXPECT_TRUE(IsValidEscape('{')); EXPECT_TRUE(IsValidEscape('|')); } TEST(IsValidEscapeTest, IsTrueForSomeLetter) { EXPECT_TRUE(IsValidEscape('d')); EXPECT_TRUE(IsValidEscape('D')); EXPECT_TRUE(IsValidEscape('s')); EXPECT_TRUE(IsValidEscape('S')); EXPECT_TRUE(IsValidEscape('w')); EXPECT_TRUE(IsValidEscape('W')); } TEST(AtomMatchesCharTest, EscapedPunct) { EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); } TEST(AtomMatchesCharTest, Escaped_d) { EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); } TEST(AtomMatchesCharTest, Escaped_D) { EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); } TEST(AtomMatchesCharTest, Escaped_s) { EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); } TEST(AtomMatchesCharTest, Escaped_S) { EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); } TEST(AtomMatchesCharTest, Escaped_w) { EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); } TEST(AtomMatchesCharTest, Escaped_W) { EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); } TEST(AtomMatchesCharTest, EscapedWhiteSpace) { EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); } TEST(AtomMatchesCharTest, UnescapedDot) { EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); } TEST(AtomMatchesCharTest, UnescapedChar) { EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); } TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), "NULL is not a valid simple regular expression"); EXPECT_NONFATAL_FAILURE( ASSERT_FALSE(ValidateRegex("a\\")), "Syntax error at index 1 in simple regular expression \"a\\\": "); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), "'\\' cannot appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), "'\\' cannot appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), "invalid escape sequence \"\\h\""); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), "'^' can only appear at the beginning"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), "'^' can only appear at the beginning"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), "'$' can only appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), "'$' can only appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), "'(' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), "')' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), "'[' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), "'{' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), "'?' can only follow a repeatable token"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), "'*' can only follow a repeatable token"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), "'+' can only follow a repeatable token"); } TEST(ValidateRegexTest, ReturnsTrueForValid) { EXPECT_TRUE(ValidateRegex("")); EXPECT_TRUE(ValidateRegex("a")); EXPECT_TRUE(ValidateRegex(".*")); EXPECT_TRUE(ValidateRegex("^a_+")); EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); EXPECT_TRUE(ValidateRegex("09*$")); EXPECT_TRUE(ValidateRegex("^Z$")); EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); // Repeating more than once. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); // Repeating zero times. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); // Repeating zero times. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); // Repeating more than once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); // Repeating zero times. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); // Repeating more than once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); } TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { EXPECT_TRUE(MatchRegexAtHead("", "")); EXPECT_TRUE(MatchRegexAtHead("", "ab")); } TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { EXPECT_FALSE(MatchRegexAtHead("$", "a")); EXPECT_TRUE(MatchRegexAtHead("$", "")); EXPECT_TRUE(MatchRegexAtHead("a$", "a")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); } TEST(MatchRegexAtHeadTest, MatchesSequentially) { EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); } TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { EXPECT_FALSE(MatchRegexAnywhere("", NULL)); } TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); EXPECT_TRUE(MatchRegexAnywhere("^$", "")); } TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); } TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); } TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); } // Tests RE's implicit constructors. TEST(RETest, ImplicitConstructorWorks) { const RE empty(""); EXPECT_STREQ("", empty.pattern()); const RE simple("hello"); EXPECT_STREQ("hello", simple.pattern()); } // Tests that RE's constructors reject invalid regular expressions. TEST(RETest, RejectsInvalidRegex) { EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); }, "NULL is not a valid simple regular expression"); EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); }, "'(' is unsupported"); EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); }, "'?' can only follow a repeatable token"); } // Tests RE::FullMatch(). TEST(RETest, FullMatchWorks) { const RE empty(""); EXPECT_TRUE(RE::FullMatch("", empty)); EXPECT_FALSE(RE::FullMatch("a", empty)); const RE re1("a"); EXPECT_TRUE(RE::FullMatch("a", re1)); const RE re("a.*z"); EXPECT_TRUE(RE::FullMatch("az", re)); EXPECT_TRUE(RE::FullMatch("axyz", re)); EXPECT_FALSE(RE::FullMatch("baz", re)); EXPECT_FALSE(RE::FullMatch("azy", re)); } // Tests RE::PartialMatch(). TEST(RETest, PartialMatchWorks) { const RE empty(""); EXPECT_TRUE(RE::PartialMatch("", empty)); EXPECT_TRUE(RE::PartialMatch("a", empty)); const RE re("a.*z"); EXPECT_TRUE(RE::PartialMatch("az", re)); EXPECT_TRUE(RE::PartialMatch("axyz", re)); EXPECT_TRUE(RE::PartialMatch("baz", re)); EXPECT_TRUE(RE::PartialMatch("azy", re)); EXPECT_FALSE(RE::PartialMatch("zza", re)); } #endif // GTEST_USES_POSIX_RE #if !GTEST_OS_WINDOWS_MOBILE TEST(CaptureTest, CapturesStdout) { CaptureStdout(); fprintf(stdout, "abc"); EXPECT_STREQ("abc", GetCapturedStdout().c_str()); CaptureStdout(); fprintf(stdout, "def%cghi", '\0'); EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); } TEST(CaptureTest, CapturesStderr) { CaptureStderr(); fprintf(stderr, "jkl"); EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); CaptureStderr(); fprintf(stderr, "jkl%cmno", '\0'); EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); } // Tests that stdout and stderr capture don't interfere with each other. TEST(CaptureTest, CapturesStdoutAndStderr) { CaptureStdout(); CaptureStderr(); fprintf(stdout, "pqr"); fprintf(stderr, "stu"); EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); EXPECT_STREQ("stu", GetCapturedStderr().c_str()); } TEST(CaptureDeathTest, CannotReenterStdoutCapture) { CaptureStdout(); EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), "Only one stdout capturer can exist at a time"); GetCapturedStdout(); // We cannot test stderr capturing using death tests as they use it // themselves. } #endif // !GTEST_OS_WINDOWS_MOBILE TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { ThreadLocal t1; EXPECT_EQ(0, t1.get()); ThreadLocal t2; EXPECT_TRUE(t2.get() == nullptr); } TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { ThreadLocal t1(123); EXPECT_EQ(123, t1.get()); int i = 0; ThreadLocal t2(&i); EXPECT_EQ(&i, t2.get()); } class NoDefaultContructor { public: explicit NoDefaultContructor(const char*) {} NoDefaultContructor(const NoDefaultContructor&) {} }; TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { ThreadLocal bar(NoDefaultContructor("foo")); bar.pointer(); } TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { ThreadLocal thread_local_string; EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); // Verifies the condition still holds after calling set. thread_local_string.set("foo"); EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); } TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { ThreadLocal thread_local_string; const ThreadLocal& const_thread_local_string = thread_local_string; EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); thread_local_string.set("foo"); EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); } #if GTEST_IS_THREADSAFE void AddTwo(int* param) { *param += 2; } TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { int i = 40; ThreadWithParam thread(&AddTwo, &i, nullptr); thread.Join(); EXPECT_EQ(42, i); } TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { // AssertHeld() is flaky only in the presence of multiple threads accessing // the lock. In this case, the test is robust. EXPECT_DEATH_IF_SUPPORTED({ Mutex m; { MutexLock lock(&m); } m.AssertHeld(); }, "thread .*hold"); } TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { Mutex m; MutexLock lock(&m); m.AssertHeld(); } class AtomicCounterWithMutex { public: explicit AtomicCounterWithMutex(Mutex* mutex) : value_(0), mutex_(mutex), random_(42) {} void Increment() { MutexLock lock(mutex_); int temp = value_; { // We need to put up a memory barrier to prevent reads and writes to // value_ rearranged with the call to SleepMilliseconds when observed // from other threads. #if GTEST_HAS_PTHREAD // On POSIX, locking a mutex puts up a memory barrier. We cannot use // Mutex and MutexLock here or rely on their memory barrier // functionality as we are testing them here. pthread_mutex_t memory_barrier_mutex; GTEST_CHECK_POSIX_SUCCESS_( pthread_mutex_init(&memory_barrier_mutex, nullptr)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); SleepMilliseconds(random_.Generate(30)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); #elif GTEST_OS_WINDOWS // On Windows, performing an interlocked access puts up a memory barrier. volatile LONG dummy = 0; ::InterlockedIncrement(&dummy); SleepMilliseconds(random_.Generate(30)); ::InterlockedIncrement(&dummy); #else # error "Memory barrier not implemented on this platform." #endif // GTEST_HAS_PTHREAD } value_ = temp + 1; } int value() const { return value_; } private: volatile int value_; Mutex* const mutex_; // Protects value_. Random random_; }; void CountingThreadFunc(pair param) { for (int i = 0; i < param.second; ++i) param.first->Increment(); } // Tests that the mutex only lets one thread at a time to lock it. TEST(MutexTest, OnlyOneThreadCanLockAtATime) { Mutex mutex; AtomicCounterWithMutex locked_counter(&mutex); typedef ThreadWithParam > ThreadType; const int kCycleCount = 20; const int kThreadCount = 7; - scoped_ptr counting_threads[kThreadCount]; + std::unique_ptr counting_threads[kThreadCount]; Notification threads_can_start; // Creates and runs kThreadCount threads that increment locked_counter // kCycleCount times each. for (int i = 0; i < kThreadCount; ++i) { counting_threads[i].reset(new ThreadType(&CountingThreadFunc, make_pair(&locked_counter, kCycleCount), &threads_can_start)); } threads_can_start.Notify(); for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join(); // If the mutex lets more than one thread to increment the counter at a // time, they are likely to encounter a race condition and have some // increments overwritten, resulting in the lower then expected counter // value. EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); } template void RunFromThread(void (func)(T), T param) { ThreadWithParam thread(func, param, nullptr); thread.Join(); } void RetrieveThreadLocalValue( pair*, std::string*> param) { *param.second = param.first->get(); } TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { ThreadLocal thread_local_string("foo"); EXPECT_STREQ("foo", thread_local_string.get().c_str()); thread_local_string.set("bar"); EXPECT_STREQ("bar", thread_local_string.get().c_str()); std::string result; RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local_string, &result)); EXPECT_STREQ("foo", result.c_str()); } // Keeps track of whether of destructors being called on instances of // DestructorTracker. On Windows, waits for the destructor call reports. class DestructorCall { public: DestructorCall() { invoked_ = false; #if GTEST_OS_WINDOWS wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); GTEST_CHECK_(wait_event_.Get() != NULL); #endif } bool CheckDestroyed() const { #if GTEST_OS_WINDOWS if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) return false; #endif return invoked_; } void ReportDestroyed() { invoked_ = true; #if GTEST_OS_WINDOWS ::SetEvent(wait_event_.Get()); #endif } static std::vector& List() { return *list_; } static void ResetList() { for (size_t i = 0; i < list_->size(); ++i) { delete list_->at(i); } list_->clear(); } private: bool invoked_; #if GTEST_OS_WINDOWS AutoHandle wait_event_; #endif static std::vector* const list_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); }; std::vector* const DestructorCall::list_ = new std::vector; // DestructorTracker keeps track of whether its instances have been // destroyed. class DestructorTracker { public: DestructorTracker() : index_(GetNewIndex()) {} DestructorTracker(const DestructorTracker& /* rhs */) : index_(GetNewIndex()) {} ~DestructorTracker() { // We never access DestructorCall::List() concurrently, so we don't need // to protect this access with a mutex. DestructorCall::List()[index_]->ReportDestroyed(); } private: static size_t GetNewIndex() { DestructorCall::List().push_back(new DestructorCall); return DestructorCall::List().size() - 1; } const size_t index_; GTEST_DISALLOW_ASSIGN_(DestructorTracker); }; typedef ThreadLocal* ThreadParam; void CallThreadLocalGet(ThreadParam thread_local_param) { thread_local_param->get(); } // Tests that when a ThreadLocal object dies in a thread, it destroys // the managed object for that thread. TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { DestructorCall::ResetList(); { ThreadLocal thread_local_tracker; ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object for the main thread. thread_local_tracker.get(); ASSERT_EQ(1U, DestructorCall::List().size()); ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); } // Now thread_local_tracker has died. ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); DestructorCall::ResetList(); } // Tests that when a thread exits, the thread-local object for that // thread is destroyed. TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { DestructorCall::ResetList(); { ThreadLocal thread_local_tracker; ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object in the new thread. ThreadWithParam thread(&CallThreadLocalGet, &thread_local_tracker, nullptr); thread.Join(); // The thread has exited, and we should have a DestroyedTracker // instance created for it. But it may not have been destroyed yet. ASSERT_EQ(1U, DestructorCall::List().size()); } // The thread has exited and thread_local_tracker has died. ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); DestructorCall::ResetList(); } TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { ThreadLocal thread_local_string; thread_local_string.set("Foo"); EXPECT_STREQ("Foo", thread_local_string.get().c_str()); std::string result; RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local_string, &result)); EXPECT_TRUE(result.empty()); } #endif // GTEST_IS_THREADSAFE #if GTEST_OS_WINDOWS TEST(WindowsTypesTest, HANDLEIsVoidStar) { StaticAssertTypeEq(); } #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { StaticAssertTypeEq(); } #else TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { StaticAssertTypeEq(); } #endif #endif // GTEST_OS_WINDOWS } // namespace internal } // namespace testing diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc index 1fe5f6ab..e72f1571 100644 --- a/googletest/test/googletest-shuffle-test_.cc +++ b/googletest/test/googletest-shuffle-test_.cc @@ -1,102 +1,101 @@ // Copyright 2009, 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. // Verifies that test shuffling works. #include "gtest/gtest.h" namespace { using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; using ::testing::Message; using ::testing::Test; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::UnitTest; -using ::testing::internal::scoped_ptr; // The test methods are empty, as the sole purpose of this program is // to print the test names before/after shuffling. class A : public Test {}; TEST_F(A, A) {} TEST_F(A, B) {} TEST(ADeathTest, A) {} TEST(ADeathTest, B) {} TEST(ADeathTest, C) {} TEST(B, A) {} TEST(B, B) {} TEST(B, C) {} TEST(B, DISABLED_D) {} TEST(B, DISABLED_E) {} TEST(BDeathTest, A) {} TEST(BDeathTest, B) {} TEST(C, A) {} TEST(C, B) {} TEST(C, C) {} TEST(C, DISABLED_D) {} TEST(CDeathTest, A) {} TEST(DISABLED_D, A) {} TEST(DISABLED_D, DISABLED_B) {} // This printer prints the full test names only, starting each test // iteration with a "----" marker. class TestNamePrinter : public EmptyTestEventListener { public: virtual void OnTestIterationStart(const UnitTest& /* unit_test */, int /* iteration */) { printf("----\n"); } virtual void OnTestStart(const TestInfo& test_info) { printf("%s.%s\n", test_info.test_case_name(), test_info.name()); } }; } // namespace int main(int argc, char **argv) { InitGoogleTest(&argc, argv); // Replaces the default printer with TestNamePrinter, which prints // the test name only. TestEventListeners& listeners = UnitTest::GetInstance()->listeners(); delete listeners.Release(listeners.default_result_printer()); listeners.Append(new TestNamePrinter); return RUN_ALL_TESTS(); } diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc index 3af14038..84348191 100644 --- a/googletest/test/gtest_stress_test.cc +++ b/googletest/test/gtest_stress_test.cc @@ -1,249 +1,248 @@ // 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. // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. #include "gtest/gtest.h" #include #include "src/gtest-internal-inl.h" #if GTEST_IS_THREADSAFE namespace testing { namespace { using internal::Notification; using internal::TestPropertyKeyIs; using internal::ThreadWithParam; -using internal::scoped_ptr; // In order to run tests in this file, for platforms where Google Test is // thread safe, implement ThreadWithParam. See the description of its API // in gtest-port.h, where it is defined for already supported platforms. // How many threads to create? const int kThreadCount = 50; std::string IdToKey(int id, const char* suffix) { Message key; key << "key_" << id << "_" << suffix; return key.GetString(); } std::string IdToString(int id) { Message id_message; id_message << id; return id_message.GetString(); } void ExpectKeyAndValueWereRecordedForId( const std::vector& properties, int id, const char* suffix) { TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str()); const std::vector::const_iterator property = std::find_if(properties.begin(), properties.end(), matches_key); ASSERT_TRUE(property != properties.end()) << "expecting " << suffix << " value for id " << id; EXPECT_STREQ(IdToString(id).c_str(), property->value()); } // Calls a large number of Google Test assertions, where exactly one of them // will fail. void ManyAsserts(int id) { GTEST_LOG_(INFO) << "Thread #" << id << " running..."; SCOPED_TRACE(Message() << "Thread #" << id); for (int i = 0; i < kThreadCount; i++) { SCOPED_TRACE(Message() << "Iteration #" << i); // A bunch of assertions that should succeed. EXPECT_TRUE(true); ASSERT_FALSE(false) << "This shouldn't fail."; EXPECT_STREQ("a", "a"); ASSERT_LE(5, 6); EXPECT_EQ(i, i) << "This shouldn't fail."; // RecordProperty() should interact safely with other threads as well. // The shared_key forces property updates. Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str()); Test::RecordProperty(IdToKey(id, "int").c_str(), id); Test::RecordProperty("shared_key", IdToString(id).c_str()); // This assertion should fail kThreadCount times per thread. It // is for testing whether Google Test can handle failed assertions in a // multi-threaded context. EXPECT_LT(i, 0) << "This should always fail."; } } void CheckTestFailureCount(int expected_failures) { const TestInfo* const info = UnitTest::GetInstance()->current_test_info(); const TestResult* const result = info->result(); GTEST_CHECK_(expected_failures == result->total_part_count()) << "Logged " << result->total_part_count() << " failures " << " vs. " << expected_failures << " expected"; } // Tests using SCOPED_TRACE() and Google Test assertions in many threads // concurrently. TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { { - scoped_ptr > threads[kThreadCount]; + std::unique_ptr > threads[kThreadCount]; Notification threads_can_start; for (int i = 0; i != kThreadCount; i++) threads[i].reset(new ThreadWithParam(&ManyAsserts, i, &threads_can_start)); threads_can_start.Notify(); // Blocks until all the threads are done. for (int i = 0; i != kThreadCount; i++) threads[i]->Join(); } // Ensures that kThreadCount*kThreadCount failures have been reported. const TestInfo* const info = UnitTest::GetInstance()->current_test_info(); const TestResult* const result = info->result(); std::vector properties; // We have no access to the TestResult's list of properties but we can // copy them one by one. for (int i = 0; i < result->test_property_count(); ++i) properties.push_back(result->GetTestProperty(i)); EXPECT_EQ(kThreadCount * 2 + 1, result->test_property_count()) << "String and int values recorded on each thread, " << "as well as one shared_key"; for (int i = 0; i < kThreadCount; ++i) { ExpectKeyAndValueWereRecordedForId(properties, i, "string"); ExpectKeyAndValueWereRecordedForId(properties, i, "int"); } CheckTestFailureCount(kThreadCount*kThreadCount); } void FailingThread(bool is_fatal) { if (is_fatal) FAIL() << "Fatal failure in some other thread. " << "(This failure is expected.)"; else ADD_FAILURE() << "Non-fatal failure in some other thread. " << "(This failure is expected.)"; } void GenerateFatalFailureInAnotherThread(bool is_fatal) { ThreadWithParam thread(&FailingThread, is_fatal, nullptr); thread.Join(); } TEST(NoFatalFailureTest, ExpectNoFatalFailureIgnoresFailuresInOtherThreads) { EXPECT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true)); // We should only have one failure (the one from // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE // should succeed. CheckTestFailureCount(1); } void AssertNoFatalFailureIgnoresFailuresInOtherThreads() { ASSERT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true)); } TEST(NoFatalFailureTest, AssertNoFatalFailureIgnoresFailuresInOtherThreads) { // Using a subroutine, to make sure, that the test continues. AssertNoFatalFailureIgnoresFailuresInOtherThreads(); // We should only have one failure (the one from // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE // should succeed. CheckTestFailureCount(1); } TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) { // This statement should fail, since the current thread doesn't generate a // fatal failure, only another one does. EXPECT_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true), "expected"); CheckTestFailureCount(2); } TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) { // This statement should succeed, because failures in all threads are // considered. EXPECT_FATAL_FAILURE_ON_ALL_THREADS( GenerateFatalFailureInAnotherThread(true), "expected"); CheckTestFailureCount(0); // We need to add a failure, because main() checks that there are failures. // But when only this test is run, we shouldn't have any failures. ADD_FAILURE() << "This is an expected non-fatal failure."; } TEST(NonFatalFailureTest, ExpectNonFatalFailureIgnoresFailuresInOtherThreads) { // This statement should fail, since the current thread doesn't generate a // fatal failure, only another one does. EXPECT_NONFATAL_FAILURE(GenerateFatalFailureInAnotherThread(false), "expected"); CheckTestFailureCount(2); } TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) { // This statement should succeed, because failures in all threads are // considered. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( GenerateFatalFailureInAnotherThread(false), "expected"); CheckTestFailureCount(0); // We need to add a failure, because main() checks that there are failures, // But when only this test is run, we shouldn't have any failures. ADD_FAILURE() << "This is an expected non-fatal failure."; } } // namespace } // namespace testing int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); const int result = RUN_ALL_TESTS(); // Expected to fail. GTEST_CHECK_(result == 1) << "RUN_ALL_TESTS() did not fail as expected"; printf("\nPASS\n"); return 0; } #else TEST(StressTest, DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) { } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif // GTEST_IS_THREADSAFE