Path: blob/master/dep/googletest/include/gtest/internal/gtest-param-util.h
4808 views
// Copyright 2008 Google Inc.1// All Rights Reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Type and function utilities for implementing parameterized tests.3031// IWYU pragma: private, include "gtest/gtest.h"32// IWYU pragma: friend gtest/.*33// IWYU pragma: friend gmock/.*3435#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_36#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_3738#include <ctype.h>3940#include <cassert>41#include <functional>42#include <iterator>43#include <map>44#include <memory>45#include <ostream>46#include <set>47#include <string>48#include <tuple>49#include <type_traits>50#include <unordered_map>51#include <utility>52#include <vector>5354#include "gtest/gtest-printers.h"55#include "gtest/gtest-test-part.h"56#include "gtest/internal/gtest-internal.h"57#include "gtest/internal/gtest-port.h"5859namespace testing {60// Input to a parameterized test name generator, describing a test parameter.61// Consists of the parameter value and the integer parameter index.62template <class ParamType>63struct TestParamInfo {64TestParamInfo(const ParamType& a_param, size_t an_index)65: param(a_param), index(an_index) {}66ParamType param;67size_t index;68};6970// A builtin parameterized test name generator which returns the result of71// testing::PrintToString.72struct PrintToStringParamName {73template <class ParamType>74std::string operator()(const TestParamInfo<ParamType>& info) const {75return PrintToString(info.param);76}77};7879namespace internal {8081// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.82// Utility Functions8384// Outputs a message explaining invalid registration of different85// fixture class for the same test suite. This may happen when86// TEST_P macro is used to define two tests with the same name87// but in different namespaces.88GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,89const CodeLocation& code_location);9091template <typename>92class ParamGeneratorInterface;93template <typename>94class ParamGenerator;9596// Interface for iterating over elements provided by an implementation97// of ParamGeneratorInterface<T>.98template <typename T>99class ParamIteratorInterface {100public:101virtual ~ParamIteratorInterface() = default;102// A pointer to the base generator instance.103// Used only for the purposes of iterator comparison104// to make sure that two iterators belong to the same generator.105virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;106// Advances iterator to point to the next element107// provided by the generator. The caller is responsible108// for not calling Advance() on an iterator equal to109// BaseGenerator()->End().110virtual void Advance() = 0;111// Clones the iterator object. Used for implementing copy semantics112// of ParamIterator<T>.113virtual ParamIteratorInterface* Clone() const = 0;114// Dereferences the current iterator and provides (read-only) access115// to the pointed value. It is the caller's responsibility not to call116// Current() on an iterator equal to BaseGenerator()->End().117// Used for implementing ParamGenerator<T>::operator*().118virtual const T* Current() const = 0;119// Determines whether the given iterator and other point to the same120// element in the sequence generated by the generator.121// Used for implementing ParamGenerator<T>::operator==().122virtual bool Equals(const ParamIteratorInterface& other) const = 0;123};124125// Class iterating over elements provided by an implementation of126// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>127// and implements the const forward iterator concept.128template <typename T>129class ParamIterator {130public:131typedef T value_type;132typedef const T& reference;133typedef ptrdiff_t difference_type;134135// ParamIterator assumes ownership of the impl_ pointer.136ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}137ParamIterator& operator=(const ParamIterator& other) {138if (this != &other) impl_.reset(other.impl_->Clone());139return *this;140}141142const T& operator*() const { return *impl_->Current(); }143const T* operator->() const { return impl_->Current(); }144// Prefix version of operator++.145ParamIterator& operator++() {146impl_->Advance();147return *this;148}149// Postfix version of operator++.150ParamIterator operator++(int /*unused*/) {151ParamIteratorInterface<T>* clone = impl_->Clone();152impl_->Advance();153return ParamIterator(clone);154}155bool operator==(const ParamIterator& other) const {156return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);157}158bool operator!=(const ParamIterator& other) const {159return !(*this == other);160}161162private:163friend class ParamGenerator<T>;164explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}165std::unique_ptr<ParamIteratorInterface<T>> impl_;166};167168// ParamGeneratorInterface<T> is the binary interface to access generators169// defined in other translation units.170template <typename T>171class ParamGeneratorInterface {172public:173typedef T ParamType;174175virtual ~ParamGeneratorInterface() = default;176177// Generator interface definition178virtual ParamIteratorInterface<T>* Begin() const = 0;179virtual ParamIteratorInterface<T>* End() const = 0;180};181182// Wraps ParamGeneratorInterface<T> and provides general generator syntax183// compatible with the STL Container concept.184// This class implements copy initialization semantics and the contained185// ParamGeneratorInterface<T> instance is shared among all copies186// of the original object. This is possible because that instance is immutable.187template <typename T>188class ParamGenerator {189public:190typedef ParamIterator<T> iterator;191192explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}193ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}194195ParamGenerator& operator=(const ParamGenerator& other) {196impl_ = other.impl_;197return *this;198}199200iterator begin() const { return iterator(impl_->Begin()); }201iterator end() const { return iterator(impl_->End()); }202203private:204std::shared_ptr<const ParamGeneratorInterface<T>> impl_;205};206207// Generates values from a range of two comparable values. Can be used to208// generate sequences of user-defined types that implement operator+() and209// operator<().210// This class is used in the Range() function.211template <typename T, typename IncrementT>212class RangeGenerator : public ParamGeneratorInterface<T> {213public:214RangeGenerator(T begin, T end, IncrementT step)215: begin_(begin),216end_(end),217step_(step),218end_index_(CalculateEndIndex(begin, end, step)) {}219~RangeGenerator() override = default;220221ParamIteratorInterface<T>* Begin() const override {222return new Iterator(this, begin_, 0, step_);223}224ParamIteratorInterface<T>* End() const override {225return new Iterator(this, end_, end_index_, step_);226}227228private:229class Iterator : public ParamIteratorInterface<T> {230public:231Iterator(const ParamGeneratorInterface<T>* base, T value, int index,232IncrementT step)233: base_(base), value_(value), index_(index), step_(step) {}234~Iterator() override = default;235236const ParamGeneratorInterface<T>* BaseGenerator() const override {237return base_;238}239void Advance() override {240value_ = static_cast<T>(value_ + step_);241index_++;242}243ParamIteratorInterface<T>* Clone() const override {244return new Iterator(*this);245}246const T* Current() const override { return &value_; }247bool Equals(const ParamIteratorInterface<T>& other) const override {248// Having the same base generator guarantees that the other249// iterator is of the same type and we can downcast.250GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())251<< "The program attempted to compare iterators "252<< "from different generators." << std::endl;253const int other_index =254CheckedDowncastToActualType<const Iterator>(&other)->index_;255return index_ == other_index;256}257258private:259Iterator(const Iterator& other)260: ParamIteratorInterface<T>(),261base_(other.base_),262value_(other.value_),263index_(other.index_),264step_(other.step_) {}265266// No implementation - assignment is unsupported.267void operator=(const Iterator& other);268269const ParamGeneratorInterface<T>* const base_;270T value_;271int index_;272const IncrementT step_;273}; // class RangeGenerator::Iterator274275static int CalculateEndIndex(const T& begin, const T& end,276const IncrementT& step) {277int end_index = 0;278for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++;279return end_index;280}281282// No implementation - assignment is unsupported.283void operator=(const RangeGenerator& other);284285const T begin_;286const T end_;287const IncrementT step_;288// The index for the end() iterator. All the elements in the generated289// sequence are indexed (0-based) to aid iterator comparison.290const int end_index_;291}; // class RangeGenerator292293// Generates values from a pair of STL-style iterators. Used in the294// ValuesIn() function. The elements are copied from the source range295// since the source can be located on the stack, and the generator296// is likely to persist beyond that stack frame.297template <typename T>298class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {299public:300template <typename ForwardIterator>301ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)302: container_(begin, end) {}303~ValuesInIteratorRangeGenerator() override = default;304305ParamIteratorInterface<T>* Begin() const override {306return new Iterator(this, container_.begin());307}308ParamIteratorInterface<T>* End() const override {309return new Iterator(this, container_.end());310}311312private:313typedef typename ::std::vector<T> ContainerType;314315class Iterator : public ParamIteratorInterface<T> {316public:317Iterator(const ParamGeneratorInterface<T>* base,318typename ContainerType::const_iterator iterator)319: base_(base), iterator_(iterator) {}320~Iterator() override = default;321322const ParamGeneratorInterface<T>* BaseGenerator() const override {323return base_;324}325void Advance() override {326++iterator_;327value_.reset();328}329ParamIteratorInterface<T>* Clone() const override {330return new Iterator(*this);331}332// We need to use cached value referenced by iterator_ because *iterator_333// can return a temporary object (and of type other then T), so just334// having "return &*iterator_;" doesn't work.335// value_ is updated here and not in Advance() because Advance()336// can advance iterator_ beyond the end of the range, and we cannot337// detect that fact. The client code, on the other hand, is338// responsible for not calling Current() on an out-of-range iterator.339const T* Current() const override {340if (value_.get() == nullptr) value_.reset(new T(*iterator_));341return value_.get();342}343bool Equals(const ParamIteratorInterface<T>& other) const override {344// Having the same base generator guarantees that the other345// iterator is of the same type and we can downcast.346GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())347<< "The program attempted to compare iterators "348<< "from different generators." << std::endl;349return iterator_ ==350CheckedDowncastToActualType<const Iterator>(&other)->iterator_;351}352353private:354Iterator(const Iterator& other)355// The explicit constructor call suppresses a false warning356// emitted by gcc when supplied with the -Wextra option.357: ParamIteratorInterface<T>(),358base_(other.base_),359iterator_(other.iterator_) {}360361const ParamGeneratorInterface<T>* const base_;362typename ContainerType::const_iterator iterator_;363// A cached value of *iterator_. We keep it here to allow access by364// pointer in the wrapping iterator's operator->().365// value_ needs to be mutable to be accessed in Current().366// Use of std::unique_ptr helps manage cached value's lifetime,367// which is bound by the lifespan of the iterator itself.368mutable std::unique_ptr<const T> value_;369}; // class ValuesInIteratorRangeGenerator::Iterator370371// No implementation - assignment is unsupported.372void operator=(const ValuesInIteratorRangeGenerator& other);373374const ContainerType container_;375}; // class ValuesInIteratorRangeGenerator376377// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.378//379// Default parameterized test name generator, returns a string containing the380// integer test parameter index.381template <class ParamType>382std::string DefaultParamName(const TestParamInfo<ParamType>& info) {383return std::to_string(info.index);384}385386template <typename T = int>387void TestNotEmpty() {388static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");389}390template <typename T = int>391void TestNotEmpty(const T&) {}392393// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.394//395// Stores a parameter value and later creates tests parameterized with that396// value.397template <class TestClass>398class ParameterizedTestFactory : public TestFactoryBase {399public:400typedef typename TestClass::ParamType ParamType;401explicit ParameterizedTestFactory(ParamType parameter)402: parameter_(parameter) {}403Test* CreateTest() override {404TestClass::SetParam(¶meter_);405return new TestClass();406}407408private:409const ParamType parameter_;410411ParameterizedTestFactory(const ParameterizedTestFactory&) = delete;412ParameterizedTestFactory& operator=(const ParameterizedTestFactory&) = delete;413};414415// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.416//417// TestMetaFactoryBase is a base class for meta-factories that create418// test factories for passing into MakeAndRegisterTestInfo function.419template <class ParamType>420class TestMetaFactoryBase {421public:422virtual ~TestMetaFactoryBase() = default;423424virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;425};426427// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.428//429// TestMetaFactory creates test factories for passing into430// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives431// ownership of test factory pointer, same factory object cannot be passed432// into that method twice. But ParameterizedTestSuiteInfo is going to call433// it for each Test/Parameter value combination. Thus it needs meta factory434// creator class.435template <class TestSuite>436class TestMetaFactory437: public TestMetaFactoryBase<typename TestSuite::ParamType> {438public:439using ParamType = typename TestSuite::ParamType;440441TestMetaFactory() = default;442443TestFactoryBase* CreateTestFactory(ParamType parameter) override {444return new ParameterizedTestFactory<TestSuite>(parameter);445}446447private:448TestMetaFactory(const TestMetaFactory&) = delete;449TestMetaFactory& operator=(const TestMetaFactory&) = delete;450};451452// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.453//454// ParameterizedTestSuiteInfoBase is a generic interface455// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase456// accumulates test information provided by TEST_P macro invocations457// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations458// and uses that information to register all resulting test instances459// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds460// a collection of pointers to the ParameterizedTestSuiteInfo objects461// and calls RegisterTests() on each of them when asked.462class ParameterizedTestSuiteInfoBase {463public:464virtual ~ParameterizedTestSuiteInfoBase() = default;465466// Base part of test suite name for display purposes.467virtual const std::string& GetTestSuiteName() const = 0;468// Test suite id to verify identity.469virtual TypeId GetTestSuiteTypeId() const = 0;470// UnitTest class invokes this method to register tests in this471// test suite right before running them in RUN_ALL_TESTS macro.472// This method should not be called more than once on any single473// instance of a ParameterizedTestSuiteInfoBase derived class.474virtual void RegisterTests() = 0;475476protected:477ParameterizedTestSuiteInfoBase() {}478479private:480ParameterizedTestSuiteInfoBase(const ParameterizedTestSuiteInfoBase&) =481delete;482ParameterizedTestSuiteInfoBase& operator=(483const ParameterizedTestSuiteInfoBase&) = delete;484};485486// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.487//488// Report a the name of a test_suit as safe to ignore489// as the side effect of construction of this type.490struct GTEST_API_ MarkAsIgnored {491explicit MarkAsIgnored(const char* test_suite);492};493494GTEST_API_ void InsertSyntheticTestCase(const std::string& name,495CodeLocation location, bool has_test_p);496497// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.498//499// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P500// macro invocations for a particular test suite and generators501// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that502// test suite. It registers tests with all values generated by all503// generators when asked.504template <class TestSuite>505class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {506public:507// ParamType and GeneratorCreationFunc are private types but are required508// for declarations of public methods AddTestPattern() and509// AddTestSuiteInstantiation().510using ParamType = typename TestSuite::ParamType;511// A function that returns an instance of appropriate generator type.512typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();513using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);514515explicit ParameterizedTestSuiteInfo(std::string name,516CodeLocation code_location)517: test_suite_name_(std::move(name)),518code_location_(std::move(code_location)) {}519520// Test suite base name for display purposes.521const std::string& GetTestSuiteName() const override {522return test_suite_name_;523}524// Test suite id to verify identity.525TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }526// TEST_P macro uses AddTestPattern() to record information527// about a single test in a LocalTestInfo structure.528// test_suite_name is the base name of the test suite (without invocation529// prefix). test_base_name is the name of an individual test without530// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is531// test suite base name and DoBar is test base name.532void AddTestPattern(const char*, const char* test_base_name,533TestMetaFactoryBase<ParamType>* meta_factory,534CodeLocation code_location) {535tests_.emplace_back(536new TestInfo(test_base_name, meta_factory, std::move(code_location)));537}538// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information539// about a generator.540int AddTestSuiteInstantiation(std::string instantiation_name,541GeneratorCreationFunc* func,542ParamNameGeneratorFunc* name_func,543const char* file, int line) {544instantiations_.emplace_back(std::move(instantiation_name), func, name_func,545file, line);546return 0; // Return value used only to run this method in namespace scope.547}548// UnitTest class invokes this method to register tests in this test suite549// right before running tests in RUN_ALL_TESTS macro.550// This method should not be called more than once on any single551// instance of a ParameterizedTestSuiteInfoBase derived class.552// UnitTest has a guard to prevent from calling this method more than once.553void RegisterTests() override {554bool generated_instantiations = false;555556std::string test_suite_name;557std::string test_name;558for (const std::shared_ptr<TestInfo>& test_info : tests_) {559for (const InstantiationInfo& instantiation : instantiations_) {560const std::string& instantiation_name = instantiation.name;561ParamGenerator<ParamType> generator((*instantiation.generator)());562ParamNameGeneratorFunc* name_func = instantiation.name_func;563const char* file = instantiation.file;564int line = instantiation.line;565566if (!instantiation_name.empty())567test_suite_name = instantiation_name + "/";568else569test_suite_name.clear();570test_suite_name += test_suite_name_;571572size_t i = 0;573std::set<std::string> test_param_names;574for (const auto& param : generator) {575generated_instantiations = true;576577test_name.clear();578579std::string param_name =580name_func(TestParamInfo<ParamType>(param, i));581582GTEST_CHECK_(IsValidParamName(param_name))583<< "Parameterized test name '" << param_name584<< "' is invalid (contains spaces, dashes, or any "585"non-alphanumeric characters other than underscores), in "586<< file << " line " << line << "" << std::endl;587588GTEST_CHECK_(test_param_names.count(param_name) == 0)589<< "Duplicate parameterized test name '" << param_name << "', in "590<< file << " line " << line << std::endl;591592if (!test_info->test_base_name.empty()) {593test_name.append(test_info->test_base_name).append("/");594}595test_name += param_name;596597test_param_names.insert(std::move(param_name));598599MakeAndRegisterTestInfo(600test_suite_name, test_name.c_str(),601nullptr, // No type parameter.602PrintToString(param).c_str(), test_info->code_location,603GetTestSuiteTypeId(),604SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),605SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),606test_info->test_meta_factory->CreateTestFactory(param));607++i;608} // for param609} // for instantiation610} // for test_info611612if (!generated_instantiations) {613// There are no generaotrs, or they all generate nothing ...614InsertSyntheticTestCase(GetTestSuiteName(), code_location_,615!tests_.empty());616}617} // RegisterTests618619private:620// LocalTestInfo structure keeps information about a single test registered621// with TEST_P macro.622struct TestInfo {623TestInfo(const char* a_test_base_name,624TestMetaFactoryBase<ParamType>* a_test_meta_factory,625CodeLocation a_code_location)626: test_base_name(a_test_base_name),627test_meta_factory(a_test_meta_factory),628code_location(std::move(a_code_location)) {}629630const std::string test_base_name;631const std::unique_ptr<TestMetaFactoryBase<ParamType>> test_meta_factory;632const CodeLocation code_location;633};634using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo>>;635// Records data received from INSTANTIATE_TEST_SUITE_P macros:636// <Instantiation name, Sequence generator creation function,637// Name generator function, Source file, Source line>638struct InstantiationInfo {639InstantiationInfo(std::string name_in, GeneratorCreationFunc* generator_in,640ParamNameGeneratorFunc* name_func_in, const char* file_in,641int line_in)642: name(std::move(name_in)),643generator(generator_in),644name_func(name_func_in),645file(file_in),646line(line_in) {}647648std::string name;649GeneratorCreationFunc* generator;650ParamNameGeneratorFunc* name_func;651const char* file;652int line;653};654typedef ::std::vector<InstantiationInfo> InstantiationContainer;655656static bool IsValidParamName(const std::string& name) {657// Check for empty string658if (name.empty()) return false;659660// Check for invalid characters661for (std::string::size_type index = 0; index < name.size(); ++index) {662if (!IsAlNum(name[index]) && name[index] != '_') return false;663}664665return true;666}667668const std::string test_suite_name_;669CodeLocation code_location_;670TestInfoContainer tests_;671InstantiationContainer instantiations_;672673ParameterizedTestSuiteInfo(const ParameterizedTestSuiteInfo&) = delete;674ParameterizedTestSuiteInfo& operator=(const ParameterizedTestSuiteInfo&) =675delete;676}; // class ParameterizedTestSuiteInfo677678// Legacy API is deprecated but still available679#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_680template <class TestCase>681using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;682#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_683684// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.685//686// ParameterizedTestSuiteRegistry contains a map of687// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P688// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding689// ParameterizedTestSuiteInfo descriptors.690class ParameterizedTestSuiteRegistry {691public:692ParameterizedTestSuiteRegistry() = default;693~ParameterizedTestSuiteRegistry() {694for (auto& test_suite_info : test_suite_infos_) {695delete test_suite_info;696}697}698699// Looks up or creates and returns a structure containing information about700// tests and instantiations of a particular test suite.701template <class TestSuite>702ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(703std::string test_suite_name, CodeLocation code_location) {704ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;705706auto item_it = suite_name_to_info_index_.find(test_suite_name);707if (item_it != suite_name_to_info_index_.end()) {708auto* test_suite_info = test_suite_infos_[item_it->second];709if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {710// Complain about incorrect usage of Google Test facilities711// and terminate the program since we cannot guaranty correct712// test suite setup and tear-down in this case.713ReportInvalidTestSuiteType(test_suite_name.c_str(), code_location);714posix::Abort();715} else {716// At this point we are sure that the object we found is of the same717// type we are looking for, so we downcast it to that type718// without further checks.719typed_test_info =720CheckedDowncastToActualType<ParameterizedTestSuiteInfo<TestSuite>>(721test_suite_info);722}723}724if (typed_test_info == nullptr) {725typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(726test_suite_name, std::move(code_location));727suite_name_to_info_index_.emplace(std::move(test_suite_name),728test_suite_infos_.size());729test_suite_infos_.push_back(typed_test_info);730}731return typed_test_info;732}733void RegisterTests() {734for (auto& test_suite_info : test_suite_infos_) {735test_suite_info->RegisterTests();736}737}738// Legacy API is deprecated but still available739#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_740template <class TestCase>741ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(742std::string test_case_name, CodeLocation code_location) {743return GetTestSuitePatternHolder<TestCase>(std::move(test_case_name),744std::move(code_location));745}746747#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_748749private:750using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;751752TestSuiteInfoContainer test_suite_infos_;753::std::unordered_map<std::string, size_t> suite_name_to_info_index_;754755ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) =756delete;757ParameterizedTestSuiteRegistry& operator=(758const ParameterizedTestSuiteRegistry&) = delete;759};760761// Keep track of what type-parameterized test suite are defined and762// where as well as which are intatiated. This allows susequently763// identifying suits that are defined but never used.764class TypeParameterizedTestSuiteRegistry {765public:766// Add a suite definition767void RegisterTestSuite(const char* test_suite_name,768CodeLocation code_location);769770// Add an instantiation of a suit.771void RegisterInstantiation(const char* test_suite_name);772773// For each suit repored as defined but not reported as instantiation,774// emit a test that reports that fact (configurably, as an error).775void CheckForInstantiations();776777private:778struct TypeParameterizedTestSuiteInfo {779explicit TypeParameterizedTestSuiteInfo(CodeLocation c)780: code_location(std::move(c)), instantiated(false) {}781782CodeLocation code_location;783bool instantiated;784};785786std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;787};788789} // namespace internal790791// Forward declarations of ValuesIn(), which is implemented in792// include/gtest/gtest-param-test.h.793template <class Container>794internal::ParamGenerator<typename Container::value_type> ValuesIn(795const Container& container);796797namespace internal {798// Used in the Values() function to provide polymorphic capabilities.799800GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)801802template <typename... Ts>803class ValueArray {804public:805explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}806807template <typename T>808operator ParamGenerator<T>() const { // NOLINT809return ValuesIn(MakeVector<T>(std::make_index_sequence<sizeof...(Ts)>()));810}811812private:813template <typename T, size_t... I>814std::vector<T> MakeVector(std::index_sequence<I...>) const {815return std::vector<T>{static_cast<T>(v_.template Get<I>())...};816}817818FlatTuple<Ts...> v_;819};820821GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100822823template <typename... T>824class CartesianProductGenerator825: public ParamGeneratorInterface<::std::tuple<T...>> {826public:827typedef ::std::tuple<T...> ParamType;828829CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)830: generators_(g) {}831~CartesianProductGenerator() override = default;832833ParamIteratorInterface<ParamType>* Begin() const override {834return new Iterator(this, generators_, false);835}836ParamIteratorInterface<ParamType>* End() const override {837return new Iterator(this, generators_, true);838}839840private:841template <class I>842class IteratorImpl;843template <size_t... I>844class IteratorImpl<std::index_sequence<I...>>845: public ParamIteratorInterface<ParamType> {846public:847IteratorImpl(const ParamGeneratorInterface<ParamType>* base,848const std::tuple<ParamGenerator<T>...>& generators,849bool is_end)850: base_(base),851begin_(std::get<I>(generators).begin()...),852end_(std::get<I>(generators).end()...),853current_(is_end ? end_ : begin_) {854ComputeCurrentValue();855}856~IteratorImpl() override = default;857858const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {859return base_;860}861// Advance should not be called on beyond-of-range iterators862// so no component iterators must be beyond end of range, either.863void Advance() override {864assert(!AtEnd());865// Advance the last iterator.866++std::get<sizeof...(T) - 1>(current_);867// if that reaches end, propagate that up.868AdvanceIfEnd<sizeof...(T) - 1>();869ComputeCurrentValue();870}871ParamIteratorInterface<ParamType>* Clone() const override {872return new IteratorImpl(*this);873}874875const ParamType* Current() const override { return current_value_.get(); }876877bool Equals(const ParamIteratorInterface<ParamType>& other) const override {878// Having the same base generator guarantees that the other879// iterator is of the same type and we can downcast.880GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())881<< "The program attempted to compare iterators "882<< "from different generators." << std::endl;883const IteratorImpl* typed_other =884CheckedDowncastToActualType<const IteratorImpl>(&other);885886// We must report iterators equal if they both point beyond their887// respective ranges. That can happen in a variety of fashions,888// so we have to consult AtEnd().889if (AtEnd() && typed_other->AtEnd()) return true;890891bool same = true;892bool dummy[] = {893(same = same && std::get<I>(current_) ==894std::get<I>(typed_other->current_))...};895(void)dummy;896return same;897}898899private:900template <size_t ThisI>901void AdvanceIfEnd() {902if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;903904bool last = ThisI == 0;905if (last) {906// We are done. Nothing else to propagate.907return;908}909910constexpr size_t NextI = ThisI - (ThisI != 0);911std::get<ThisI>(current_) = std::get<ThisI>(begin_);912++std::get<NextI>(current_);913AdvanceIfEnd<NextI>();914}915916void ComputeCurrentValue() {917if (!AtEnd())918current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);919}920bool AtEnd() const {921bool at_end = false;922bool dummy[] = {923(at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};924(void)dummy;925return at_end;926}927928const ParamGeneratorInterface<ParamType>* const base_;929std::tuple<typename ParamGenerator<T>::iterator...> begin_;930std::tuple<typename ParamGenerator<T>::iterator...> end_;931std::tuple<typename ParamGenerator<T>::iterator...> current_;932std::shared_ptr<ParamType> current_value_;933};934935using Iterator = IteratorImpl<std::make_index_sequence<sizeof...(T)>>;936937std::tuple<ParamGenerator<T>...> generators_;938};939940template <class... Gen>941class CartesianProductHolder {942public:943CartesianProductHolder(const Gen&... g) : generators_(g...) {}944template <typename... T>945operator ParamGenerator<::std::tuple<T...>>() const {946return ParamGenerator<::std::tuple<T...>>(947new CartesianProductGenerator<T...>(generators_));948}949950private:951std::tuple<Gen...> generators_;952};953954template <typename From, typename To, typename Func>955class ParamGeneratorConverter : public ParamGeneratorInterface<To> {956public:957ParamGeneratorConverter(ParamGenerator<From> gen, Func converter) // NOLINT958: generator_(std::move(gen)), converter_(std::move(converter)) {}959960ParamIteratorInterface<To>* Begin() const override {961return new Iterator(this, generator_.begin(), generator_.end());962}963ParamIteratorInterface<To>* End() const override {964return new Iterator(this, generator_.end(), generator_.end());965}966967// Returns the std::function wrapping the user-supplied converter callable. It968// is used by the iterator (see class Iterator below) to convert the object969// (of type FROM) returned by the ParamGenerator to an object of a type that970// can be static_cast to type TO.971const Func& TypeConverter() const { return converter_; }972973private:974class Iterator : public ParamIteratorInterface<To> {975public:976Iterator(const ParamGeneratorConverter* base, ParamIterator<From> it,977ParamIterator<From> end)978: base_(base), it_(it), end_(end) {979if (it_ != end_)980value_ =981std::make_shared<To>(static_cast<To>(base->TypeConverter()(*it_)));982}983~Iterator() override = default;984985const ParamGeneratorInterface<To>* BaseGenerator() const override {986return base_;987}988void Advance() override {989++it_;990if (it_ != end_)991value_ =992std::make_shared<To>(static_cast<To>(base_->TypeConverter()(*it_)));993}994ParamIteratorInterface<To>* Clone() const override {995return new Iterator(*this);996}997const To* Current() const override { return value_.get(); }998bool Equals(const ParamIteratorInterface<To>& other) const override {999// Having the same base generator guarantees that the other1000// iterator is of the same type and we can downcast.1001GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())1002<< "The program attempted to compare iterators "1003<< "from different generators." << std::endl;1004const ParamIterator<From> other_it =1005CheckedDowncastToActualType<const Iterator>(&other)->it_;1006return it_ == other_it;1007}10081009private:1010Iterator(const Iterator& other) = default;10111012const ParamGeneratorConverter* const base_;1013ParamIterator<From> it_;1014ParamIterator<From> end_;1015std::shared_ptr<To> value_;1016}; // class ParamGeneratorConverter::Iterator10171018ParamGenerator<From> generator_;1019Func converter_;1020}; // class ParamGeneratorConverter10211022template <class GeneratedT,1023typename StdFunction =1024std::function<const GeneratedT&(const GeneratedT&)>>1025class ParamConverterGenerator {1026public:1027ParamConverterGenerator(ParamGenerator<GeneratedT> g) // NOLINT1028: generator_(std::move(g)), converter_(Identity) {}10291030ParamConverterGenerator(ParamGenerator<GeneratedT> g, StdFunction converter)1031: generator_(std::move(g)), converter_(std::move(converter)) {}10321033template <typename T>1034operator ParamGenerator<T>() const { // NOLINT1035return ParamGenerator<T>(1036new ParamGeneratorConverter<GeneratedT, T, StdFunction>(generator_,1037converter_));1038}10391040private:1041static const GeneratedT& Identity(const GeneratedT& v) { return v; }10421043ParamGenerator<GeneratedT> generator_;1044StdFunction converter_;1045};10461047// Template to determine the param type of a single-param std::function.1048template <typename T>1049struct FuncSingleParamType;1050template <typename R, typename P>1051struct FuncSingleParamType<std::function<R(P)>> {1052using type = std::remove_cv_t<std::remove_reference_t<P>>;1053};10541055template <typename T>1056struct IsSingleArgStdFunction : public std::false_type {};1057template <typename R, typename P>1058struct IsSingleArgStdFunction<std::function<R(P)>> : public std::true_type {};10591060} // namespace internal1061} // namespace testing10621063#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_106410651066