Unverified Commit 120863ba authored by Romain Deterre's avatar Romain Deterre Committed by GitHub
Browse files

Update Google Test to v1.10.0 (#840)

This commit updates the version of Google Test from 1.8 to 1.10.
parent b2f89386
...@@ -26,33 +26,30 @@ ...@@ -26,33 +26,30 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Type and function utilities for implementing parameterized tests. // Type and function utilities for implementing parameterized tests.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#include <ctype.h> #include <ctype.h>
#include <cassert>
#include <iterator> #include <iterator>
#include <memory>
#include <set> #include <set>
#include <tuple>
#include <utility> #include <utility>
#include <vector> #include <vector>
// scripts/fuse_gtest.py depends on gtest's own header being #included
// *unconditionally*. Therefore these #includes cannot be moved
// inside #if GTEST_HAS_PARAM_TEST.
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#if GTEST_HAS_PARAM_TEST
namespace testing { namespace testing {
// Input to a parameterized test name generator, describing a test parameter. // Input to a parameterized test name generator, describing a test parameter.
// Consists of the parameter value and the integer parameter index. // Consists of the parameter value and the integer parameter index.
template <class ParamType> template <class ParamType>
...@@ -76,13 +73,14 @@ struct PrintToStringParamName { ...@@ -76,13 +73,14 @@ struct PrintToStringParamName {
namespace internal { namespace internal {
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// // Utility Functions
// Outputs a message explaining invalid registration of different // Outputs a message explaining invalid registration of different
// fixture class for the same test case. This may happen when // fixture class for the same test suite. This may happen when
// TEST_P macro is used to define two tests with the same name // TEST_P macro is used to define two tests with the same name
// but in different namespaces. // but in different namespaces.
GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
CodeLocation code_location); CodeLocation code_location);
template <typename> class ParamGeneratorInterface; template <typename> class ParamGeneratorInterface;
template <typename> class ParamGenerator; template <typename> class ParamGenerator;
...@@ -157,7 +155,7 @@ class ParamIterator { ...@@ -157,7 +155,7 @@ class ParamIterator {
private: private:
friend class ParamGenerator<T>; friend class ParamGenerator<T>;
explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
scoped_ptr<ParamIteratorInterface<T> > impl_; std::unique_ptr<ParamIteratorInterface<T> > impl_;
}; };
// ParamGeneratorInterface<T> is the binary interface to access generators // ParamGeneratorInterface<T> is the binary interface to access generators
...@@ -196,7 +194,7 @@ class ParamGenerator { ...@@ -196,7 +194,7 @@ class ParamGenerator {
iterator end() const { return iterator(impl_->End()); } iterator end() const { return iterator(impl_->End()); }
private: private:
linked_ptr<const ParamGeneratorInterface<T> > impl_; std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
}; };
// Generates values from a range of two comparable values. Can be used to // Generates values from a range of two comparable values. Can be used to
...@@ -209,12 +207,12 @@ class RangeGenerator : public ParamGeneratorInterface<T> { ...@@ -209,12 +207,12 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
RangeGenerator(T begin, T end, IncrementT step) RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin), end_(end), : begin_(begin), end_(end),
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
virtual ~RangeGenerator() {} ~RangeGenerator() override {}
virtual ParamIteratorInterface<T>* Begin() const { ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, begin_, 0, step_); return new Iterator(this, begin_, 0, step_);
} }
virtual ParamIteratorInterface<T>* End() const { ParamIteratorInterface<T>* End() const override {
return new Iterator(this, end_, end_index_, step_); return new Iterator(this, end_, end_index_, step_);
} }
...@@ -224,20 +222,20 @@ class RangeGenerator : public ParamGeneratorInterface<T> { ...@@ -224,20 +222,20 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base, T value, int index, Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step) IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {} : base_(base), value_(value), index_(index), step_(step) {}
virtual ~Iterator() {} ~Iterator() override {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const { const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_; return base_;
} }
virtual void Advance() { void Advance() override {
value_ = static_cast<T>(value_ + step_); value_ = static_cast<T>(value_ + step_);
index_++; index_++;
} }
virtual ParamIteratorInterface<T>* Clone() const { ParamIteratorInterface<T>* Clone() const override {
return new Iterator(*this); return new Iterator(*this);
} }
virtual const T* Current() const { return &value_; } const T* Current() const override { return &value_; }
virtual bool Equals(const ParamIteratorInterface<T>& other) const { bool Equals(const ParamIteratorInterface<T>& other) const override {
// Having the same base generator guarantees that the other // Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast. // iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
...@@ -294,12 +292,12 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { ...@@ -294,12 +292,12 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
template <typename ForwardIterator> template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {} : container_(begin, end) {}
virtual ~ValuesInIteratorRangeGenerator() {} ~ValuesInIteratorRangeGenerator() override {}
virtual ParamIteratorInterface<T>* Begin() const { ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, container_.begin()); return new Iterator(this, container_.begin());
} }
virtual ParamIteratorInterface<T>* End() const { ParamIteratorInterface<T>* End() const override {
return new Iterator(this, container_.end()); return new Iterator(this, container_.end());
} }
...@@ -311,16 +309,16 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { ...@@ -311,16 +309,16 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base, Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator) typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {} : base_(base), iterator_(iterator) {}
virtual ~Iterator() {} ~Iterator() override {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const { const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_; return base_;
} }
virtual void Advance() { void Advance() override {
++iterator_; ++iterator_;
value_.reset(); value_.reset();
} }
virtual ParamIteratorInterface<T>* Clone() const { ParamIteratorInterface<T>* Clone() const override {
return new Iterator(*this); return new Iterator(*this);
} }
// We need to use cached value referenced by iterator_ because *iterator_ // We need to use cached value referenced by iterator_ because *iterator_
...@@ -330,12 +328,11 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { ...@@ -330,12 +328,11 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
// can advance iterator_ beyond the end of the range, and we cannot // can advance iterator_ beyond the end of the range, and we cannot
// detect that fact. The client code, on the other hand, is // detect that fact. The client code, on the other hand, is
// responsible for not calling Current() on an out-of-range iterator. // responsible for not calling Current() on an out-of-range iterator.
virtual const T* Current() const { const T* Current() const override {
if (value_.get() == NULL) if (value_.get() == nullptr) value_.reset(new T(*iterator_));
value_.reset(new T(*iterator_));
return value_.get(); return value_.get();
} }
virtual bool Equals(const ParamIteratorInterface<T>& other) const { bool Equals(const ParamIteratorInterface<T>& other) const override {
// Having the same base generator guarantees that the other // Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast. // iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
...@@ -358,9 +355,9 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { ...@@ -358,9 +355,9 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
// A cached value of *iterator_. We keep it here to allow access by // A cached value of *iterator_. We keep it here to allow access by
// pointer in the wrapping iterator's operator->(). // pointer in the wrapping iterator's operator->().
// value_ needs to be mutable to be accessed in Current(). // 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. // which is bound by the lifespan of the iterator itself.
mutable scoped_ptr<const T> value_; mutable std::unique_ptr<const T> value_;
}; // class ValuesInIteratorRangeGenerator::Iterator }; // class ValuesInIteratorRangeGenerator::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
...@@ -380,25 +377,12 @@ std::string DefaultParamName(const TestParamInfo<ParamType>& info) { ...@@ -380,25 +377,12 @@ std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
return name_stream.GetString(); return name_stream.GetString();
} }
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. template <typename T = int>
// void TestNotEmpty() {
// Parameterized test name overload helpers, which help the static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized
// test name generator and user param name generator.
template <class ParamType, class ParamNameGenFunctor>
ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) {
return func;
}
template <class ParamType>
struct ParamNameGenFunc {
typedef std::string Type(const TestParamInfo<ParamType>&);
};
template <class ParamType>
typename ParamNameGenFunc<ParamType>::Type *GetParamNameGen() {
return DefaultParamName;
} }
template <typename T = int>
void TestNotEmpty(const T&) {}
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
...@@ -410,7 +394,7 @@ class ParameterizedTestFactory : public TestFactoryBase { ...@@ -410,7 +394,7 @@ class ParameterizedTestFactory : public TestFactoryBase {
typedef typename TestClass::ParamType ParamType; typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter) : explicit ParameterizedTestFactory(ParamType parameter) :
parameter_(parameter) {} parameter_(parameter) {}
virtual Test* CreateTest() { Test* CreateTest() override {
TestClass::SetParam(&parameter_); TestClass::SetParam(&parameter_);
return new TestClass(); return new TestClass();
} }
...@@ -438,19 +422,19 @@ class TestMetaFactoryBase { ...@@ -438,19 +422,19 @@ class TestMetaFactoryBase {
// TestMetaFactory creates test factories for passing into // TestMetaFactory creates test factories for passing into
// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
// ownership of test factory pointer, same factory object cannot be passed // ownership of test factory pointer, same factory object cannot be passed
// into that method twice. But ParameterizedTestCaseInfo is going to call // into that method twice. But ParameterizedTestSuiteInfo is going to call
// it for each Test/Parameter value combination. Thus it needs meta factory // it for each Test/Parameter value combination. Thus it needs meta factory
// creator class. // creator class.
template <class TestCase> template <class TestSuite>
class TestMetaFactory class TestMetaFactory
: public TestMetaFactoryBase<typename TestCase::ParamType> { : public TestMetaFactoryBase<typename TestSuite::ParamType> {
public: public:
typedef typename TestCase::ParamType ParamType; using ParamType = typename TestSuite::ParamType;
TestMetaFactory() {} TestMetaFactory() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { TestFactoryBase* CreateTestFactory(ParamType parameter) override {
return new ParameterizedTestFactory<TestCase>(parameter); return new ParameterizedTestFactory<TestSuite>(parameter);
} }
private: private:
...@@ -459,107 +443,106 @@ class TestMetaFactory ...@@ -459,107 +443,106 @@ class TestMetaFactory
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// ParameterizedTestCaseInfoBase is a generic interface // ParameterizedTestSuiteInfoBase is a generic interface
// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
// accumulates test information provided by TEST_P macro invocations // accumulates test information provided by TEST_P macro invocations
// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
// and uses that information to register all resulting test instances // and uses that information to register all resulting test instances
// in RegisterTests method. The ParameterizeTestCaseRegistry class holds // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
// a collection of pointers to the ParameterizedTestCaseInfo objects // a collection of pointers to the ParameterizedTestSuiteInfo objects
// and calls RegisterTests() on each of them when asked. // and calls RegisterTests() on each of them when asked.
class ParameterizedTestCaseInfoBase { class ParameterizedTestSuiteInfoBase {
public: public:
virtual ~ParameterizedTestCaseInfoBase() {} virtual ~ParameterizedTestSuiteInfoBase() {}
// Base part of test case name for display purposes. // Base part of test suite name for display purposes.
virtual const string& GetTestCaseName() const = 0; virtual const std::string& GetTestSuiteName() const = 0;
// Test case id to verify identity. // Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const = 0; virtual TypeId GetTestSuiteTypeId() const = 0;
// UnitTest class invokes this method to register tests in this // UnitTest class invokes this method to register tests in this
// test case right before running them in RUN_ALL_TESTS macro. // test suite right before running them in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single // This method should not be called more than once on any single
// instance of a ParameterizedTestCaseInfoBase derived class. // instance of a ParameterizedTestSuiteInfoBase derived class.
virtual void RegisterTests() = 0; virtual void RegisterTests() = 0;
protected: protected:
ParameterizedTestCaseInfoBase() {} ParameterizedTestSuiteInfoBase() {}
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
}; };
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
// macro invocations for a particular test case and generators // macro invocations for a particular test suite and generators
// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
// test case. It registers tests with all values generated by all // test suite. It registers tests with all values generated by all
// generators when asked. // generators when asked.
template <class TestCase> template <class TestSuite>
class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
public: public:
// ParamType and GeneratorCreationFunc are private types but are required // ParamType and GeneratorCreationFunc are private types but are required
// for declarations of public methods AddTestPattern() and // for declarations of public methods AddTestPattern() and
// AddTestCaseInstantiation(). // AddTestSuiteInstantiation().
typedef typename TestCase::ParamType ParamType; using ParamType = typename TestSuite::ParamType;
// A function that returns an instance of appropriate generator type. // A function that returns an instance of appropriate generator type.
typedef ParamGenerator<ParamType>(GeneratorCreationFunc)(); typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
typedef typename ParamNameGenFunc<ParamType>::Type ParamNameGeneratorFunc; using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
explicit ParameterizedTestCaseInfo( explicit ParameterizedTestSuiteInfo(const char* name,
const char* name, CodeLocation code_location) CodeLocation code_location)
: test_case_name_(name), code_location_(code_location) {} : test_suite_name_(name), code_location_(code_location) {}
// Test case base name for display purposes. // Test case base name for display purposes.
virtual const string& GetTestCaseName() const { return test_case_name_; } const std::string& GetTestSuiteName() const override {
return test_suite_name_;
}
// Test case id to verify identity. // Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); } TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
// TEST_P macro uses AddTestPattern() to record information // TEST_P macro uses AddTestPattern() to record information
// about a single test in a LocalTestInfo structure. // about a single test in a LocalTestInfo structure.
// test_case_name is the base name of the test case (without invocation // test_suite_name is the base name of the test suite (without invocation
// prefix). test_base_name is the name of an individual test without // prefix). test_base_name is the name of an individual test without
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test case base name and DoBar is test base name. // test suite base name and DoBar is test base name.
void AddTestPattern(const char* test_case_name, void AddTestPattern(const char* test_suite_name, const char* test_base_name,
const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory) { TestMetaFactoryBase<ParamType>* meta_factory) {
tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name, tests_.push_back(std::shared_ptr<TestInfo>(
test_base_name, new TestInfo(test_suite_name, test_base_name, meta_factory)));
meta_factory)));
} }
// INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
// about a generator. // about a generator.
int AddTestCaseInstantiation(const string& instantiation_name, int AddTestSuiteInstantiation(const std::string& instantiation_name,
GeneratorCreationFunc* func, GeneratorCreationFunc* func,
ParamNameGeneratorFunc* name_func, ParamNameGeneratorFunc* name_func,
const char* file, const char* file, int line) {
int line) {
instantiations_.push_back( instantiations_.push_back(
InstantiationInfo(instantiation_name, func, name_func, file, line)); InstantiationInfo(instantiation_name, func, name_func, file, line));
return 0; // Return value used only to run this method in namespace scope. 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 // UnitTest class invokes this method to register tests in this test suite
// test cases right before running tests in RUN_ALL_TESTS macro. // test suites right before running tests in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single // This method should not be called more than once on any single
// instance of a ParameterizedTestCaseInfoBase derived class. // instance of a ParameterizedTestSuiteInfoBase derived class.
// UnitTest has a guard to prevent from calling this method more then once. // UnitTest has a guard to prevent from calling this method more than once.
virtual void RegisterTests() { void RegisterTests() override {
for (typename TestInfoContainer::iterator test_it = tests_.begin(); for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) { test_it != tests_.end(); ++test_it) {
linked_ptr<TestInfo> test_info = *test_it; std::shared_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it = for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end(); instantiations_.begin(); gen_it != instantiations_.end();
++gen_it) { ++gen_it) {
const string& instantiation_name = gen_it->name; const std::string& instantiation_name = gen_it->name;
ParamGenerator<ParamType> generator((*gen_it->generator)()); ParamGenerator<ParamType> generator((*gen_it->generator)());
ParamNameGeneratorFunc* name_func = gen_it->name_func; ParamNameGeneratorFunc* name_func = gen_it->name_func;
const char* file = gen_it->file; const char* file = gen_it->file;
int line = gen_it->line; int line = gen_it->line;
string test_case_name; std::string test_suite_name;
if ( !instantiation_name.empty() ) if ( !instantiation_name.empty() )
test_case_name = instantiation_name + "/"; test_suite_name = instantiation_name + "/";
test_case_name += test_info->test_case_base_name; test_suite_name += test_info->test_suite_base_name;
size_t i = 0; size_t i = 0;
std::set<std::string> test_param_names; std::set<std::string> test_param_names;
...@@ -582,39 +565,39 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { ...@@ -582,39 +565,39 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
test_param_names.insert(param_name); test_param_names.insert(param_name);
test_name_stream << test_info->test_base_name << "/" << param_name; if (!test_info->test_base_name.empty()) {
test_name_stream << test_info->test_base_name << "/";
}
test_name_stream << param_name;
MakeAndRegisterTestInfo( MakeAndRegisterTestInfo(
test_case_name.c_str(), test_suite_name.c_str(), test_name_stream.GetString().c_str(),
test_name_stream.GetString().c_str(), nullptr, // No type parameter.
NULL, // No type parameter. PrintToString(*param_it).c_str(), code_location_,
PrintToString(*param_it).c_str(), GetTestSuiteTypeId(),
code_location_, SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
GetTestCaseTypeId(), SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
TestCase::SetUpTestCase,
TestCase::TearDownTestCase,
test_info->test_meta_factory->CreateTestFactory(*param_it)); test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it } // for param_it
} // for gen_it } // for gen_it
} // for test_it } // for test_it
} // RegisterTests } // RegisterTests
private: private:
// LocalTestInfo structure keeps information about a single test registered // LocalTestInfo structure keeps information about a single test registered
// with TEST_P macro. // with TEST_P macro.
struct TestInfo { struct TestInfo {
TestInfo(const char* a_test_case_base_name, TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
const char* a_test_base_name, TestMetaFactoryBase<ParamType>* a_test_meta_factory)
TestMetaFactoryBase<ParamType>* a_test_meta_factory) : : test_suite_base_name(a_test_suite_base_name),
test_case_base_name(a_test_case_base_name), test_base_name(a_test_base_name),
test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory) {}
test_meta_factory(a_test_meta_factory) {}
const std::string test_suite_base_name;
const string test_case_base_name; const std::string test_base_name;
const string test_base_name; const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
}; };
typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer; using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
// Records data received from INSTANTIATE_TEST_CASE_P macros: // Records data received from INSTANTIATE_TEST_SUITE_P macros:
// <Instantiation name, Sequence generator creation function, // <Instantiation name, Sequence generator creation function,
// Name generator function, Source file, Source line> // Name generator function, Source file, Source line>
struct InstantiationInfo { struct InstantiationInfo {
...@@ -651,81 +634,250 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { ...@@ -651,81 +634,250 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
return true; return true;
} }
const string test_case_name_; const std::string test_suite_name_;
CodeLocation code_location_; CodeLocation code_location_;
TestInfoContainer tests_; TestInfoContainer tests_;
InstantiationContainer instantiations_; InstantiationContainer instantiations_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
}; // class ParameterizedTestCaseInfo }; // class ParameterizedTestSuiteInfo
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
template <class TestCase>
using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase // ParameterizedTestSuiteRegistry contains a map of
// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
// macros use it to locate their corresponding ParameterizedTestCaseInfo // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
// descriptors. // ParameterizedTestSuiteInfo descriptors.
class ParameterizedTestCaseRegistry { class ParameterizedTestSuiteRegistry {
public: public:
ParameterizedTestCaseRegistry() {} ParameterizedTestSuiteRegistry() {}
~ParameterizedTestCaseRegistry() { ~ParameterizedTestSuiteRegistry() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); for (auto& test_suite_info : test_suite_infos_) {
it != test_case_infos_.end(); ++it) { delete test_suite_info;
delete *it;
} }
} }
// Looks up or creates and returns a structure containing information about // Looks up or creates and returns a structure containing information about
// tests and instantiations of a particular test case. // tests and instantiations of a particular test suite.
template <class TestCase> template <class TestSuite>
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder( ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
const char* test_case_name, const char* test_suite_name, CodeLocation code_location) {
CodeLocation code_location) { ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL; for (auto& test_suite_info : test_suite_infos_) {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); if (test_suite_info->GetTestSuiteName() == test_suite_name) {
it != test_case_infos_.end(); ++it) { if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
if ((*it)->GetTestCaseName() == test_case_name) {
if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
// Complain about incorrect usage of Google Test facilities // Complain about incorrect usage of Google Test facilities
// and terminate the program since we cannot guaranty correct // and terminate the program since we cannot guaranty correct
// test case setup and tear-down in this case. // test suite setup and tear-down in this case.
ReportInvalidTestCaseType(test_case_name, code_location); ReportInvalidTestSuiteType(test_suite_name, code_location);
posix::Abort(); posix::Abort();
} else { } else {
// At this point we are sure that the object we found is of the same // 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 // type we are looking for, so we downcast it to that type
// without further checks. // without further checks.
typed_test_info = CheckedDowncastToActualType< typed_test_info = CheckedDowncastToActualType<
ParameterizedTestCaseInfo<TestCase> >(*it); ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
} }
break; break;
} }
} }
if (typed_test_info == NULL) { if (typed_test_info == nullptr) {
typed_test_info = new ParameterizedTestCaseInfo<TestCase>( typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
test_case_name, code_location); test_suite_name, code_location);
test_case_infos_.push_back(typed_test_info); test_suite_infos_.push_back(typed_test_info);
} }
return typed_test_info; return typed_test_info;
} }
void RegisterTests() { void RegisterTests() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); for (auto& test_suite_info : test_suite_infos_) {
it != test_case_infos_.end(); ++it) { test_suite_info->RegisterTests();
(*it)->RegisterTests();
} }
} }
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
template <class TestCase>
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
const char* test_case_name, CodeLocation code_location) {
return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
private: private:
typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer; using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
TestCaseInfoContainer test_case_infos_; TestSuiteInfoContainer test_suite_infos_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
}; };
} // namespace internal } // namespace internal
} // namespace testing
#endif // GTEST_HAS_PARAM_TEST // Forward declarations of ValuesIn(), which is implemented in
// include/gtest/gtest-param-test.h.
template <class Container>
internal::ParamGenerator<typename Container::value_type> ValuesIn(
const Container& container);
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
template <typename... Ts>
class ValueArray {
public:
ValueArray(Ts... v) : v_{std::move(v)...} {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
}
private:
template <typename T, size_t... I>
std::vector<T> MakeVector(IndexSequence<I...>) const {
return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
}
FlatTuple<Ts...> v_;
};
template <typename... T>
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
public:
typedef ::std::tuple<T...> ParamType;
CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
: generators_(g) {}
~CartesianProductGenerator() override {}
ParamIteratorInterface<ParamType>* Begin() const override {
return new Iterator(this, generators_, false);
}
ParamIteratorInterface<ParamType>* End() const override {
return new Iterator(this, generators_, true);
}
private:
template <class I>
class IteratorImpl;
template <size_t... I>
class IteratorImpl<IndexSequence<I...>>
: public ParamIteratorInterface<ParamType> {
public:
IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
: base_(base),
begin_(std::get<I>(generators).begin()...),
end_(std::get<I>(generators).end()...),
current_(is_end ? end_ : begin_) {
ComputeCurrentValue();
}
~IteratorImpl() override {}
const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
return base_;
}
// Advance should not be called on beyond-of-range iterators
// so no component iterators must be beyond end of range, either.
void Advance() override {
assert(!AtEnd());
// Advance the last iterator.
++std::get<sizeof...(T) - 1>(current_);
// if that reaches end, propagate that up.
AdvanceIfEnd<sizeof...(T) - 1>();
ComputeCurrentValue();
}
ParamIteratorInterface<ParamType>* Clone() const override {
return new IteratorImpl(*this);
}
const ParamType* Current() const override { return current_value_.get(); }
bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
// 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 IteratorImpl* typed_other =
CheckedDowncastToActualType<const IteratorImpl>(&other);
// We must report iterators equal if they both point beyond their
// respective ranges. That can happen in a variety of fashions,
// so we have to consult AtEnd().
if (AtEnd() && typed_other->AtEnd()) return true;
bool same = true;
bool dummy[] = {
(same = same && std::get<I>(current_) ==
std::get<I>(typed_other->current_))...};
(void)dummy;
return same;
}
private:
template <size_t ThisI>
void AdvanceIfEnd() {
if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
bool last = ThisI == 0;
if (last) {
// We are done. Nothing else to propagate.
return;
}
constexpr size_t NextI = ThisI - (ThisI != 0);
std::get<ThisI>(current_) = std::get<ThisI>(begin_);
++std::get<NextI>(current_);
AdvanceIfEnd<NextI>();
}
void ComputeCurrentValue() {
if (!AtEnd())
current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
}
bool AtEnd() const {
bool at_end = false;
bool dummy[] = {
(at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
(void)dummy;
return at_end;
}
const ParamGeneratorInterface<ParamType>* const base_;
std::tuple<typename ParamGenerator<T>::iterator...> begin_;
std::tuple<typename ParamGenerator<T>::iterator...> end_;
std::tuple<typename ParamGenerator<T>::iterator...> current_;
std::shared_ptr<ParamType> current_value_;
};
using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
std::tuple<ParamGenerator<T>...> generators_;
};
template <class... Gen>
class CartesianProductHolder {
public:
CartesianProductHolder(const Gen&... g) : generators_(g...) {}
template <typename... T>
operator ParamGenerator<::std::tuple<T...>>() const {
return ParamGenerator<::std::tuple<T...>>(
new CartesianProductGenerator<T...>(generators_));
}
private:
std::tuple<Gen...> generators_;
};
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// The Google C++ Testing Framework (Google Test) // The Google C++ Testing and Mocking Framework (Google Test)
// //
// This header file defines the GTEST_OS_* macro. // This header file defines the GTEST_OS_* macro.
// It is separate from gtest-port.h so that custom/gtest-port.h can include it. // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
...@@ -38,14 +38,13 @@ ...@@ -38,14 +38,13 @@
// Determines the platform on which Google Test is compiled. // Determines the platform on which Google Test is compiled.
#ifdef __CYGWIN__ #ifdef __CYGWIN__
# define GTEST_OS_CYGWIN 1 # define GTEST_OS_CYGWIN 1
#elif defined __SYMBIAN32__ # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
# define GTEST_OS_SYMBIAN 1 # define GTEST_OS_WINDOWS_MINGW 1
# define GTEST_OS_WINDOWS 1
#elif defined _WIN32 #elif defined _WIN32
# define GTEST_OS_WINDOWS 1 # define GTEST_OS_WINDOWS 1
# ifdef _WIN32_WCE # ifdef _WIN32_WCE
# define GTEST_OS_WINDOWS_MOBILE 1 # define GTEST_OS_WINDOWS_MOBILE 1
# elif defined(__MINGW__) || defined(__MINGW32__)
# define GTEST_OS_WINDOWS_MINGW 1
# elif defined(WINAPI_FAMILY) # elif defined(WINAPI_FAMILY)
# include <winapifamily.h> # include <winapifamily.h>
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
...@@ -54,6 +53,9 @@ ...@@ -54,6 +53,9 @@
# define GTEST_OS_WINDOWS_PHONE 1 # define GTEST_OS_WINDOWS_PHONE 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
# define GTEST_OS_WINDOWS_RT 1 # define GTEST_OS_WINDOWS_RT 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
# define GTEST_OS_WINDOWS_PHONE 1
# define GTEST_OS_WINDOWS_TV_TITLE 1
# else # else
// WINAPI_FAMILY defined but no known partition matched. // WINAPI_FAMILY defined but no known partition matched.
// Default to desktop. // Default to desktop.
...@@ -62,13 +64,21 @@ ...@@ -62,13 +64,21 @@
# else # else
# define GTEST_OS_WINDOWS_DESKTOP 1 # define GTEST_OS_WINDOWS_DESKTOP 1
# endif // _WIN32_WCE # endif // _WIN32_WCE
#elif defined __OS2__
# define GTEST_OS_OS2 1
#elif defined __APPLE__ #elif defined __APPLE__
# define GTEST_OS_MAC 1 # define GTEST_OS_MAC 1
# if TARGET_OS_IPHONE # if TARGET_OS_IPHONE
# define GTEST_OS_IOS 1 # define GTEST_OS_IOS 1
# endif # endif
#elif defined __DragonFly__
# define GTEST_OS_DRAGONFLY 1
#elif defined __FreeBSD__ #elif defined __FreeBSD__
# define GTEST_OS_FREEBSD 1 # define GTEST_OS_FREEBSD 1
#elif defined __Fuchsia__
# define GTEST_OS_FUCHSIA 1
#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
# define GTEST_OS_GNU_KFREEBSD 1
#elif defined __linux__ #elif defined __linux__
# define GTEST_OS_LINUX 1 # define GTEST_OS_LINUX 1
# if defined __ANDROID__ # if defined __ANDROID__
...@@ -84,10 +94,14 @@ ...@@ -84,10 +94,14 @@
# define GTEST_OS_HPUX 1 # define GTEST_OS_HPUX 1
#elif defined __native_client__ #elif defined __native_client__
# define GTEST_OS_NACL 1 # define GTEST_OS_NACL 1
#elif defined __NetBSD__
# define GTEST_OS_NETBSD 1
#elif defined __OpenBSD__ #elif defined __OpenBSD__
# define GTEST_OS_OPENBSD 1 # define GTEST_OS_OPENBSD 1
#elif defined __QNX__ #elif defined __QNX__
# define GTEST_OS_QNX 1 # define GTEST_OS_QNX 1
#elif defined(__HAIKU__)
#define GTEST_OS_HAIKU 1
#endif // __CYGWIN__ #endif // __CYGWIN__
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
...@@ -27,8 +27,6 @@ ...@@ -27,8 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Authors: wan@google.com (Zhanyong Wan)
//
// Low-level types and utilities for porting Google Test to various // Low-level types and utilities for porting Google Test to various
// platforms. All macros ending with _ and symbols defined in an // platforms. All macros ending with _ and symbols defined in an
// internal namespace are subject to change without notice. Code // internal namespace are subject to change without notice. Code
...@@ -40,6 +38,8 @@ ...@@ -40,6 +38,8 @@
// files are expected to #include this. Therefore, it cannot #include // files are expected to #include this. Therefore, it cannot #include
// any other Google Test header. // any other Google Test header.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
...@@ -72,12 +72,6 @@ ...@@ -72,12 +72,6 @@
// is/isn't available. // is/isn't available.
// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
// are enabled. // are enabled.
// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::string, which is different to std::string).
// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::wstring, which is different to std::wstring).
// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
// expressions are/aren't available. // expressions are/aren't available.
// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
...@@ -87,8 +81,6 @@ ...@@ -87,8 +81,6 @@
// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
// std::wstring does/doesn't work (Google Test can // std::wstring does/doesn't work (Google Test can
// be used where std::wstring is unavailable). // be used where std::wstring is unavailable).
// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple
// is/isn't available.
// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
// compiler supports Microsoft's "Structured // compiler supports Microsoft's "Structured
// Exception Handling". // Exception Handling".
...@@ -96,12 +88,6 @@ ...@@ -96,12 +88,6 @@
// - Define it to 1/0 to indicate whether the // - Define it to 1/0 to indicate whether the
// platform supports I/O stream redirection using // platform supports I/O stream redirection using
// dup() and dup2(). // dup() and dup2().
// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google
// Test's own tr1 tuple implementation should be
// used. Unused when the user sets
// GTEST_HAS_TR1_TUPLE to 0.
// 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 // GTEST_LINKED_AS_SHARED_LIBRARY
// - Define to 1 when compiling tests that use // - Define to 1 when compiling tests that use
// Google Test as a shared library (known as // Google Test as a shared library (known as
...@@ -109,6 +95,12 @@ ...@@ -109,6 +95,12 @@
// GTEST_CREATE_SHARED_LIBRARY // GTEST_CREATE_SHARED_LIBRARY
// - Define to 1 when compiling Google Test itself // - Define to 1 when compiling Google Test itself
// as a shared library. // 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 // Platform-indicating macros
// -------------------------- // --------------------------
...@@ -121,17 +113,22 @@ ...@@ -121,17 +113,22 @@
// //
// GTEST_OS_AIX - IBM AIX // GTEST_OS_AIX - IBM AIX
// GTEST_OS_CYGWIN - Cygwin // GTEST_OS_CYGWIN - Cygwin
// GTEST_OS_DRAGONFLY - DragonFlyBSD
// GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_FREEBSD - FreeBSD
// GTEST_OS_FUCHSIA - Fuchsia
// GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
// GTEST_OS_HAIKU - Haiku
// GTEST_OS_HPUX - HP-UX // GTEST_OS_HPUX - HP-UX
// GTEST_OS_LINUX - Linux // GTEST_OS_LINUX - Linux
// GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_LINUX_ANDROID - Google Android
// GTEST_OS_MAC - Mac OS X // GTEST_OS_MAC - Mac OS X
// GTEST_OS_IOS - iOS // GTEST_OS_IOS - iOS
// GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_NACL - Google Native Client (NaCl)
// GTEST_OS_NETBSD - NetBSD
// GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_OPENBSD - OpenBSD
// GTEST_OS_OS2 - OS/2
// GTEST_OS_QNX - QNX // GTEST_OS_QNX - QNX
// GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SOLARIS - Sun Solaris
// GTEST_OS_SYMBIAN - Symbian
// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
// GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MINGW - MinGW
...@@ -140,7 +137,7 @@ ...@@ -140,7 +137,7 @@
// GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
// GTEST_OS_ZOS - z/OS // GTEST_OS_ZOS - z/OS
// //
// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
// most stable support. Since core members of the Google Test project // most stable support. Since core members of the Google Test project
// don't have access to other platforms, support for them may be less // don't have access to other platforms, support for them may be less
// stable. If you notice any problems on your platform, please notify // stable. If you notice any problems on your platform, please notify
...@@ -166,19 +163,16 @@ ...@@ -166,19 +163,16 @@
// EXPECT_DEATH(DoSomethingDeadly()); // EXPECT_DEATH(DoSomethingDeadly());
// #endif // #endif
// //
// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized
// tests)
// GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_DEATH_TEST - death tests
// GTEST_HAS_PARAM_TEST - value-parameterized tests
// GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST - typed tests
// GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
// GTEST_IS_THREADSAFE - Google Test is thread-safe. // 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_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
// GTEST_HAS_POSIX_RE (see above) which users can // GTEST_HAS_POSIX_RE (see above) which users can
// define themselves. // define themselves.
// GTEST_USES_SIMPLE_RE - our own simple regex is used; // GTEST_USES_SIMPLE_RE - our own simple regex is used;
// the above two are mutually exclusive. // the above RE\b(s) are mutually exclusive.
// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
// Misc public macros // Misc public macros
// ------------------ // ------------------
...@@ -204,28 +198,16 @@ ...@@ -204,28 +198,16 @@
// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
// is suppressed. // is suppressed.
// //
// C++11 feature wrappers:
//
// testing::internal::move - portability wrapper for std::move.
//
// Synchronization: // Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount() // Mutex, MutexLock, ThreadLocal, GetThreadCount()
// - synchronization primitives. // - 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: // Regular expressions:
// RE - a simple regular expression class using the POSIX // RE - a simple regular expression class using the POSIX
// Extended Regular Expression syntax on UNIX-like // Extended Regular Expression syntax on UNIX-like platforms
// platforms, or a reduced regular exception syntax on // GOOGLETEST_CM0008 DO NOT DELETE
// other platforms, including Windows. // or a reduced regular exception syntax on other
// // platforms, including Windows.
// Logging: // Logging:
// GTEST_LOG_() - logs messages at the specified severity level. // GTEST_LOG_() - logs messages at the specified severity level.
// LogToStderr() - directs all log messages to stderr. // LogToStderr() - directs all log messages to stderr.
...@@ -255,12 +237,20 @@ ...@@ -255,12 +237,20 @@
// BoolFromGTestEnv() - parses a bool environment variable. // BoolFromGTestEnv() - parses a bool environment variable.
// Int32FromGTestEnv() - parses an Int32 environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable.
// StringFromGTestEnv() - parses a string environment variable. // StringFromGTestEnv() - parses a string environment variable.
//
// Deprecation warnings:
// GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
// deprecated; calling a marked function
// should generate a compiler warning
#include <ctype.h> // for isspace, etc #include <ctype.h> // for isspace, etc
#include <stddef.h> // for ptrdiff_t #include <stddef.h> // for ptrdiff_t
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <memory>
#include <type_traits>
#ifndef _WIN32_WCE #ifndef _WIN32_WCE
# include <sys/types.h> # include <sys/types.h>
# include <sys/stat.h> # include <sys/stat.h>
...@@ -272,9 +262,10 @@ ...@@ -272,9 +262,10 @@
#endif #endif
#include <algorithm> // NOLINT #include <algorithm> // NOLINT
#include <iostream> // NOLINT #include <iostream> // NOLINT
#include <sstream> // NOLINT #include <sstream> // NOLINT
#include <string> // NOLINT #include <string> // NOLINT
#include <tuple>
#include <utility> #include <utility>
#include <vector> // NOLINT #include <vector> // NOLINT
...@@ -306,85 +297,32 @@ ...@@ -306,85 +297,32 @@
// GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
// /* code that triggers warnings C4800 and C4385 */ // /* code that triggers warnings C4800 and C4385 */
// GTEST_DISABLE_MSC_WARNINGS_POP_() // GTEST_DISABLE_MSC_WARNINGS_POP_()
#if _MSC_VER >= 1500 #if defined(_MSC_VER)
# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
__pragma(warning(push)) \ __pragma(warning(push)) \
__pragma(warning(disable: warnings)) __pragma(warning(disable: warnings))
# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
__pragma(warning(pop)) __pragma(warning(pop))
#else #else
// Older versions of MSVC don't have __pragma. // Not all compilers are MSVC
# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
# define GTEST_DISABLE_MSC_WARNINGS_POP_() # define GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif #endif
#ifndef GTEST_LANG_CXX11 // Clang on Windows does not understand MSVC's pragma warning.
// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when // We need clang-specific way to disable function deprecation warning.
// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a #ifdef __clang__
// value for __cplusplus, and recent versions of clang, gcc, and # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
// probably other compilers set that too in C++11 mode. _Pragma("clang diagnostic push") \
# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
// Compiling in at least C++11 mode. _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
# define GTEST_LANG_CXX11 1 #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
# else _Pragma("clang diagnostic pop")
# define GTEST_LANG_CXX11 0 #else
# endif # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
#endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
// Distinct from C++11 language support, some environments don't provide GTEST_DISABLE_MSC_WARNINGS_POP_()
// 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
# define GTEST_HAS_STD_FUNCTION_ 1
# define GTEST_HAS_STD_INITIALIZER_LIST_ 1
# define GTEST_HAS_STD_MOVE_ 1
# define GTEST_HAS_STD_SHARED_PTR_ 1
# define GTEST_HAS_STD_TYPE_TRAITS_ 1
# define GTEST_HAS_STD_UNIQUE_PTR_ 1
#endif
// C++11 specifies that <tuple> provides std::tuple.
// Some platforms still might not have it, however.
#if GTEST_LANG_CXX11
# define GTEST_HAS_STD_TUPLE_ 1
# if defined(__clang__)
// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include
# if defined(__has_include) && !__has_include(<tuple>)
# undef GTEST_HAS_STD_TUPLE_
# endif
# elif defined(_MSC_VER)
// Inspired by boost/config/stdlib/dinkumware.hpp
# if defined(_CPPLIB_VER) && _CPPLIB_VER < 520
# undef GTEST_HAS_STD_TUPLE_
# endif
# elif defined(__GLIBCXX__)
// Inspired by boost/config/stdlib/libstdcpp3.hpp,
// http://gcc.gnu.org/gcc-4.2/changes.html and
// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x
# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
# undef GTEST_HAS_STD_TUPLE_
# endif
# endif
#endif #endif
// Brings in definitions for functions used in the testing::internal::posix // Brings in definitions for functions used in the testing::internal::posix
...@@ -396,10 +334,16 @@ ...@@ -396,10 +334,16 @@
# include <io.h> # include <io.h>
# endif # endif
// In order to avoid having to include <windows.h>, use forward declaration // In order to avoid having to include <windows.h>, use forward declaration
// assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. #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 // This assumption is verified by
// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
struct _RTL_CRITICAL_SECTION; typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
#else #else
// This assumes that non-Windows OSes provide unistd.h. For OSes where this // 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 // is not the case, we need to include headers that provide the functions
...@@ -413,7 +357,8 @@ struct _RTL_CRITICAL_SECTION; ...@@ -413,7 +357,8 @@ struct _RTL_CRITICAL_SECTION;
# include <android/api-level.h> // NOLINT # include <android/api-level.h> // NOLINT
#endif #endif
// Defines this to true iff Google Test can use POSIX regular expressions. // Defines this to true if and only if Google Test can use POSIX regular
// expressions.
#ifndef GTEST_HAS_POSIX_RE #ifndef GTEST_HAS_POSIX_RE
# if GTEST_OS_LINUX_ANDROID # if GTEST_OS_LINUX_ANDROID
// On Android, <regex.h> is only available starting with Gingerbread. // On Android, <regex.h> is only available starting with Gingerbread.
...@@ -453,8 +398,11 @@ struct _RTL_CRITICAL_SECTION; ...@@ -453,8 +398,11 @@ struct _RTL_CRITICAL_SECTION;
#ifndef GTEST_HAS_EXCEPTIONS #ifndef GTEST_HAS_EXCEPTIONS
// The user didn't tell us whether exceptions are enabled, so we need // The user didn't tell us whether exceptions are enabled, so we need
// to figure it out. // to figure it out.
# if defined(_MSC_VER) || defined(__BORLANDC__) # if defined(_MSC_VER) && defined(_CPPUNWIND)
// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // MSVC defines _CPPUNWIND to 1 if and only if 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. // macro to enable exceptions, so we'll do the same.
// Assumes that exceptions are enabled by default. // Assumes that exceptions are enabled by default.
# ifndef _HAS_EXCEPTIONS # ifndef _HAS_EXCEPTIONS
...@@ -462,16 +410,17 @@ struct _RTL_CRITICAL_SECTION; ...@@ -462,16 +410,17 @@ struct _RTL_CRITICAL_SECTION;
# endif // _HAS_EXCEPTIONS # endif // _HAS_EXCEPTIONS
# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
# elif defined(__clang__) # elif defined(__clang__)
// clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
// but iff cleanups are enabled after that. In Obj-C++ files, there can be // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions // there can be cleanups for ObjC exceptions which also need cleanups, even if
// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
// exceptions starting at clang r206352, but which checked for cleanups prior to // checks for C++ exceptions starting at clang r206352, but which checked for
// that. To reliably check for C++ exception availability with clang, check for // cleanups prior to that. To reliably check for C++ exception availability with
// clang, check for
// __EXCEPTIONS && __has_feature(cxx_exceptions). // __EXCEPTIONS && __has_feature(cxx_exceptions).
# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
# elif defined(__GNUC__) && __EXCEPTIONS # elif defined(__GNUC__) && __EXCEPTIONS
// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
# define GTEST_HAS_EXCEPTIONS 1 # define GTEST_HAS_EXCEPTIONS 1
# elif defined(__SUNPRO_CC) # elif defined(__SUNPRO_CC)
// Sun Pro CC supports exceptions. However, there is no compile-time way of // Sun Pro CC supports exceptions. However, there is no compile-time way of
...@@ -479,7 +428,7 @@ struct _RTL_CRITICAL_SECTION; ...@@ -479,7 +428,7 @@ struct _RTL_CRITICAL_SECTION;
// they are enabled unless the user tells us otherwise. // they are enabled unless the user tells us otherwise.
# define GTEST_HAS_EXCEPTIONS 1 # define GTEST_HAS_EXCEPTIONS 1
# elif defined(__IBMCPP__) && __EXCEPTIONS # elif defined(__IBMCPP__) && __EXCEPTIONS
// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
# define GTEST_HAS_EXCEPTIONS 1 # define GTEST_HAS_EXCEPTIONS 1
# elif defined(__HP_aCC) # elif defined(__HP_aCC)
// Exception handling is in effect by default in HP aCC compiler. It has to // Exception handling is in effect by default in HP aCC compiler. It has to
...@@ -498,38 +447,21 @@ struct _RTL_CRITICAL_SECTION; ...@@ -498,38 +447,21 @@ struct _RTL_CRITICAL_SECTION;
# define GTEST_HAS_STD_STRING 1 # define GTEST_HAS_STD_STRING 1
#elif !GTEST_HAS_STD_STRING #elif !GTEST_HAS_STD_STRING
// The user told us that ::std::string isn't available. // The user told us that ::std::string isn't available.
# error "Google Test cannot be used where ::std::string isn't available." # error "::std::string isn't available."
#endif // !defined(GTEST_HAS_STD_STRING) #endif // !defined(GTEST_HAS_STD_STRING)
#ifndef GTEST_HAS_GLOBAL_STRING
// The user didn't tell us whether ::string is available, so we need
// to figure it out.
# define GTEST_HAS_GLOBAL_STRING 0
#endif // GTEST_HAS_GLOBAL_STRING
#ifndef GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_STD_WSTRING
// The user didn't tell us whether ::std::wstring is available, so we need // The user didn't tell us whether ::std::wstring is available, so we need
// to figure it out. // to figure it out.
// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
// is available.
// Cygwin 1.7 and below doesn't support ::std::wstring. // Cygwin 1.7 and below doesn't support ::std::wstring.
// Solaris' libc++ doesn't support it either. Android has // Solaris' libc++ doesn't support it either. Android has
// no support for it at least as recent as Froyo (2.2). // no support for it at least as recent as Froyo (2.2).
# define GTEST_HAS_STD_WSTRING \ #define GTEST_HAS_STD_WSTRING \
(!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
GTEST_OS_HAIKU))
#endif // GTEST_HAS_STD_WSTRING #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. // Determines whether RTTI is available.
#ifndef GTEST_HAS_RTTI #ifndef GTEST_HAS_RTTI
// The user didn't tell us whether RTTI is enabled, so we need to // The user didn't tell us whether RTTI is enabled, so we need to
...@@ -537,14 +469,15 @@ struct _RTL_CRITICAL_SECTION; ...@@ -537,14 +469,15 @@ struct _RTL_CRITICAL_SECTION;
# ifdef _MSC_VER # ifdef _MSC_VER
# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
# define GTEST_HAS_RTTI 1 # define GTEST_HAS_RTTI 1
# else # else
# define GTEST_HAS_RTTI 0 # define GTEST_HAS_RTTI 0
# endif # endif
// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) // enabled.
# elif defined(__GNUC__)
# ifdef __GXX_RTTI # ifdef __GXX_RTTI
// When building against STLport with the Android NDK and with // When building against STLport with the Android NDK and with
...@@ -600,8 +533,11 @@ struct _RTL_CRITICAL_SECTION; ...@@ -600,8 +533,11 @@ struct _RTL_CRITICAL_SECTION;
// //
// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
// to your compiler flags. // to your compiler flags.
# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ #define GTEST_HAS_PTHREAD \
|| GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
GTEST_OS_HAIKU)
#endif // GTEST_HAS_PTHREAD #endif // GTEST_HAS_PTHREAD
#if GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD
...@@ -613,138 +549,6 @@ struct _RTL_CRITICAL_SECTION; ...@@ -613,138 +549,6 @@ struct _RTL_CRITICAL_SECTION;
# include <time.h> // NOLINT # include <time.h> // NOLINT
#endif #endif
// Determines if hash_map/hash_set are available.
// Only used for testing against those containers.
#if !defined(GTEST_HAS_HASH_MAP_)
# if _MSC_VER
# 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 Google Test can use tr1/tuple. You can define
// this macro to 0 to prevent Google Test from using tuple (any
// feature depending on tuple with be disabled in this mode).
#ifndef GTEST_HAS_TR1_TUPLE
# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
// STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
# define GTEST_HAS_TR1_TUPLE 0
# else
// The user didn't tell us not to do it, so we assume it's OK.
# define GTEST_HAS_TR1_TUPLE 1
# endif
#endif // GTEST_HAS_TR1_TUPLE
// Determines whether Google Test's own tr1 tuple implementation
// should be used.
#ifndef GTEST_USE_OWN_TR1_TUPLE
// The user didn't tell us, so we need to figure it out.
// We use our own TR1 tuple if we aren't sure the user has an
// implementation of it already. At this time, libstdc++ 4.0.0+ and
// MSVC 2010 are the only mainstream standard libraries that come
// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler
// pretends to be GCC by defining __GNUC__ and friends, but cannot
// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1
// tuple in a 323 MB Feature Pack download, which we cannot assume the
// user has. QNX's QCC compiler is a modified GCC but it doesn't
// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode,
// and it can be used with some compilers that define __GNUC__.
# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
&& !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
# define GTEST_ENV_HAS_TR1_TUPLE_ 1
# endif
// C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
// can build with clang but need to use gcc4.2's libstdc++).
# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
# define GTEST_ENV_HAS_STD_TUPLE_ 1
# endif
# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
# define GTEST_USE_OWN_TR1_TUPLE 0
# else
# define GTEST_USE_OWN_TR1_TUPLE 1
# endif
#endif // GTEST_USE_OWN_TR1_TUPLE
// To avoid conditional compilation everywhere, we make it
// gtest-port.h's responsibility to #include the header implementing
// tuple.
#if GTEST_HAS_STD_TUPLE_
# include <tuple> // IWYU pragma: export
# define GTEST_TUPLE_NAMESPACE_ ::std
#endif // GTEST_HAS_STD_TUPLE_
// We include tr1::tuple even if std::tuple is available to define printers for
// them.
#if GTEST_HAS_TR1_TUPLE
# ifndef GTEST_TUPLE_NAMESPACE_
# define GTEST_TUPLE_NAMESPACE_ ::std::tr1
# endif // GTEST_TUPLE_NAMESPACE_
# if GTEST_USE_OWN_TR1_TUPLE
# include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT
# elif GTEST_ENV_HAS_STD_TUPLE_
# include <tuple>
// C++11 puts its tuple into the ::std namespace rather than
// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there.
// This causes undefined behavior, but supported compilers react in
// the way we intend.
namespace std {
namespace tr1 {
using ::std::get;
using ::std::make_tuple;
using ::std::tuple;
using ::std::tuple_element;
using ::std::tuple_size;
}
}
# elif GTEST_OS_SYMBIAN
// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
// use STLport's tuple implementation, which unfortunately doesn't
// work as the copy of STLport distributed with Symbian is incomplete.
// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
// use its own tuple implementation.
# ifdef BOOST_HAS_TR1_TUPLE
# undef BOOST_HAS_TR1_TUPLE
# endif // BOOST_HAS_TR1_TUPLE
// This prevents <boost/tr1/detail/config.hpp>, which defines
// BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
# include <tuple> // IWYU pragma: export // NOLINT
# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
// GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does
// not conform to the TR1 spec, which requires the header to be <tuple>.
# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
// Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
// which is #included by <tr1/tuple>, to not compile when RTTI is
// disabled. _TR1_FUNCTIONAL is the header guard for
// <tr1/functional>. Hence the following #define is a hack to prevent
// <tr1/functional> from being included.
# define _TR1_FUNCTIONAL 1
# include <tr1/tuple>
# undef _TR1_FUNCTIONAL // Allows the user to #include
// <tr1/functional> if he chooses to.
# else
# include <tr1/tuple> // NOLINT
# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
# else
// If the compiler is not GCC 4.0+, we assume the user is using a
// spec-conforming TR1 implementation.
# include <tuple> // IWYU pragma: export // NOLINT
# endif // GTEST_USE_OWN_TR1_TUPLE
#endif // GTEST_HAS_TR1_TUPLE
// Determines whether clone(2) is supported. // Determines whether clone(2) is supported.
// Usually it will only be available on Linux, excluding // Usually it will only be available on Linux, excluding
// Linux on the Itanium architecture. // Linux on the Itanium architecture.
...@@ -754,8 +558,12 @@ using ::std::tuple_size; ...@@ -754,8 +558,12 @@ using ::std::tuple_size;
# if GTEST_OS_LINUX && !defined(__ia64__) # if GTEST_OS_LINUX && !defined(__ia64__)
# if GTEST_OS_LINUX_ANDROID # if GTEST_OS_LINUX_ANDROID
// On Android, clone() is only available on ARM starting with Gingerbread. // On Android, clone() became available at different API levels for each 32-bit
# if defined(__arm__) && __ANDROID_API__ >= 9 // architecture.
# if defined(__LP64__) || \
(defined(__arm__) && __ANDROID_API__ >= 9) || \
(defined(__mips__) && __ANDROID_API__ >= 12) || \
(defined(__i386__) && __ANDROID_API__ >= 17)
# define GTEST_HAS_CLONE 1 # define GTEST_HAS_CLONE 1
# else # else
# define GTEST_HAS_CLONE 0 # define GTEST_HAS_CLONE 0
...@@ -774,55 +582,41 @@ using ::std::tuple_size; ...@@ -774,55 +582,41 @@ using ::std::tuple_size;
#ifndef GTEST_HAS_STREAM_REDIRECTION #ifndef GTEST_HAS_STREAM_REDIRECTION
// By default, we assume that stream redirection is supported on all // By default, we assume that stream redirection is supported on all
// platforms except known mobile ones. // platforms except known mobile ones.
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
# define GTEST_HAS_STREAM_REDIRECTION 0 # define GTEST_HAS_STREAM_REDIRECTION 0
# else # else
# define GTEST_HAS_STREAM_REDIRECTION 1 # define GTEST_HAS_STREAM_REDIRECTION 1
# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN # endif // !GTEST_OS_WINDOWS_MOBILE
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// Determines whether to support death tests. // 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. // pops up a dialog window that cannot be suppressed programmatically.
#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
(GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \
(GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
# define GTEST_HAS_DEATH_TEST 1 # define GTEST_HAS_DEATH_TEST 1
#endif #endif
// We don't support MSVC 7.1 with exceptions disabled now. Therefore
// all the compilers we care about are adequate for supporting
// value-parameterized tests.
#define GTEST_HAS_PARAM_TEST 1
// Determines whether to support type-driven tests. // Determines whether to support type-driven tests.
// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
// Sun Pro CC, IBM Visual Age, and HP aCC support. // Sun Pro CC, IBM Visual Age, and HP aCC support.
#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
defined(__IBMCPP__) || defined(__HP_aCC) defined(__IBMCPP__) || defined(__HP_aCC)
# define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST 1
# define GTEST_HAS_TYPED_TEST_P 1 # define GTEST_HAS_TYPED_TEST_P 1
#endif #endif
// Determines whether to support Combine(). This only makes sense when
// value-parameterized tests are enabled. The implementation doesn't
// work on Sun Studio since it doesn't understand templated conversion
// operators.
#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
# define GTEST_HAS_COMBINE 1
#endif
// Determines whether the system compiler uses UTF-16 for encoding wide strings. // Determines whether the system compiler uses UTF-16 for encoding wide strings.
#define GTEST_WIDE_STRING_USES_UTF16_ \ #define GTEST_WIDE_STRING_USES_UTF16_ \
(GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
// Determines whether test results can be streamed to a socket. // Determines whether test results can be streamed to a socket.
#if GTEST_OS_LINUX #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
# define GTEST_CAN_STREAM_RESULTS_ 1 # define GTEST_CAN_STREAM_RESULTS_ 1
#endif #endif
...@@ -864,15 +658,33 @@ using ::std::tuple_size; ...@@ -864,15 +658,33 @@ using ::std::tuple_size;
# define GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_
#endif #endif
// 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= // A macro to disallow operator=
// This should be used in the private: declarations for a class. // This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_ASSIGN_(type)\ #define GTEST_DISALLOW_ASSIGN_(type) \
void operator=(type const &) void operator=(type const &) = delete
// A macro to disallow copy constructor and operator= // A macro to disallow copy constructor and operator=
// This should be used in the private: declarations for a class. // This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
type(type const &);\ type(type const &) = delete; \
GTEST_DISALLOW_ASSIGN_(type) GTEST_DISALLOW_ASSIGN_(type)
// Tell the compiler to warn about unused return values for functions declared // Tell the compiler to warn about unused return values for functions declared
...@@ -880,11 +692,11 @@ using ::std::tuple_size; ...@@ -880,11 +692,11 @@ using ::std::tuple_size;
// following the argument list: // following the argument list:
// //
// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) #if defined(__GNUC__) && !defined(COMPILER_ICC)
# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
#else #else
# define GTEST_MUST_USE_RESULT_ # define GTEST_MUST_USE_RESULT_
#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC #endif // __GNUC__ && !COMPILER_ICC
// MS C++ compiler emits warning when a conditional expression is compile time // 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 // constant. In some contexts this warning is false positive and needs to be
...@@ -913,13 +725,22 @@ using ::std::tuple_size; ...@@ -913,13 +725,22 @@ using ::std::tuple_size;
# define GTEST_HAS_SEH 0 # define GTEST_HAS_SEH 0
# endif # 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 #endif // GTEST_HAS_SEH
#ifndef GTEST_IS_THREADSAFE
#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_IS_THREADSAFE
// 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 #ifdef _MSC_VER
# if GTEST_LINKED_AS_SHARED_LIBRARY # if GTEST_LINKED_AS_SHARED_LIBRARY
# define GTEST_API_ __declspec(dllimport) # define GTEST_API_ __declspec(dllimport)
...@@ -928,11 +749,17 @@ using ::std::tuple_size; ...@@ -928,11 +749,17 @@ using ::std::tuple_size;
# endif # endif
#elif __GNUC__ >= 4 || defined(__clang__) #elif __GNUC__ >= 4 || defined(__clang__)
# define GTEST_API_ __attribute__((visibility ("default"))) # define GTEST_API_ __attribute__((visibility ("default")))
#endif // _MSC_VER #endif // _MSC_VER
#endif // GTEST_API_
#ifndef GTEST_API_ #ifndef GTEST_API_
# define GTEST_API_ # define GTEST_API_
#endif #endif // GTEST_API_
#ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
# define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
#endif // GTEST_DEFAULT_DEATH_TEST_STYLE
#ifdef __GNUC__ #ifdef __GNUC__
// Ask the compiler to never inline a given function. // Ask the compiler to never inline a given function.
...@@ -942,10 +769,12 @@ using ::std::tuple_size; ...@@ -942,10 +769,12 @@ using ::std::tuple_size;
#endif #endif
// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) #if !defined(GTEST_HAS_CXXABI_H_)
# define GTEST_HAS_CXXABI_H_ 1 # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
#else # define GTEST_HAS_CXXABI_H_ 1
# define GTEST_HAS_CXXABI_H_ 0 # else
# define GTEST_HAS_CXXABI_H_ 0
# endif
#endif #endif
// A function level attribute to disable checking for use of uninitialized // A function level attribute to disable checking for use of uninitialized
...@@ -973,6 +802,18 @@ using ::std::tuple_size; ...@@ -973,6 +802,18 @@ using ::std::tuple_size;
# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
#endif // __clang__ #endif // __clang__
// A function level attribute to disable HWAddressSanitizer instrumentation.
#if defined(__clang__)
# if __has_feature(hwaddress_sanitizer)
# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
__attribute__((no_sanitize("hwaddress")))
# else
# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
# endif // __has_feature(hwaddress_sanitizer)
#else
# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
#endif // __clang__
// A function level attribute to disable ThreadSanitizer instrumentation. // A function level attribute to disable ThreadSanitizer instrumentation.
#if defined(__clang__) #if defined(__clang__)
# if __has_feature(thread_sanitizer) # if __has_feature(thread_sanitizer)
...@@ -989,16 +830,13 @@ namespace testing { ...@@ -989,16 +830,13 @@ namespace testing {
class Message; class Message;
#if defined(GTEST_TUPLE_NAMESPACE_) // Legacy imports for backwards compatibility.
// Import tuple and friends into the ::testing namespace. // New code should use std:: names directly.
// It is part of our interface, having them in ::testing allows us to change using std::get;
// their types as needed. using std::make_tuple;
using GTEST_TUPLE_NAMESPACE_::get; using std::tuple;
using GTEST_TUPLE_NAMESPACE_::make_tuple; using std::tuple_element;
using GTEST_TUPLE_NAMESPACE_::tuple; using std::tuple_size;
using GTEST_TUPLE_NAMESPACE_::tuple_size;
using GTEST_TUPLE_NAMESPACE_::tuple_element;
#endif // defined(GTEST_TUPLE_NAMESPACE_)
namespace internal { namespace internal {
...@@ -1007,150 +845,30 @@ namespace internal { ...@@ -1007,150 +845,30 @@ namespace internal {
// Secret object, which is what we want. // Secret object, which is what we want.
class Secret; class Secret;
// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
// expression is true. For example, you could use it to verify the // time expression is true (in new code, use static_assert instead). For
// size of a static array: // example, you could use it to verify the size of a static array:
// //
// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
// names_incorrect_size); // names_incorrect_size);
// //
// or to make sure a struct is smaller than a certain size: // The second argument to the macro must be a valid C++ identifier. If the
// // expression is false, compiler will issue an error containing this identifier.
// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
//
// 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 <bool>
struct CompileAssert {
};
# define GTEST_COMPILE_ASSERT_(expr, msg) \
typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
msg[static_cast<bool>(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<bool(expr)>
//
// 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 <typename T1, typename T2>
struct StaticAssertTypeEqHelper;
template <typename T>
struct StaticAssertTypeEqHelper<T, T> {
enum { value = true };
};
// Evaluates to the number of elements in 'array'. // Evaluates to the number of elements in 'array'.
#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #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 // A helper for suppressing warnings on constant condition. It just
// returns 'condition'. // returns 'condition'.
GTEST_API_ bool IsTrue(bool 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 <typename T>
class scoped_ptr {
public:
typedef T element_type;
explicit scoped_ptr(T* p = NULL) : 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_ = NULL;
return ptr;
}
void reset(T* p = NULL) {
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. // 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 <regex.h>. It uses the POSIX Extended // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
// Regular Expression syntax. // Regular Expression syntax.
class GTEST_API_ RE { class GTEST_API_ RE {
...@@ -1162,25 +880,16 @@ class GTEST_API_ RE { ...@@ -1162,25 +880,16 @@ class GTEST_API_ RE {
// Constructs an RE from a string. // Constructs an RE from a string.
RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT 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(const char* regex) { Init(regex); } // NOLINT
~RE(); ~RE();
// Returns the string representation of the regex. // Returns the string representation of the regex.
const char* pattern() const { return pattern_; } const char* pattern() const { return pattern_; }
// FullMatch(str, re) returns true iff regular expression re matches // FullMatch(str, re) returns true if and only if regular expression re
// the entire str. // matches the entire str.
// PartialMatch(str, re) returns true iff regular expression re // PartialMatch(str, re) returns true if and only if regular expression re
// matches a substring of str (including str itself). // matches a substring of str (including str itself).
//
// TODO(wan@google.com): make FullMatch() and PartialMatch() work
// when str contains NUL characters.
static bool FullMatch(const ::std::string& str, const RE& re) { static bool FullMatch(const ::std::string& str, const RE& re) {
return FullMatch(str.c_str(), re); return FullMatch(str.c_str(), re);
} }
...@@ -1188,43 +897,30 @@ class GTEST_API_ RE { ...@@ -1188,43 +897,30 @@ class GTEST_API_ RE {
return PartialMatch(str.c_str(), 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 FullMatch(const char* str, const RE& re);
static bool PartialMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re);
private: private:
void Init(const char* regex); 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. TODO(wan@google.com): change to
// std::string.
const char* pattern_; const char* pattern_;
bool is_valid_; bool is_valid_;
#if GTEST_USES_POSIX_RE # if GTEST_USES_POSIX_RE
regex_t full_regex_; // For FullMatch(). regex_t full_regex_; // For FullMatch().
regex_t partial_regex_; // For PartialMatch(). regex_t partial_regex_; // For PartialMatch().
#else // GTEST_USES_SIMPLE_RE # else // GTEST_USES_SIMPLE_RE
const char* full_pattern_; // For FullMatch(); const char* full_pattern_; // For FullMatch();
#endif # endif
GTEST_DISALLOW_ASSIGN_(RE); GTEST_DISALLOW_ASSIGN_(RE);
}; };
#endif // GTEST_USES_PCRE
// Formats a source file path and a line number as they would appear // 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. // in an error message from the compiler used to compile this code.
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
...@@ -1273,7 +969,7 @@ class GTEST_API_ GTestLog { ...@@ -1273,7 +969,7 @@ class GTEST_API_ GTestLog {
__FILE__, __LINE__).GetStream() __FILE__, __LINE__).GetStream()
inline void LogToStderr() {} inline void LogToStderr() {}
inline void FlushInfoLog() { fflush(NULL); } inline void FlushInfoLog() { fflush(nullptr); }
#endif // !defined(GTEST_LOG_) #endif // !defined(GTEST_LOG_)
...@@ -1310,14 +1006,25 @@ inline void FlushInfoLog() { fflush(NULL); } ...@@ -1310,14 +1006,25 @@ inline void FlushInfoLog() { fflush(NULL); }
GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
<< gtest_error << gtest_error
#if GTEST_HAS_STD_MOVE_ // Transforms "T" into "const T&" according to standard reference collapsing
using std::move; // rules (this is only needed as a backport for C++98 compilers that do not
#else // GTEST_HAS_STD_MOVE_ // 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 <typename T> template <typename T>
const T& move(const T& t) { struct ConstRef { typedef const T& type; };
return t; template <typename T>
} struct ConstRef<T&> { typedef T& type; };
#endif // GTEST_HAS_STD_MOVE_
// The argument T must depend on some template parameters.
#define GTEST_REFERENCE_TO_CONST_(T) \
typename ::testing::internal::ConstRef<T>::type
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
...@@ -1372,13 +1079,13 @@ inline To DownCast_(From* f) { // so we only accept pointers ...@@ -1372,13 +1079,13 @@ inline To DownCast_(From* f) { // so we only accept pointers
GTEST_INTENTIONAL_CONST_COND_PUSH_() GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (false) { if (false) {
GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_INTENTIONAL_CONST_COND_POP_()
const To to = NULL; const To to = nullptr;
::testing::internal::ImplicitCast_<From*>(to); ::testing::internal::ImplicitCast_<From*>(to);
} }
#if GTEST_HAS_RTTI #if GTEST_HAS_RTTI
// RTTI: debug mode only! // RTTI: debug mode only!
GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL); GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
#endif #endif
return static_cast<To>(f); return static_cast<To>(f);
} }
...@@ -1417,10 +1124,6 @@ GTEST_API_ void CaptureStderr(); ...@@ -1417,10 +1124,6 @@ GTEST_API_ void CaptureStderr();
GTEST_API_ std::string GetCapturedStderr(); GTEST_API_ std::string GetCapturedStderr();
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// Returns a path to temporary directory.
GTEST_API_ std::string TempDir();
// Returns the size (in bytes) of a file. // Returns the size (in bytes) of a file.
GTEST_API_ size_t GetFileSize(FILE* file); GTEST_API_ size_t GetFileSize(FILE* file);
...@@ -1428,14 +1131,15 @@ GTEST_API_ size_t GetFileSize(FILE* file); ...@@ -1428,14 +1131,15 @@ GTEST_API_ size_t GetFileSize(FILE* file);
GTEST_API_ std::string ReadEntireFile(FILE* file); GTEST_API_ std::string ReadEntireFile(FILE* file);
// All command line arguments. // All command line arguments.
GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs(); GTEST_API_ std::vector<std::string> GetArgvs();
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
const ::std::vector<testing::internal::string>& GetInjectableArgvs(); std::vector<std::string> GetInjectableArgvs();
void SetInjectableArgvs(const ::std::vector<testing::internal::string>* // Deprecated: pass the args vector by value instead.
new_argvs); void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
void ClearInjectableArgvs();
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
...@@ -1450,7 +1154,7 @@ inline void SleepMilliseconds(int n) { ...@@ -1450,7 +1154,7 @@ inline void SleepMilliseconds(int n) {
0, // 0 seconds. 0, // 0 seconds.
n * 1000L * 1000L, // And n ms. n * 1000L * 1000L, // And n ms.
}; };
nanosleep(&time, NULL); nanosleep(&time, nullptr);
} }
# endif // GTEST_HAS_PTHREAD # endif // GTEST_HAS_PTHREAD
...@@ -1468,7 +1172,7 @@ inline void SleepMilliseconds(int n) { ...@@ -1468,7 +1172,7 @@ inline void SleepMilliseconds(int n) {
class Notification { class Notification {
public: public:
Notification() : notified_(false) { Notification() : notified_(false) {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
} }
~Notification() { ~Notification() {
pthread_mutex_destroy(&mutex_); pthread_mutex_destroy(&mutex_);
...@@ -1526,7 +1230,8 @@ class GTEST_API_ AutoHandle { ...@@ -1526,7 +1230,8 @@ class GTEST_API_ AutoHandle {
void Reset(Handle handle); void Reset(Handle handle);
private: private:
// Returns true iff the handle is a valid handle object that can be closed. // Returns true if and only if the handle is a valid handle object that can be
// closed.
bool IsCloseable() const; bool IsCloseable() const;
Handle handle_; Handle handle_;
...@@ -1577,7 +1282,7 @@ class ThreadWithParamBase { ...@@ -1577,7 +1282,7 @@ class ThreadWithParamBase {
// pass into pthread_create(). // pass into pthread_create().
extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
static_cast<ThreadWithParamBase*>(thread)->Run(); static_cast<ThreadWithParamBase*>(thread)->Run();
return NULL; return nullptr;
} }
// Helper class for testing Google Test's multi-threading constructs. // Helper class for testing Google Test's multi-threading constructs.
...@@ -1606,20 +1311,19 @@ class ThreadWithParam : public ThreadWithParamBase { ...@@ -1606,20 +1311,19 @@ class ThreadWithParam : public ThreadWithParamBase {
// The thread can be created only after all fields except thread_ // The thread can be created only after all fields except thread_
// have been initialized. // have been initialized.
GTEST_CHECK_POSIX_SUCCESS_( GTEST_CHECK_POSIX_SUCCESS_(
pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
} }
~ThreadWithParam() { Join(); } ~ThreadWithParam() override { Join(); }
void Join() { void Join() {
if (!finished_) { if (!finished_) {
GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
finished_ = true; finished_ = true;
} }
} }
virtual void Run() { void Run() override {
if (thread_can_start_ != NULL) if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
thread_can_start_->WaitForNotification();
func_(param_); func_(param_);
} }
...@@ -1629,7 +1333,8 @@ class ThreadWithParam : public ThreadWithParamBase { ...@@ -1629,7 +1333,8 @@ class ThreadWithParam : public ThreadWithParamBase {
// When non-NULL, used to block execution until the controller thread // When non-NULL, used to block execution until the controller thread
// notifies. // notifies.
Notification* const thread_can_start_; Notification* const thread_can_start_;
bool finished_; // true iff we know that the thread function has finished. bool finished_; // true if and only if we know that the thread function has
// finished.
pthread_t thread_; // The native thread object. pthread_t thread_; // The native thread object.
GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
...@@ -1685,7 +1390,7 @@ class GTEST_API_ Mutex { ...@@ -1685,7 +1390,7 @@ class GTEST_API_ Mutex {
// Initializes owner_thread_id_ and critical_section_ in static mutexes. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
void ThreadSafeLazyInit(); void ThreadSafeLazyInit();
// Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
// we assume that 0 is an invalid value for thread IDs. // we assume that 0 is an invalid value for thread IDs.
unsigned int owner_thread_id_; unsigned int owner_thread_id_;
...@@ -1693,7 +1398,7 @@ class GTEST_API_ Mutex { ...@@ -1693,7 +1398,7 @@ class GTEST_API_ Mutex {
// by the linker. // by the linker.
MutexType type_; MutexType type_;
long critical_section_init_phase_; // NOLINT long critical_section_init_phase_; // NOLINT
_RTL_CRITICAL_SECTION* critical_section_; GTEST_CRITICAL_SECTION* critical_section_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
}; };
...@@ -1913,7 +1618,7 @@ class ThreadLocal : public ThreadLocalBase { ...@@ -1913,7 +1618,7 @@ class ThreadLocal : public ThreadLocalBase {
GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
}; };
scoped_ptr<ValueHolderFactory> default_factory_; std::unique_ptr<ValueHolderFactory> default_factory_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
}; };
...@@ -1969,15 +1674,20 @@ class MutexBase { ...@@ -1969,15 +1674,20 @@ class MutexBase {
extern ::testing::internal::MutexBase mutex extern ::testing::internal::MutexBase mutex
// Defines and statically (i.e. at link time) initializes a static mutex. // Defines and statically (i.e. at link time) initializes a static mutex.
# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ // The initialization list here does not explicitly initialize each field,
::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } // 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 // The Mutex class can only be used for mutexes created at runtime. It
// shares its API with MutexBase otherwise. // shares its API with MutexBase otherwise.
class Mutex : public MutexBase { class Mutex : public MutexBase {
public: public:
Mutex() { Mutex() {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
has_owner_ = false; has_owner_ = false;
} }
~Mutex() { ~Mutex() {
...@@ -2027,7 +1737,7 @@ extern "C" inline void DeleteThreadLocalValue(void* value_holder) { ...@@ -2027,7 +1737,7 @@ extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
// Implements thread-local storage on pthreads-based systems. // Implements thread-local storage on pthreads-based systems.
template <typename T> template <typename T>
class ThreadLocal { class GTEST_API_ ThreadLocal {
public: public:
ThreadLocal() ThreadLocal()
: key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
...@@ -2075,7 +1785,7 @@ class ThreadLocal { ...@@ -2075,7 +1785,7 @@ class ThreadLocal {
T* GetOrCreateValue() const { T* GetOrCreateValue() const {
ThreadLocalValueHolderBase* const holder = ThreadLocalValueHolderBase* const holder =
static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
if (holder != NULL) { if (holder != nullptr) {
return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
} }
...@@ -2119,7 +1829,7 @@ class ThreadLocal { ...@@ -2119,7 +1829,7 @@ class ThreadLocal {
// A key pthreads uses for looking up per-thread values. // A key pthreads uses for looking up per-thread values.
const pthread_key_t key_; const pthread_key_t key_;
scoped_ptr<ValueHolderFactory> default_factory_; std::unique_ptr<ValueHolderFactory> default_factory_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
}; };
...@@ -2159,7 +1869,7 @@ class GTestMutexLock { ...@@ -2159,7 +1869,7 @@ class GTestMutexLock {
typedef GTestMutexLock MutexLock; typedef GTestMutexLock MutexLock;
template <typename T> template <typename T>
class ThreadLocal { class GTEST_API_ ThreadLocal {
public: public:
ThreadLocal() : value_() {} ThreadLocal() : value_() {}
explicit ThreadLocal(const T& value) : value_(value) {} explicit ThreadLocal(const T& value) : value_(value) {}
...@@ -2177,58 +1887,8 @@ class ThreadLocal { ...@@ -2177,58 +1887,8 @@ class ThreadLocal {
// we cannot detect it. // we cannot detect it.
GTEST_API_ size_t GetThreadCount(); GTEST_API_ size_t GetThreadCount();
// Passing non-POD classes through ellipsis (...) crashes the ARM template <bool B>
// compiler and generates a warning in Sun Studio. The Nokia Symbian using bool_constant = std::integral_constant<bool, B>;
// 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)
// 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 <bool bool_value>
struct bool_constant {
typedef bool_constant<bool_value> type;
static const bool value = bool_value;
};
template <bool bool_value> const bool bool_constant<bool_value>::value;
typedef bool_constant<false> false_type;
typedef bool_constant<true> true_type;
template <typename T>
struct is_pointer : public false_type {};
template <typename T>
struct is_pointer<T*> : public true_type {};
template <typename Iterator>
struct IteratorTraits {
typedef typename Iterator::value_type value_type;
};
template <typename T>
struct IteratorTraits<T*> {
typedef T value_type;
};
template <typename T>
struct IteratorTraits<const T*> {
typedef T value_type;
};
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# define GTEST_PATH_SEP_ "\\" # define GTEST_PATH_SEP_ "\\"
...@@ -2351,7 +2011,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } ...@@ -2351,7 +2011,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
// Functions deprecated by MSVC 8.0. // Functions deprecated by MSVC 8.0.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
inline const char* StrNCpy(char* dest, const char* src, size_t n) { inline const char* StrNCpy(char* dest, const char* src, size_t n) {
return strncpy(dest, src, n); return strncpy(dest, src, n);
...@@ -2385,29 +2045,29 @@ inline int Close(int fd) { return close(fd); } ...@@ -2385,29 +2045,29 @@ inline int Close(int fd) { return close(fd); }
inline const char* StrError(int errnum) { return strerror(errnum); } inline const char* StrError(int errnum) { return strerror(errnum); }
#endif #endif
inline const char* GetEnv(const char* name) { inline const char* GetEnv(const char* name) {
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
// We are on Windows CE, which has no environment variables. // We are on Windows CE, which has no environment variables.
static_cast<void>(name); // To prevent 'unused argument' warning. static_cast<void>(name); // To prevent 'unused argument' warning.
return NULL; return nullptr;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
// Environment variables which we programmatically clear will be set to the // Environment variables which we programmatically clear will be set to the
// empty string rather than unset (NULL). Handle that case. // empty string rather than unset (NULL). Handle that case.
const char* const env = getenv(name); const char* const env = getenv(name);
return (env != NULL && env[0] != '\0') ? env : NULL; return (env != nullptr && env[0] != '\0') ? env : nullptr;
#else #else
return getenv(name); return getenv(name);
#endif #endif
} }
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_DEPRECATED_POP_()
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
// Windows CE has no C library. The abort() function is used in // Windows CE has no C library. The abort() function is used in
// several places in Google Test. This implementation provides a reasonable // several places in Google Test. This implementation provides a reasonable
// imitation of standard behaviour. // imitation of standard behaviour.
void Abort(); [[noreturn]] void Abort();
#else #else
inline void Abort() { abort(); } [[noreturn]] inline void Abort() { abort(); }
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} // namespace posix } // namespace posix
...@@ -2417,13 +2077,12 @@ inline void Abort() { abort(); } ...@@ -2417,13 +2077,12 @@ inline void Abort() { abort(); }
// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
// function in order to achieve that. We use macro definition here because // function in order to achieve that. We use macro definition here because
// snprintf is a variadic function. // snprintf is a variadic function.
#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
// MSVC 2005 and above support variadic macros. // MSVC 2005 and above support variadic macros.
# define GTEST_SNPRINTF_(buffer, size, format, ...) \ # define GTEST_SNPRINTF_(buffer, size, format, ...) \
_snprintf_s(buffer, size, size, format, __VA_ARGS__) _snprintf_s(buffer, size, size, format, __VA_ARGS__)
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // Windows CE does not define _snprintf_s
// complain about _snprintf.
# define GTEST_SNPRINTF_ _snprintf # define GTEST_SNPRINTF_ _snprintf
#else #else
# define GTEST_SNPRINTF_ snprintf # define GTEST_SNPRINTF_ snprintf
...@@ -2515,15 +2174,15 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. ...@@ -2515,15 +2174,15 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
# define GTEST_DECLARE_int32_(name) \ # define GTEST_DECLARE_int32_(name) \
GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
#define GTEST_DECLARE_string_(name) \ # define GTEST_DECLARE_string_(name) \
GTEST_API_ extern ::std::string GTEST_FLAG(name) GTEST_API_ extern ::std::string GTEST_FLAG(name)
// Macros for defining flags. // Macros for defining flags.
#define GTEST_DEFINE_bool_(name, default_val, doc) \ # define GTEST_DEFINE_bool_(name, default_val, doc) \
GTEST_API_ bool GTEST_FLAG(name) = (default_val) GTEST_API_ bool GTEST_FLAG(name) = (default_val)
#define GTEST_DEFINE_int32_(name, default_val, doc) \ # define GTEST_DEFINE_int32_(name, default_val, doc) \
GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
#define GTEST_DEFINE_string_(name, default_val, doc) \ # define GTEST_DEFINE_string_(name, default_val, doc) \
GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
#endif // !defined(GTEST_DECLARE_bool_) #endif // !defined(GTEST_DECLARE_bool_)
...@@ -2537,18 +2196,36 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. ...@@ -2537,18 +2196,36 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
// Parses 'str' for a 32-bit signed integer. If successful, writes the result // Parses 'str' for a 32-bit signed integer. If successful, writes the result
// to *value and returns true; otherwise leaves *value unchanged and returns // to *value and returns true; otherwise leaves *value unchanged and returns
// false. // false.
// TODO(chandlerc): 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); bool ParseInt32(const Message& src_text, const char* str, Int32* value);
// Parses a bool/Int32/string from the environment variable // Parses a bool/Int32/string from the environment variable
// corresponding to the given Google Test flag. // corresponding to the given Google Test flag.
bool BoolFromGTestEnv(const char* flag, bool default_val); bool BoolFromGTestEnv(const char* flag, bool default_val);
GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
std::string StringFromGTestEnv(const char* flag, const char* default_val); std::string OutputFlagAlsoCheckEnvVar();
const char* StringFromGTestEnv(const char* flag, const char* default_val);
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#if !defined(GTEST_INTERNAL_DEPRECATED)
// Internal Macro to mark an API deprecated, for googletest usage only
// Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
// GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
// a deprecated entity will trigger a warning when compiled with
// `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
// For msvc /W3 option will need to be used
// Note that for 'other' compilers this macro evaluates to nothing to prevent
// compilations errors.
#if defined(_MSC_VER)
#define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
#elif defined(__GNUC__)
#define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
#else
#define GTEST_INTERNAL_DEPRECATED(message)
#endif
#endif // !defined(GTEST_INTERNAL_DEPRECATED)
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
...@@ -27,17 +27,17 @@ ...@@ -27,17 +27,17 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file declares the String class and functions used internally by // This header file declares the String class and functions used internally by
// Google Test. They are subject to change without notice. They should not used // Google Test. They are subject to change without notice. They should not used
// by code external to Google Test. // by code external to Google Test.
// //
// This header file is #included by <gtest/internal/gtest-internal.h>. // This header file is #included by gtest-internal.h.
// It should not be #included by other files. // It should not be #included by other files.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
...@@ -94,7 +94,8 @@ class GTEST_API_ String { ...@@ -94,7 +94,8 @@ class GTEST_API_ String {
static const char* Utf16ToAnsi(LPCWSTR utf16_str); static const char* Utf16ToAnsi(LPCWSTR utf16_str);
#endif #endif
// Compares two C strings. Returns true iff they have the same content. // Compares two C strings. Returns true if and only if they have the same
// content.
// //
// Unlike strcmp(), this function can handle NULL argument(s). A // Unlike strcmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string, // NULL C string is considered different to any non-NULL C string,
...@@ -107,16 +108,16 @@ class GTEST_API_ String { ...@@ -107,16 +108,16 @@ class GTEST_API_ String {
// returned. // returned.
static std::string ShowWideCString(const wchar_t* wide_c_str); static std::string ShowWideCString(const wchar_t* wide_c_str);
// Compares two wide C strings. Returns true iff they have the same // Compares two wide C strings. Returns true if and only if they have the
// content. // same content.
// //
// Unlike wcscmp(), this function can handle NULL argument(s). A // Unlike wcscmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string, // NULL C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
// Compares two C strings, ignoring case. Returns true iff they // Compares two C strings, ignoring case. Returns true if and only if
// have the same content. // they have the same content.
// //
// Unlike strcasecmp(), this function can handle NULL argument(s). // Unlike strcasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL C string, // A NULL C string is considered different to any non-NULL C string,
...@@ -124,8 +125,8 @@ class GTEST_API_ String { ...@@ -124,8 +125,8 @@ class GTEST_API_ String {
static bool CaseInsensitiveCStringEquals(const char* lhs, static bool CaseInsensitiveCStringEquals(const char* lhs,
const char* rhs); const char* rhs);
// Compares two wide C strings, ignoring case. Returns true iff they // Compares two wide C strings, ignoring case. Returns true if and only if
// have the same content. // they have the same content.
// //
// Unlike wcscasecmp(), this function can handle NULL argument(s). // Unlike wcscasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL wide C string, // A NULL C string is considered different to any non-NULL wide C string,
...@@ -139,8 +140,8 @@ class GTEST_API_ String { ...@@ -139,8 +140,8 @@ class GTEST_API_ String {
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs); const wchar_t* rhs);
// Returns true iff the given string ends with the given suffix, ignoring // Returns true if and only if the given string ends with the given suffix,
// case. Any string is considered to end with an empty suffix. // ignoring case. Any string is considered to end with an empty suffix.
static bool EndsWithCaseInsensitive( static bool EndsWithCaseInsensitive(
const std::string& str, const std::string& suffix); const std::string& str, const std::string& suffix);
...@@ -150,6 +151,9 @@ class GTEST_API_ String { ...@@ -150,6 +151,9 @@ class GTEST_API_ String {
// Formats an int value as "%X". // Formats an int value as "%X".
static std::string FormatHexInt(int value); static std::string FormatHexInt(int value);
// Formats an int value as "%X".
static std::string FormatHexUInt32(UInt32 value);
// Formats a byte as "%02X". // Formats a byte as "%02X".
static std::string FormatByte(unsigned char value); static std::string FormatByte(unsigned char value);
......
...@@ -30,17 +30,17 @@ ...@@ -30,17 +30,17 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Type utilities needed for implementing typed and type-parameterized // Type utilities needed for implementing typed and type-parameterized
// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
// //
// Currently we support at most 50 types in a list, and at most 50 // Currently we support at most 50 types in a list, and at most 50
// type-parameterized tests in one type-parameterized test case. // type-parameterized tests in one type-parameterized test suite.
// Please contact googletestframework@googlegroups.com if you need // Please contact googletestframework@googlegroups.com if you need
// more. // more.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
...@@ -57,6 +57,22 @@ ...@@ -57,6 +57,22 @@
namespace testing { namespace testing {
namespace internal { namespace internal {
// Canonicalizes a given name with respect to the Standard C++ Library.
// This handles removing the inline namespace within `std` that is
// used by various standard libraries (e.g., `std::__1`). Names outside
// of namespace std are returned unmodified.
inline std::string CanonicalizeForStdLibVersioning(std::string s) {
static const char prefix[] = "std::__";
if (s.compare(0, strlen(prefix), prefix) == 0) {
std::string::size_type end = s.find("::", strlen(prefix));
if (end != s.npos) {
// Erase everything between the initial `std` and the second `::`.
s.erase(strlen("std"), end - strlen("std"));
}
}
return s;
}
// GetTypeName<T>() returns a human-readable name of type T. // GetTypeName<T>() returns a human-readable name of type T.
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
...@@ -72,10 +88,10 @@ std::string GetTypeName() { ...@@ -72,10 +88,10 @@ std::string GetTypeName() {
# if GTEST_HAS_CXXABI_H_ # if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // GTEST_HAS_CXXABI_H_ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
const std::string name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return CanonicalizeForStdLibVersioning(name_str);
# else # else
return name; return name;
# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
...@@ -89,18 +105,6 @@ std::string GetTypeName() { ...@@ -89,18 +105,6 @@ std::string GetTypeName() {
#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
// AssertyTypeEq<T1, T2>::type is defined iff T1 and T2 are the same
// type. This can be used as a compile-time assertion to ensure that
// two types are equal.
template <typename T1, typename T2>
struct AssertTypeEq;
template <typename T>
struct AssertTypeEq<T, T> {
typedef bool type;
};
// A unique type used as the default value for the arguments of class // A unique type used as the default value for the arguments of class
// template Types. This allows us to simulate variadic templates // template Types. This allows us to simulate variadic templates
// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't // (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
...@@ -3295,8 +3299,8 @@ struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, ...@@ -3295,8 +3299,8 @@ struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
}; };
// The TypeList template makes it possible to use either a single type // The TypeList template makes it possible to use either a single type
// or a Types<...> list in TYPED_TEST_CASE() and // or a Types<...> list in TYPED_TEST_SUITE() and
// INSTANTIATE_TYPED_TEST_CASE_P(). // INSTANTIATE_TYPED_TEST_SUITE_P().
template <typename T> template <typename T>
struct TypeList { struct TypeList {
......
...@@ -28,17 +28,18 @@ $var n = 50 $$ Maximum length of type lists we want to support. ...@@ -28,17 +28,18 @@ $var n = 50 $$ Maximum length of type lists we want to support.
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Type utilities needed for implementing typed and type-parameterized // Type utilities needed for implementing typed and type-parameterized
// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
// //
// Currently we support at most $n types in a list, and at most $n // Currently we support at most $n types in a list, and at most $n
// type-parameterized tests in one type-parameterized test case. // type-parameterized tests in one type-parameterized test suite.
// Please contact googletestframework@googlegroups.com if you need // Please contact googletestframework@googlegroups.com if you need
// more. // more.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
...@@ -55,6 +56,22 @@ $var n = 50 $$ Maximum length of type lists we want to support. ...@@ -55,6 +56,22 @@ $var n = 50 $$ Maximum length of type lists we want to support.
namespace testing { namespace testing {
namespace internal { namespace internal {
// Canonicalizes a given name with respect to the Standard C++ Library.
// This handles removing the inline namespace within `std` that is
// used by various standard libraries (e.g., `std::__1`). Names outside
// of namespace std are returned unmodified.
inline std::string CanonicalizeForStdLibVersioning(std::string s) {
static const char prefix[] = "std::__";
if (s.compare(0, strlen(prefix), prefix) == 0) {
std::string::size_type end = s.find("::", strlen(prefix));
if (end != s.npos) {
// Erase everything between the initial `std` and the second `::`.
s.erase(strlen("std"), end - strlen("std"));
}
}
return s;
}
// GetTypeName<T>() returns a human-readable name of type T. // GetTypeName<T>() returns a human-readable name of type T.
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
...@@ -70,10 +87,10 @@ std::string GetTypeName() { ...@@ -70,10 +87,10 @@ std::string GetTypeName() {
# if GTEST_HAS_CXXABI_H_ # if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // GTEST_HAS_CXXABI_H_ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
const std::string name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return CanonicalizeForStdLibVersioning(name_str);
# else # else
return name; return name;
# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
...@@ -87,18 +104,6 @@ std::string GetTypeName() { ...@@ -87,18 +104,6 @@ std::string GetTypeName() {
#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
// AssertyTypeEq<T1, T2>::type is defined iff T1 and T2 are the same
// type. This can be used as a compile-time assertion to ensure that
// two types are equal.
template <typename T1, typename T2>
struct AssertTypeEq;
template <typename T>
struct AssertTypeEq<T, T> {
typedef bool type;
};
// A unique type used as the default value for the arguments of class // A unique type used as the default value for the arguments of class
// template Types. This allows us to simulate variadic templates // template Types. This allows us to simulate variadic templates
// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't // (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
...@@ -274,8 +279,8 @@ struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { ...@@ -274,8 +279,8 @@ struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> {
]] ]]
// The TypeList template makes it possible to use either a single type // The TypeList template makes it possible to use either a single type
// or a Types<...> list in TYPED_TEST_CASE() and // or a Types<...> list in TYPED_TEST_SUITE() and
// INSTANTIATE_TYPED_TEST_CASE_P(). // INSTANTIATE_TYPED_TEST_SUITE_P().
template <typename T> template <typename T>
struct TypeList { struct TypeList {
......
...@@ -26,9 +26,8 @@ ...@@ -26,9 +26,8 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Author: vladl@google.com (Vlad Losev)
// This provides interface PrimeTable that determines whether a number is a // This provides interface PrimeTable that determines whether a number is a
// prime and determines a next prime number. This interface is used // prime and determines a next prime number. This interface is used
...@@ -44,7 +43,7 @@ class PrimeTable { ...@@ -44,7 +43,7 @@ class PrimeTable {
public: public:
virtual ~PrimeTable() {} virtual ~PrimeTable() {}
// Returns true iff n is a prime number. // Returns true if and only if n is a prime number.
virtual bool IsPrime(int n) const = 0; virtual bool IsPrime(int n) const = 0;
// Returns the smallest prime number greater than p; or returns -1 // Returns the smallest prime number greater than p; or returns -1
...@@ -55,7 +54,7 @@ class PrimeTable { ...@@ -55,7 +54,7 @@ class PrimeTable {
// Implementation #1 calculates the primes on-the-fly. // Implementation #1 calculates the primes on-the-fly.
class OnTheFlyPrimeTable : public PrimeTable { class OnTheFlyPrimeTable : public PrimeTable {
public: public:
virtual bool IsPrime(int n) const { bool IsPrime(int n) const override {
if (n <= 1) return false; if (n <= 1) return false;
for (int i = 2; i*i <= n; i++) { for (int i = 2; i*i <= n; i++) {
...@@ -66,7 +65,7 @@ class OnTheFlyPrimeTable : public PrimeTable { ...@@ -66,7 +65,7 @@ class OnTheFlyPrimeTable : public PrimeTable {
return true; return true;
} }
virtual int GetNextPrime(int p) const { int GetNextPrime(int p) const override {
for (int n = p + 1; n > 0; n++) { for (int n = p + 1; n > 0; n++) {
if (IsPrime(n)) return n; if (IsPrime(n)) return n;
} }
...@@ -84,13 +83,13 @@ class PreCalculatedPrimeTable : public PrimeTable { ...@@ -84,13 +83,13 @@ class PreCalculatedPrimeTable : public PrimeTable {
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) { : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
CalculatePrimesUpTo(max); CalculatePrimesUpTo(max);
} }
virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; } ~PreCalculatedPrimeTable() override { delete[] is_prime_; }
virtual bool IsPrime(int n) const { bool IsPrime(int n) const override {
return 0 <= n && n < is_prime_size_ && is_prime_[n]; return 0 <= n && n < is_prime_size_ && is_prime_[n];
} }
virtual int GetNextPrime(int p) const { int GetNextPrime(int p) const override {
for (int n = p + 1; n < is_prime_size_; n++) { for (int n = p + 1; n < is_prime_size_; n++) {
if (is_prime_[n]) return n; if (is_prime_[n]) return n;
} }
...@@ -103,11 +102,15 @@ class PreCalculatedPrimeTable : public PrimeTable { ...@@ -103,11 +102,15 @@ class PreCalculatedPrimeTable : public PrimeTable {
::std::fill(is_prime_, is_prime_ + is_prime_size_, true); ::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
is_prime_[0] = is_prime_[1] = false; is_prime_[0] = is_prime_[1] = false;
for (int i = 2; i <= max; i++) { // Checks every candidate for prime number (we know that 2 is the only even
// prime).
for (int i = 2; i*i <= max; i += i%2+1) {
if (!is_prime_[i]) continue; if (!is_prime_[i]) continue;
// Marks all multiples of i (except i itself) as non-prime. // Marks all multiples of i (except i itself) as non-prime.
for (int j = 2*i; j <= max; j += i) { // We are starting here from i-th multiplier, because all smaller
// complex numbers were already marked.
for (int j = i*i; j <= max; j += i) {
is_prime_[j] = false; is_prime_[j] = false;
} }
} }
......
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include "sample1.h" #include "sample1.h"
...@@ -43,7 +41,7 @@ int Factorial(int n) { ...@@ -43,7 +41,7 @@ int Factorial(int n) {
return result; return result;
} }
// Returns true iff n is a prime number. // Returns true if and only if n is a prime number.
bool IsPrime(int n) { bool IsPrime(int n) {
// Trivial case 1: small numbers // Trivial case 1: small numbers
if (n <= 1) return false; if (n <= 1) return false;
...@@ -55,7 +53,7 @@ bool IsPrime(int n) { ...@@ -55,7 +53,7 @@ bool IsPrime(int n) {
// Try to divide n by every odd number i, starting from 3 // Try to divide n by every odd number i, starting from 3
for (int i = 3; ; i += 2) { for (int i = 3; ; i += 2) {
// We only have to try i up to the squre root of n // We only have to try i up to the square root of n
if (i > n/i) break; if (i > n/i) break;
// Now, we have i <= n/i < n. // Now, we have i <= n/i < n.
......
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE1_H_ #ifndef GTEST_SAMPLES_SAMPLE1_H_
#define GTEST_SAMPLES_SAMPLE1_H_ #define GTEST_SAMPLES_SAMPLE1_H_
...@@ -37,7 +35,7 @@ ...@@ -37,7 +35,7 @@
// Returns n! (the factorial of n). For negative n, n! is defined to be 1. // Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n); int Factorial(int n);
// Returns true iff n is a prime number. // Returns true if and only if n is a prime number.
bool IsPrime(int n); bool IsPrime(int n);
#endif // GTEST_SAMPLES_SAMPLE1_H_ #endif // GTEST_SAMPLES_SAMPLE1_H_
...@@ -25,8 +25,7 @@ ...@@ -25,8 +25,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// This sample shows how to use Google Test listener API to implement // This sample shows how to use Google Test listener API to implement
// a primitive leak checker. // a primitive leak checker.
...@@ -35,18 +34,15 @@ ...@@ -35,18 +34,15 @@
#include <stdlib.h> #include <stdlib.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
using ::testing::EmptyTestEventListener; using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestCase;
using ::testing::TestEventListeners; using ::testing::TestEventListeners;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::UnitTest; using ::testing::UnitTest;
namespace { namespace {
// We will track memory used by this class. // We will track memory used by this class.
class Water { class Water {
public: public:
...@@ -78,12 +74,12 @@ int Water::allocated_ = 0; ...@@ -78,12 +74,12 @@ int Water::allocated_ = 0;
class LeakChecker : public EmptyTestEventListener { class LeakChecker : public EmptyTestEventListener {
private: private:
// Called before a test starts. // Called before a test starts.
virtual void OnTestStart(const TestInfo& /* test_info */) { void OnTestStart(const TestInfo& /* test_info */) override {
initially_allocated_ = Water::allocated(); initially_allocated_ = Water::allocated();
} }
// Called after a test ends. // Called after a test ends.
virtual void OnTestEnd(const TestInfo& /* test_info */) { void OnTestEnd(const TestInfo& /* test_info */) override {
int difference = Water::allocated() - initially_allocated_; int difference = Water::allocated() - initially_allocated_;
// You can generate a failure in any event handler except // You can generate a failure in any event handler except
...@@ -104,9 +100,8 @@ TEST(ListenersTest, DoesNotLeak) { ...@@ -104,9 +100,8 @@ TEST(ListenersTest, DoesNotLeak) {
// specified. // specified.
TEST(ListenersTest, LeaksWater) { TEST(ListenersTest, LeaksWater) {
Water* water = new Water; Water* water = new Water;
EXPECT_TRUE(water != NULL); EXPECT_TRUE(water != nullptr);
} }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char **argv) {
......
...@@ -28,9 +28,6 @@ ...@@ -28,9 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// This sample shows how to write a simple unit test for a function, // This sample shows how to write a simple unit test for a function,
// using Google C++ testing framework. // using Google C++ testing framework.
...@@ -46,7 +43,7 @@ ...@@ -46,7 +43,7 @@
#include <limits.h> #include <limits.h>
#include "sample1.h" #include "sample1.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace {
// Step 2. Use the TEST macro to define your tests. // Step 2. Use the TEST macro to define your tests.
// //
...@@ -139,6 +136,7 @@ TEST(IsPrimeTest, Positive) { ...@@ -139,6 +136,7 @@ TEST(IsPrimeTest, Positive) {
EXPECT_FALSE(IsPrime(6)); EXPECT_FALSE(IsPrime(6));
EXPECT_TRUE(IsPrime(23)); EXPECT_TRUE(IsPrime(23));
} }
} // namespace
// Step 3. Call RUN_ALL_TESTS() in main(). // Step 3. Call RUN_ALL_TESTS() in main().
// //
......
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include "sample2.h" #include "sample2.h"
...@@ -37,7 +35,7 @@ ...@@ -37,7 +35,7 @@
// Clones a 0-terminated C string, allocating memory using new. // Clones a 0-terminated C string, allocating memory using new.
const char* MyString::CloneCString(const char* a_c_string) { const char* MyString::CloneCString(const char* a_c_string) {
if (a_c_string == NULL) return NULL; if (a_c_string == nullptr) return nullptr;
const size_t len = strlen(a_c_string); const size_t len = strlen(a_c_string);
char* const clone = new char[ len + 1 ]; char* const clone = new char[ len + 1 ];
......
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE2_H_ #ifndef GTEST_SAMPLES_SAMPLE2_H_
#define GTEST_SAMPLES_SAMPLE2_H_ #define GTEST_SAMPLES_SAMPLE2_H_
...@@ -52,15 +50,15 @@ class MyString { ...@@ -52,15 +50,15 @@ class MyString {
// C'tors // C'tors
// The default c'tor constructs a NULL string. // The default c'tor constructs a NULL string.
MyString() : c_string_(NULL) {} MyString() : c_string_(nullptr) {}
// Constructs a MyString by cloning a 0-terminated C string. // Constructs a MyString by cloning a 0-terminated C string.
explicit MyString(const char* a_c_string) : c_string_(NULL) { explicit MyString(const char* a_c_string) : c_string_(nullptr) {
Set(a_c_string); Set(a_c_string);
} }
// Copy c'tor // Copy c'tor
MyString(const MyString& string) : c_string_(NULL) { MyString(const MyString& string) : c_string_(nullptr) {
Set(string.c_string_); Set(string.c_string_);
} }
...@@ -73,9 +71,7 @@ class MyString { ...@@ -73,9 +71,7 @@ class MyString {
// Gets the 0-terminated C string this MyString object represents. // Gets the 0-terminated C string this MyString object represents.
const char* c_string() const { return c_string_; } const char* c_string() const { return c_string_; }
size_t Length() const { size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); }
return c_string_ == NULL ? 0 : strlen(c_string_);
}
// Sets the 0-terminated C string this MyString object represents. // Sets the 0-terminated C string this MyString object represents.
void Set(const char* c_string); void Set(const char* c_string);
......
...@@ -28,9 +28,6 @@ ...@@ -28,9 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// This sample shows how to write a more complex unit test for a class // This sample shows how to write a more complex unit test for a class
// that has multiple member functions. // that has multiple member functions.
...@@ -42,7 +39,7 @@ ...@@ -42,7 +39,7 @@
#include "sample2.h" #include "sample2.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace {
// In this example, we test the MyString class (a simple string). // In this example, we test the MyString class (a simple string).
// Tests the default c'tor. // Tests the default c'tor.
...@@ -69,7 +66,7 @@ TEST(MyString, DefaultConstructor) { ...@@ -69,7 +66,7 @@ TEST(MyString, DefaultConstructor) {
// we have to live with this fact. // we have to live with this fact.
// //
// </TechnicalDetails> // </TechnicalDetails>
EXPECT_STREQ(NULL, s.c_string()); EXPECT_STREQ(nullptr, s.c_string());
EXPECT_EQ(0u, s.Length()); EXPECT_EQ(0u, s.Length());
} }
...@@ -104,6 +101,7 @@ TEST(MyString, Set) { ...@@ -104,6 +101,7 @@ TEST(MyString, Set) {
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
// Can we set the MyString to NULL? // Can we set the MyString to NULL?
s.Set(NULL); s.Set(nullptr);
EXPECT_STREQ(NULL, s.c_string()); EXPECT_STREQ(nullptr, s.c_string());
} }
} // namespace
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_ #ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
#define GTEST_SAMPLES_SAMPLE3_INL_H_ #define GTEST_SAMPLES_SAMPLE3_INL_H_
...@@ -60,7 +58,8 @@ class QueueNode { ...@@ -60,7 +58,8 @@ class QueueNode {
private: private:
// Creates a node with a given element value. The next pointer is // Creates a node with a given element value. The next pointer is
// set to NULL. // set to NULL.
explicit QueueNode(const E& an_element) : element_(an_element), next_(NULL) {} explicit QueueNode(const E& an_element)
: element_(an_element), next_(nullptr) {}
// We disable the default assignment operator and copy c'tor. // We disable the default assignment operator and copy c'tor.
const QueueNode& operator = (const QueueNode&); const QueueNode& operator = (const QueueNode&);
...@@ -74,7 +73,7 @@ template <typename E> // E is the element type. ...@@ -74,7 +73,7 @@ template <typename E> // E is the element type.
class Queue { class Queue {
public: public:
// Creates an empty queue. // Creates an empty queue.
Queue() : head_(NULL), last_(NULL), size_(0) {} Queue() : head_(nullptr), last_(nullptr), size_(0) {}
// D'tor. Clears the queue. // D'tor. Clears the queue.
~Queue() { Clear(); } ~Queue() { Clear(); }
...@@ -88,12 +87,12 @@ class Queue { ...@@ -88,12 +87,12 @@ class Queue {
for (; ;) { for (; ;) {
delete node; delete node;
node = next; node = next;
if (node == NULL) break; if (node == nullptr) break;
next = node->next(); next = node->next();
} }
// 2. Resets the member variables. // 2. Resets the member variables.
head_ = last_ = NULL; head_ = last_ = nullptr;
size_ = 0; size_ = 0;
} }
} }
...@@ -130,14 +129,14 @@ class Queue { ...@@ -130,14 +129,14 @@ class Queue {
// the queue is empty. // the queue is empty.
E* Dequeue() { E* Dequeue() {
if (size_ == 0) { if (size_ == 0) {
return NULL; return nullptr;
} }
const QueueNode<E>* const old_head = head_; const QueueNode<E>* const old_head = head_;
head_ = head_->next_; head_ = head_->next_;
size_--; size_--;
if (size_ == 0) { if (size_ == 0) {
last_ = NULL; last_ = nullptr;
} }
E* element = new E(old_head->element()); E* element = new E(old_head->element());
...@@ -152,7 +151,8 @@ class Queue { ...@@ -152,7 +151,8 @@ class Queue {
template <typename F> template <typename F>
Queue* Map(F function) const { Queue* Map(F function) const {
Queue* new_queue = new Queue(); Queue* new_queue = new Queue();
for (const QueueNode<E>* node = head_; node != NULL; node = node->next_) { for (const QueueNode<E>* node = head_; node != nullptr;
node = node->next_) {
new_queue->Enqueue(function(node->element())); new_queue->Enqueue(function(node->element()));
} }
......
...@@ -28,9 +28,6 @@ ...@@ -28,9 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// In this example, we use a more advanced feature of Google Test called // In this example, we use a more advanced feature of Google Test called
// test fixture. // test fixture.
...@@ -65,16 +62,16 @@ ...@@ -65,16 +62,16 @@
#include "sample3-inl.h" #include "sample3-inl.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace {
// To use a test fixture, derive a class from testing::Test. // To use a test fixture, derive a class from testing::Test.
class QueueTest : public testing::Test { class QueueTestSmpl3 : public testing::Test {
protected: // You should make the members protected s.t. they can be protected: // You should make the members protected s.t. they can be
// accessed from sub-classes. // accessed from sub-classes.
// virtual void SetUp() will be called before each test is run. You // virtual void SetUp() will be called before each test is run. You
// should define it if you need to initialize the varaibles. // should define it if you need to initialize the variables.
// Otherwise, this can be skipped. // Otherwise, this can be skipped.
virtual void SetUp() { void SetUp() override {
q1_.Enqueue(1); q1_.Enqueue(1);
q2_.Enqueue(2); q2_.Enqueue(2);
q2_.Enqueue(3); q2_.Enqueue(3);
...@@ -102,8 +99,8 @@ class QueueTest : public testing::Test { ...@@ -102,8 +99,8 @@ class QueueTest : public testing::Test {
ASSERT_EQ(q->Size(), new_q->Size()); ASSERT_EQ(q->Size(), new_q->Size());
// Verifies the relationship between the elements of the two queues. // Verifies the relationship between the elements of the two queues.
for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head(); for (const QueueNode<int>*n1 = q->Head(), *n2 = new_q->Head();
n1 != NULL; n1 = n1->next(), n2 = n2->next() ) { n1 != nullptr; n1 = n1->next(), n2 = n2->next()) {
EXPECT_EQ(2 * n1->element(), n2->element()); EXPECT_EQ(2 * n1->element(), n2->element());
} }
...@@ -120,32 +117,33 @@ class QueueTest : public testing::Test { ...@@ -120,32 +117,33 @@ class QueueTest : public testing::Test {
// instead of TEST. // instead of TEST.
// Tests the default c'tor. // Tests the default c'tor.
TEST_F(QueueTest, DefaultConstructor) { TEST_F(QueueTestSmpl3, DefaultConstructor) {
// You can access data in the test fixture here. // You can access data in the test fixture here.
EXPECT_EQ(0u, q0_.Size()); EXPECT_EQ(0u, q0_.Size());
} }
// Tests Dequeue(). // Tests Dequeue().
TEST_F(QueueTest, Dequeue) { TEST_F(QueueTestSmpl3, Dequeue) {
int * n = q0_.Dequeue(); int * n = q0_.Dequeue();
EXPECT_TRUE(n == NULL); EXPECT_TRUE(n == nullptr);
n = q1_.Dequeue(); n = q1_.Dequeue();
ASSERT_TRUE(n != NULL); ASSERT_TRUE(n != nullptr);
EXPECT_EQ(1, *n); EXPECT_EQ(1, *n);
EXPECT_EQ(0u, q1_.Size()); EXPECT_EQ(0u, q1_.Size());
delete n; delete n;
n = q2_.Dequeue(); n = q2_.Dequeue();
ASSERT_TRUE(n != NULL); ASSERT_TRUE(n != nullptr);
EXPECT_EQ(2, *n); EXPECT_EQ(2, *n);
EXPECT_EQ(1u, q2_.Size()); EXPECT_EQ(1u, q2_.Size());
delete n; delete n;
} }
// Tests the Queue::Map() function. // Tests the Queue::Map() function.
TEST_F(QueueTest, Map) { TEST_F(QueueTestSmpl3, Map) {
MapTester(&q0_); MapTester(&q0_);
MapTester(&q1_); MapTester(&q1_);
MapTester(&q2_); MapTester(&q2_);
} }
} // namespace
...@@ -28,8 +28,6 @@ ...@@ -28,8 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include <stdio.h> #include <stdio.h>
...@@ -40,6 +38,16 @@ int Counter::Increment() { ...@@ -40,6 +38,16 @@ int Counter::Increment() {
return counter_++; return counter_++;
} }
// Returns the current counter value, and decrements it.
// counter can not be less than 0, return 0 in this case
int Counter::Decrement() {
if (counter_ == 0) {
return counter_;
} else {
return counter_--;
}
}
// Prints the current counter value to STDOUT. // Prints the current counter value to STDOUT.
void Counter::Print() const { void Counter::Print() const {
printf("%d", counter_); printf("%d", counter_);
......
...@@ -28,9 +28,6 @@ ...@@ -28,9 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE4_H_ #ifndef GTEST_SAMPLES_SAMPLE4_H_
#define GTEST_SAMPLES_SAMPLE4_H_ #define GTEST_SAMPLES_SAMPLE4_H_
...@@ -46,6 +43,9 @@ class Counter { ...@@ -46,6 +43,9 @@ class Counter {
// Returns the current counter value, and increments it. // Returns the current counter value, and increments it.
int Increment(); int Increment();
// Returns the current counter value, and decrements it.
int Decrement();
// Prints the current counter value to STDOUT. // Prints the current counter value to STDOUT.
void Print() const; void Print() const;
}; };
......
...@@ -26,20 +26,28 @@ ...@@ -26,20 +26,28 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include "gtest/gtest.h"
#include "sample4.h" #include "sample4.h"
#include "gtest/gtest.h"
namespace {
// Tests the Increment() method. // Tests the Increment() method.
TEST(Counter, Increment) { TEST(Counter, Increment) {
Counter c; Counter c;
// Test that counter 0 returns 0
EXPECT_EQ(0, c.Decrement());
// EXPECT_EQ() evaluates its arguments exactly once, so they // EXPECT_EQ() evaluates its arguments exactly once, so they
// can have side effects. // can have side effects.
EXPECT_EQ(0, c.Increment()); EXPECT_EQ(0, c.Increment());
EXPECT_EQ(1, c.Increment()); EXPECT_EQ(1, c.Increment());
EXPECT_EQ(2, c.Increment()); EXPECT_EQ(2, c.Increment());
EXPECT_EQ(3, c.Decrement());
} }
} // namespace
...@@ -26,8 +26,7 @@ ...@@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// This sample teaches how to reuse a test fixture in multiple test // This sample teaches how to reuse a test fixture in multiple test
// cases by deriving sub-fixtures from it. // cases by deriving sub-fixtures from it.
...@@ -46,10 +45,10 @@ ...@@ -46,10 +45,10 @@
#include <limits.h> #include <limits.h>
#include <time.h> #include <time.h>
#include "sample3-inl.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "sample1.h" #include "sample1.h"
#include "sample3-inl.h"
namespace {
// In this sample, we want to ensure that every test finishes within // In this sample, we want to ensure that every test finishes within
// ~5 seconds. If a test takes longer to run, we consider it a // ~5 seconds. If a test takes longer to run, we consider it a
// failure. // failure.
...@@ -64,15 +63,13 @@ class QuickTest : public testing::Test { ...@@ -64,15 +63,13 @@ class QuickTest : public testing::Test {
protected: protected:
// Remember that SetUp() is run immediately before a test starts. // Remember that SetUp() is run immediately before a test starts.
// This is a good place to record the start time. // This is a good place to record the start time.
virtual void SetUp() { void SetUp() override { start_time_ = time(nullptr); }
start_time_ = time(NULL);
}
// TearDown() is invoked immediately after a test finishes. Here we // TearDown() is invoked immediately after a test finishes. Here we
// check if the test was too slow. // check if the test was too slow.
virtual void TearDown() { void TearDown() override {
// Gets the time when the test finishes // Gets the time when the test finishes
const time_t end_time = time(NULL); const time_t end_time = time(nullptr);
// Asserts that the test took no more than ~5 seconds. Did you // Asserts that the test took no more than ~5 seconds. Did you
// know that you can use assertions in SetUp() and TearDown() as // know that you can use assertions in SetUp() and TearDown() as
...@@ -143,7 +140,7 @@ TEST_F(IntegerFunctionTest, IsPrime) { ...@@ -143,7 +140,7 @@ TEST_F(IntegerFunctionTest, IsPrime) {
// stuff inside the body of the test fixture, as usual. // stuff inside the body of the test fixture, as usual.
class QueueTest : public QuickTest { class QueueTest : public QuickTest {
protected: protected:
virtual void SetUp() { void SetUp() override {
// First, we need to set up the super fixture (QuickTest). // First, we need to set up the super fixture (QuickTest).
QuickTest::SetUp(); QuickTest::SetUp();
...@@ -177,21 +174,21 @@ TEST_F(QueueTest, DefaultConstructor) { ...@@ -177,21 +174,21 @@ TEST_F(QueueTest, DefaultConstructor) {
// Tests Dequeue(). // Tests Dequeue().
TEST_F(QueueTest, Dequeue) { TEST_F(QueueTest, Dequeue) {
int* n = q0_.Dequeue(); int* n = q0_.Dequeue();
EXPECT_TRUE(n == NULL); EXPECT_TRUE(n == nullptr);
n = q1_.Dequeue(); n = q1_.Dequeue();
EXPECT_TRUE(n != NULL); EXPECT_TRUE(n != nullptr);
EXPECT_EQ(1, *n); EXPECT_EQ(1, *n);
EXPECT_EQ(0u, q1_.Size()); EXPECT_EQ(0u, q1_.Size());
delete n; delete n;
n = q2_.Dequeue(); n = q2_.Dequeue();
EXPECT_TRUE(n != NULL); EXPECT_TRUE(n != nullptr);
EXPECT_EQ(2, *n); EXPECT_EQ(2, *n);
EXPECT_EQ(1u, q2_.Size()); EXPECT_EQ(1u, q2_.Size());
delete n; delete n;
} }
} // namespace
// If necessary, you can derive further test fixtures from a derived // If necessary, you can derive further test fixtures from a derived
// fixture itself. For example, you can derive another fixture from // fixture itself. For example, you can derive another fixture from
// QueueTest. Google Test imposes no limit on how deep the hierarchy // QueueTest. Google Test imposes no limit on how deep the hierarchy
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment