gtest-param-util.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. // Copyright 2008 Google Inc.
  2. // All Rights Reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Type and function utilities for implementing parameterized tests.
  30. // GOOGLETEST_CM0001 DO NOT DELETE
  31. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  32. #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  33. #include <ctype.h>
  34. #include <cassert>
  35. #include <iterator>
  36. #include <memory>
  37. #include <set>
  38. #include <tuple>
  39. #include <utility>
  40. #include <vector>
  41. #include "gtest/internal/gtest-internal.h"
  42. #include "gtest/internal/gtest-port.h"
  43. #include "gtest/gtest-printers.h"
  44. namespace testing {
  45. // Input to a parameterized test name generator, describing a test parameter.
  46. // Consists of the parameter value and the integer parameter index.
  47. template <class ParamType>
  48. struct TestParamInfo {
  49. TestParamInfo(const ParamType& a_param, size_t an_index) :
  50. param(a_param),
  51. index(an_index) {}
  52. ParamType param;
  53. size_t index;
  54. };
  55. // A builtin parameterized test name generator which returns the result of
  56. // testing::PrintToString.
  57. struct PrintToStringParamName {
  58. template <class ParamType>
  59. std::string operator()(const TestParamInfo<ParamType>& info) const {
  60. return PrintToString(info.param);
  61. }
  62. };
  63. namespace internal {
  64. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  65. // Utility Functions
  66. // Outputs a message explaining invalid registration of different
  67. // fixture class for the same test suite. This may happen when
  68. // TEST_P macro is used to define two tests with the same name
  69. // but in different namespaces.
  70. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
  71. CodeLocation code_location);
  72. template <typename> class ParamGeneratorInterface;
  73. template <typename> class ParamGenerator;
  74. // Interface for iterating over elements provided by an implementation
  75. // of ParamGeneratorInterface<T>.
  76. template <typename T>
  77. class ParamIteratorInterface {
  78. public:
  79. virtual ~ParamIteratorInterface() {}
  80. // A pointer to the base generator instance.
  81. // Used only for the purposes of iterator comparison
  82. // to make sure that two iterators belong to the same generator.
  83. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
  84. // Advances iterator to point to the next element
  85. // provided by the generator. The caller is responsible
  86. // for not calling Advance() on an iterator equal to
  87. // BaseGenerator()->End().
  88. virtual void Advance() = 0;
  89. // Clones the iterator object. Used for implementing copy semantics
  90. // of ParamIterator<T>.
  91. virtual ParamIteratorInterface* Clone() const = 0;
  92. // Dereferences the current iterator and provides (read-only) access
  93. // to the pointed value. It is the caller's responsibility not to call
  94. // Current() on an iterator equal to BaseGenerator()->End().
  95. // Used for implementing ParamGenerator<T>::operator*().
  96. virtual const T* Current() const = 0;
  97. // Determines whether the given iterator and other point to the same
  98. // element in the sequence generated by the generator.
  99. // Used for implementing ParamGenerator<T>::operator==().
  100. virtual bool Equals(const ParamIteratorInterface& other) const = 0;
  101. };
  102. // Class iterating over elements provided by an implementation of
  103. // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
  104. // and implements the const forward iterator concept.
  105. template <typename T>
  106. class ParamIterator {
  107. public:
  108. typedef T value_type;
  109. typedef const T& reference;
  110. typedef ptrdiff_t difference_type;
  111. // ParamIterator assumes ownership of the impl_ pointer.
  112. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
  113. ParamIterator& operator=(const ParamIterator& other) {
  114. if (this != &other)
  115. impl_.reset(other.impl_->Clone());
  116. return *this;
  117. }
  118. const T& operator*() const { return *impl_->Current(); }
  119. const T* operator->() const { return impl_->Current(); }
  120. // Prefix version of operator++.
  121. ParamIterator& operator++() {
  122. impl_->Advance();
  123. return *this;
  124. }
  125. // Postfix version of operator++.
  126. ParamIterator operator++(int /*unused*/) {
  127. ParamIteratorInterface<T>* clone = impl_->Clone();
  128. impl_->Advance();
  129. return ParamIterator(clone);
  130. }
  131. bool operator==(const ParamIterator& other) const {
  132. return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
  133. }
  134. bool operator!=(const ParamIterator& other) const {
  135. return !(*this == other);
  136. }
  137. private:
  138. friend class ParamGenerator<T>;
  139. explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
  140. std::unique_ptr<ParamIteratorInterface<T> > impl_;
  141. };
  142. // ParamGeneratorInterface<T> is the binary interface to access generators
  143. // defined in other translation units.
  144. template <typename T>
  145. class ParamGeneratorInterface {
  146. public:
  147. typedef T ParamType;
  148. virtual ~ParamGeneratorInterface() {}
  149. // Generator interface definition
  150. virtual ParamIteratorInterface<T>* Begin() const = 0;
  151. virtual ParamIteratorInterface<T>* End() const = 0;
  152. };
  153. // Wraps ParamGeneratorInterface<T> and provides general generator syntax
  154. // compatible with the STL Container concept.
  155. // This class implements copy initialization semantics and the contained
  156. // ParamGeneratorInterface<T> instance is shared among all copies
  157. // of the original object. This is possible because that instance is immutable.
  158. template<typename T>
  159. class ParamGenerator {
  160. public:
  161. typedef ParamIterator<T> iterator;
  162. explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
  163. ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
  164. ParamGenerator& operator=(const ParamGenerator& other) {
  165. impl_ = other.impl_;
  166. return *this;
  167. }
  168. iterator begin() const { return iterator(impl_->Begin()); }
  169. iterator end() const { return iterator(impl_->End()); }
  170. private:
  171. std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
  172. };
  173. // Generates values from a range of two comparable values. Can be used to
  174. // generate sequences of user-defined types that implement operator+() and
  175. // operator<().
  176. // This class is used in the Range() function.
  177. template <typename T, typename IncrementT>
  178. class RangeGenerator : public ParamGeneratorInterface<T> {
  179. public:
  180. RangeGenerator(T begin, T end, IncrementT step)
  181. : begin_(begin), end_(end),
  182. step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
  183. ~RangeGenerator() override {}
  184. ParamIteratorInterface<T>* Begin() const override {
  185. return new Iterator(this, begin_, 0, step_);
  186. }
  187. ParamIteratorInterface<T>* End() const override {
  188. return new Iterator(this, end_, end_index_, step_);
  189. }
  190. private:
  191. class Iterator : public ParamIteratorInterface<T> {
  192. public:
  193. Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
  194. IncrementT step)
  195. : base_(base), value_(value), index_(index), step_(step) {}
  196. ~Iterator() override {}
  197. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  198. return base_;
  199. }
  200. void Advance() override {
  201. value_ = static_cast<T>(value_ + step_);
  202. index_++;
  203. }
  204. ParamIteratorInterface<T>* Clone() const override {
  205. return new Iterator(*this);
  206. }
  207. const T* Current() const override { return &value_; }
  208. bool Equals(const ParamIteratorInterface<T>& other) const override {
  209. // Having the same base generator guarantees that the other
  210. // iterator is of the same type and we can downcast.
  211. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  212. << "The program attempted to compare iterators "
  213. << "from different generators." << std::endl;
  214. const int other_index =
  215. CheckedDowncastToActualType<const Iterator>(&other)->index_;
  216. return index_ == other_index;
  217. }
  218. private:
  219. Iterator(const Iterator& other)
  220. : ParamIteratorInterface<T>(),
  221. base_(other.base_), value_(other.value_), index_(other.index_),
  222. step_(other.step_) {}
  223. // No implementation - assignment is unsupported.
  224. void operator=(const Iterator& other);
  225. const ParamGeneratorInterface<T>* const base_;
  226. T value_;
  227. int index_;
  228. const IncrementT step_;
  229. }; // class RangeGenerator::Iterator
  230. static int CalculateEndIndex(const T& begin,
  231. const T& end,
  232. const IncrementT& step) {
  233. int end_index = 0;
  234. for (T i = begin; i < end; i = static_cast<T>(i + step))
  235. end_index++;
  236. return end_index;
  237. }
  238. // No implementation - assignment is unsupported.
  239. void operator=(const RangeGenerator& other);
  240. const T begin_;
  241. const T end_;
  242. const IncrementT step_;
  243. // The index for the end() iterator. All the elements in the generated
  244. // sequence are indexed (0-based) to aid iterator comparison.
  245. const int end_index_;
  246. }; // class RangeGenerator
  247. // Generates values from a pair of STL-style iterators. Used in the
  248. // ValuesIn() function. The elements are copied from the source range
  249. // since the source can be located on the stack, and the generator
  250. // is likely to persist beyond that stack frame.
  251. template <typename T>
  252. class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
  253. public:
  254. template <typename ForwardIterator>
  255. ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
  256. : container_(begin, end) {}
  257. ~ValuesInIteratorRangeGenerator() override {}
  258. ParamIteratorInterface<T>* Begin() const override {
  259. return new Iterator(this, container_.begin());
  260. }
  261. ParamIteratorInterface<T>* End() const override {
  262. return new Iterator(this, container_.end());
  263. }
  264. private:
  265. typedef typename ::std::vector<T> ContainerType;
  266. class Iterator : public ParamIteratorInterface<T> {
  267. public:
  268. Iterator(const ParamGeneratorInterface<T>* base,
  269. typename ContainerType::const_iterator iterator)
  270. : base_(base), iterator_(iterator) {}
  271. ~Iterator() override {}
  272. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  273. return base_;
  274. }
  275. void Advance() override {
  276. ++iterator_;
  277. value_.reset();
  278. }
  279. ParamIteratorInterface<T>* Clone() const override {
  280. return new Iterator(*this);
  281. }
  282. // We need to use cached value referenced by iterator_ because *iterator_
  283. // can return a temporary object (and of type other then T), so just
  284. // having "return &*iterator_;" doesn't work.
  285. // value_ is updated here and not in Advance() because Advance()
  286. // can advance iterator_ beyond the end of the range, and we cannot
  287. // detect that fact. The client code, on the other hand, is
  288. // responsible for not calling Current() on an out-of-range iterator.
  289. const T* Current() const override {
  290. if (value_.get() == nullptr) value_.reset(new T(*iterator_));
  291. return value_.get();
  292. }
  293. bool Equals(const ParamIteratorInterface<T>& other) const override {
  294. // Having the same base generator guarantees that the other
  295. // iterator is of the same type and we can downcast.
  296. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  297. << "The program attempted to compare iterators "
  298. << "from different generators." << std::endl;
  299. return iterator_ ==
  300. CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
  301. }
  302. private:
  303. Iterator(const Iterator& other)
  304. // The explicit constructor call suppresses a false warning
  305. // emitted by gcc when supplied with the -Wextra option.
  306. : ParamIteratorInterface<T>(),
  307. base_(other.base_),
  308. iterator_(other.iterator_) {}
  309. const ParamGeneratorInterface<T>* const base_;
  310. typename ContainerType::const_iterator iterator_;
  311. // A cached value of *iterator_. We keep it here to allow access by
  312. // pointer in the wrapping iterator's operator->().
  313. // value_ needs to be mutable to be accessed in Current().
  314. // Use of std::unique_ptr helps manage cached value's lifetime,
  315. // which is bound by the lifespan of the iterator itself.
  316. mutable std::unique_ptr<const T> value_;
  317. }; // class ValuesInIteratorRangeGenerator::Iterator
  318. // No implementation - assignment is unsupported.
  319. void operator=(const ValuesInIteratorRangeGenerator& other);
  320. const ContainerType container_;
  321. }; // class ValuesInIteratorRangeGenerator
  322. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  323. //
  324. // Default parameterized test name generator, returns a string containing the
  325. // integer test parameter index.
  326. template <class ParamType>
  327. std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
  328. Message name_stream;
  329. name_stream << info.index;
  330. return name_stream.GetString();
  331. }
  332. template <typename T = int>
  333. void TestNotEmpty() {
  334. static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
  335. }
  336. template <typename T = int>
  337. void TestNotEmpty(const T&) {}
  338. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  339. //
  340. // Stores a parameter value and later creates tests parameterized with that
  341. // value.
  342. template <class TestClass>
  343. class ParameterizedTestFactory : public TestFactoryBase {
  344. public:
  345. typedef typename TestClass::ParamType ParamType;
  346. explicit ParameterizedTestFactory(ParamType parameter) :
  347. parameter_(parameter) {}
  348. Test* CreateTest() override {
  349. TestClass::SetParam(&parameter_);
  350. return new TestClass();
  351. }
  352. private:
  353. const ParamType parameter_;
  354. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
  355. };
  356. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  357. //
  358. // TestMetaFactoryBase is a base class for meta-factories that create
  359. // test factories for passing into MakeAndRegisterTestInfo function.
  360. template <class ParamType>
  361. class TestMetaFactoryBase {
  362. public:
  363. virtual ~TestMetaFactoryBase() {}
  364. virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
  365. };
  366. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  367. //
  368. // TestMetaFactory creates test factories for passing into
  369. // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
  370. // ownership of test factory pointer, same factory object cannot be passed
  371. // into that method twice. But ParameterizedTestSuiteInfo is going to call
  372. // it for each Test/Parameter value combination. Thus it needs meta factory
  373. // creator class.
  374. template <class TestSuite>
  375. class TestMetaFactory
  376. : public TestMetaFactoryBase<typename TestSuite::ParamType> {
  377. public:
  378. using ParamType = typename TestSuite::ParamType;
  379. TestMetaFactory() {}
  380. TestFactoryBase* CreateTestFactory(ParamType parameter) override {
  381. return new ParameterizedTestFactory<TestSuite>(parameter);
  382. }
  383. private:
  384. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
  385. };
  386. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  387. //
  388. // ParameterizedTestSuiteInfoBase is a generic interface
  389. // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
  390. // accumulates test information provided by TEST_P macro invocations
  391. // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
  392. // and uses that information to register all resulting test instances
  393. // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
  394. // a collection of pointers to the ParameterizedTestSuiteInfo objects
  395. // and calls RegisterTests() on each of them when asked.
  396. class ParameterizedTestSuiteInfoBase {
  397. public:
  398. virtual ~ParameterizedTestSuiteInfoBase() {}
  399. // Base part of test suite name for display purposes.
  400. virtual const std::string& GetTestSuiteName() const = 0;
  401. // Test case id to verify identity.
  402. virtual TypeId GetTestSuiteTypeId() const = 0;
  403. // UnitTest class invokes this method to register tests in this
  404. // test suite right before running them in RUN_ALL_TESTS macro.
  405. // This method should not be called more than once on any single
  406. // instance of a ParameterizedTestSuiteInfoBase derived class.
  407. virtual void RegisterTests() = 0;
  408. protected:
  409. ParameterizedTestSuiteInfoBase() {}
  410. private:
  411. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
  412. };
  413. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  414. //
  415. // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
  416. // macro invocations for a particular test suite and generators
  417. // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
  418. // test suite. It registers tests with all values generated by all
  419. // generators when asked.
  420. template <class TestSuite>
  421. class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
  422. public:
  423. // ParamType and GeneratorCreationFunc are private types but are required
  424. // for declarations of public methods AddTestPattern() and
  425. // AddTestSuiteInstantiation().
  426. using ParamType = typename TestSuite::ParamType;
  427. // A function that returns an instance of appropriate generator type.
  428. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
  429. using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
  430. explicit ParameterizedTestSuiteInfo(const char* name,
  431. CodeLocation code_location)
  432. : test_suite_name_(name), code_location_(code_location) {}
  433. // Test case base name for display purposes.
  434. const std::string& GetTestSuiteName() const override {
  435. return test_suite_name_;
  436. }
  437. // Test case id to verify identity.
  438. TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
  439. // TEST_P macro uses AddTestPattern() to record information
  440. // about a single test in a LocalTestInfo structure.
  441. // test_suite_name is the base name of the test suite (without invocation
  442. // prefix). test_base_name is the name of an individual test without
  443. // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
  444. // test suite base name and DoBar is test base name.
  445. void AddTestPattern(const char* test_suite_name, const char* test_base_name,
  446. TestMetaFactoryBase<ParamType>* meta_factory) {
  447. tests_.push_back(std::shared_ptr<TestInfo>(
  448. new TestInfo(test_suite_name, test_base_name, meta_factory)));
  449. }
  450. // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
  451. // about a generator.
  452. int AddTestSuiteInstantiation(const std::string& instantiation_name,
  453. GeneratorCreationFunc* func,
  454. ParamNameGeneratorFunc* name_func,
  455. const char* file, int line) {
  456. instantiations_.push_back(
  457. InstantiationInfo(instantiation_name, func, name_func, file, line));
  458. return 0; // Return value used only to run this method in namespace scope.
  459. }
  460. // UnitTest class invokes this method to register tests in this test suite
  461. // test suites right before running tests in RUN_ALL_TESTS macro.
  462. // This method should not be called more than once on any single
  463. // instance of a ParameterizedTestSuiteInfoBase derived class.
  464. // UnitTest has a guard to prevent from calling this method more than once.
  465. void RegisterTests() override {
  466. for (typename TestInfoContainer::iterator test_it = tests_.begin();
  467. test_it != tests_.end(); ++test_it) {
  468. std::shared_ptr<TestInfo> test_info = *test_it;
  469. for (typename InstantiationContainer::iterator gen_it =
  470. instantiations_.begin(); gen_it != instantiations_.end();
  471. ++gen_it) {
  472. const std::string& instantiation_name = gen_it->name;
  473. ParamGenerator<ParamType> generator((*gen_it->generator)());
  474. ParamNameGeneratorFunc* name_func = gen_it->name_func;
  475. const char* file = gen_it->file;
  476. int line = gen_it->line;
  477. std::string test_suite_name;
  478. if ( !instantiation_name.empty() )
  479. test_suite_name = instantiation_name + "/";
  480. test_suite_name += test_info->test_suite_base_name;
  481. size_t i = 0;
  482. std::set<std::string> test_param_names;
  483. for (typename ParamGenerator<ParamType>::iterator param_it =
  484. generator.begin();
  485. param_it != generator.end(); ++param_it, ++i) {
  486. Message test_name_stream;
  487. std::string param_name = name_func(
  488. TestParamInfo<ParamType>(*param_it, i));
  489. GTEST_CHECK_(IsValidParamName(param_name))
  490. << "Parameterized test name '" << param_name
  491. << "' is invalid, in " << file
  492. << " line " << line << std::endl;
  493. GTEST_CHECK_(test_param_names.count(param_name) == 0)
  494. << "Duplicate parameterized test name '" << param_name
  495. << "', in " << file << " line " << line << std::endl;
  496. test_param_names.insert(param_name);
  497. if (!test_info->test_base_name.empty()) {
  498. test_name_stream << test_info->test_base_name << "/";
  499. }
  500. test_name_stream << param_name;
  501. MakeAndRegisterTestInfo(
  502. test_suite_name.c_str(), test_name_stream.GetString().c_str(),
  503. nullptr, // No type parameter.
  504. PrintToString(*param_it).c_str(), code_location_,
  505. GetTestSuiteTypeId(),
  506. SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
  507. SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
  508. test_info->test_meta_factory->CreateTestFactory(*param_it));
  509. } // for param_it
  510. } // for gen_it
  511. } // for test_it
  512. } // RegisterTests
  513. private:
  514. // LocalTestInfo structure keeps information about a single test registered
  515. // with TEST_P macro.
  516. struct TestInfo {
  517. TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
  518. TestMetaFactoryBase<ParamType>* a_test_meta_factory)
  519. : test_suite_base_name(a_test_suite_base_name),
  520. test_base_name(a_test_base_name),
  521. test_meta_factory(a_test_meta_factory) {}
  522. const std::string test_suite_base_name;
  523. const std::string test_base_name;
  524. const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
  525. };
  526. using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
  527. // Records data received from INSTANTIATE_TEST_SUITE_P macros:
  528. // <Instantiation name, Sequence generator creation function,
  529. // Name generator function, Source file, Source line>
  530. struct InstantiationInfo {
  531. InstantiationInfo(const std::string &name_in,
  532. GeneratorCreationFunc* generator_in,
  533. ParamNameGeneratorFunc* name_func_in,
  534. const char* file_in,
  535. int line_in)
  536. : name(name_in),
  537. generator(generator_in),
  538. name_func(name_func_in),
  539. file(file_in),
  540. line(line_in) {}
  541. std::string name;
  542. GeneratorCreationFunc* generator;
  543. ParamNameGeneratorFunc* name_func;
  544. const char* file;
  545. int line;
  546. };
  547. typedef ::std::vector<InstantiationInfo> InstantiationContainer;
  548. static bool IsValidParamName(const std::string& name) {
  549. // Check for empty string
  550. if (name.empty())
  551. return false;
  552. // Check for invalid characters
  553. for (std::string::size_type index = 0; index < name.size(); ++index) {
  554. if (!isalnum(name[index]) && name[index] != '_')
  555. return false;
  556. }
  557. return true;
  558. }
  559. const std::string test_suite_name_;
  560. CodeLocation code_location_;
  561. TestInfoContainer tests_;
  562. InstantiationContainer instantiations_;
  563. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
  564. }; // class ParameterizedTestSuiteInfo
  565. // Legacy API is deprecated but still available
  566. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  567. template <class TestCase>
  568. using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
  569. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  570. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  571. //
  572. // ParameterizedTestSuiteRegistry contains a map of
  573. // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
  574. // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
  575. // ParameterizedTestSuiteInfo descriptors.
  576. class ParameterizedTestSuiteRegistry {
  577. public:
  578. ParameterizedTestSuiteRegistry() {}
  579. ~ParameterizedTestSuiteRegistry() {
  580. for (auto& test_suite_info : test_suite_infos_) {
  581. delete test_suite_info;
  582. }
  583. }
  584. // Looks up or creates and returns a structure containing information about
  585. // tests and instantiations of a particular test suite.
  586. template <class TestSuite>
  587. ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
  588. const char* test_suite_name, CodeLocation code_location) {
  589. ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
  590. for (auto& test_suite_info : test_suite_infos_) {
  591. if (test_suite_info->GetTestSuiteName() == test_suite_name) {
  592. if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
  593. // Complain about incorrect usage of Google Test facilities
  594. // and terminate the program since we cannot guaranty correct
  595. // test suite setup and tear-down in this case.
  596. ReportInvalidTestSuiteType(test_suite_name, code_location);
  597. posix::Abort();
  598. } else {
  599. // At this point we are sure that the object we found is of the same
  600. // type we are looking for, so we downcast it to that type
  601. // without further checks.
  602. typed_test_info = CheckedDowncastToActualType<
  603. ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
  604. }
  605. break;
  606. }
  607. }
  608. if (typed_test_info == nullptr) {
  609. typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
  610. test_suite_name, code_location);
  611. test_suite_infos_.push_back(typed_test_info);
  612. }
  613. return typed_test_info;
  614. }
  615. void RegisterTests() {
  616. for (auto& test_suite_info : test_suite_infos_) {
  617. test_suite_info->RegisterTests();
  618. }
  619. }
  620. // Legacy API is deprecated but still available
  621. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  622. template <class TestCase>
  623. ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
  624. const char* test_case_name, CodeLocation code_location) {
  625. return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
  626. }
  627. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  628. private:
  629. using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
  630. TestSuiteInfoContainer test_suite_infos_;
  631. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
  632. };
  633. } // namespace internal
  634. // Forward declarations of ValuesIn(), which is implemented in
  635. // include/gtest/gtest-param-test.h.
  636. template <class Container>
  637. internal::ParamGenerator<typename Container::value_type> ValuesIn(
  638. const Container& container);
  639. namespace internal {
  640. // Used in the Values() function to provide polymorphic capabilities.
  641. template <typename... Ts>
  642. class ValueArray {
  643. public:
  644. ValueArray(Ts... v) : v_{std::move(v)...} {}
  645. template <typename T>
  646. operator ParamGenerator<T>() const { // NOLINT
  647. return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
  648. }
  649. private:
  650. template <typename T, size_t... I>
  651. std::vector<T> MakeVector(IndexSequence<I...>) const {
  652. return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
  653. }
  654. FlatTuple<Ts...> v_;
  655. };
  656. template <typename... T>
  657. class CartesianProductGenerator
  658. : public ParamGeneratorInterface<::std::tuple<T...>> {
  659. public:
  660. typedef ::std::tuple<T...> ParamType;
  661. CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
  662. : generators_(g) {}
  663. ~CartesianProductGenerator() override {}
  664. ParamIteratorInterface<ParamType>* Begin() const override {
  665. return new Iterator(this, generators_, false);
  666. }
  667. ParamIteratorInterface<ParamType>* End() const override {
  668. return new Iterator(this, generators_, true);
  669. }
  670. private:
  671. template <class I>
  672. class IteratorImpl;
  673. template <size_t... I>
  674. class IteratorImpl<IndexSequence<I...>>
  675. : public ParamIteratorInterface<ParamType> {
  676. public:
  677. IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
  678. const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
  679. : base_(base),
  680. begin_(std::get<I>(generators).begin()...),
  681. end_(std::get<I>(generators).end()...),
  682. current_(is_end ? end_ : begin_) {
  683. ComputeCurrentValue();
  684. }
  685. ~IteratorImpl() override {}
  686. const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
  687. return base_;
  688. }
  689. // Advance should not be called on beyond-of-range iterators
  690. // so no component iterators must be beyond end of range, either.
  691. void Advance() override {
  692. assert(!AtEnd());
  693. // Advance the last iterator.
  694. ++std::get<sizeof...(T) - 1>(current_);
  695. // if that reaches end, propagate that up.
  696. AdvanceIfEnd<sizeof...(T) - 1>();
  697. ComputeCurrentValue();
  698. }
  699. ParamIteratorInterface<ParamType>* Clone() const override {
  700. return new IteratorImpl(*this);
  701. }
  702. const ParamType* Current() const override { return current_value_.get(); }
  703. bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
  704. // Having the same base generator guarantees that the other
  705. // iterator is of the same type and we can downcast.
  706. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  707. << "The program attempted to compare iterators "
  708. << "from different generators." << std::endl;
  709. const IteratorImpl* typed_other =
  710. CheckedDowncastToActualType<const IteratorImpl>(&other);
  711. // We must report iterators equal if they both point beyond their
  712. // respective ranges. That can happen in a variety of fashions,
  713. // so we have to consult AtEnd().
  714. if (AtEnd() && typed_other->AtEnd()) return true;
  715. bool same = true;
  716. bool dummy[] = {
  717. (same = same && std::get<I>(current_) ==
  718. std::get<I>(typed_other->current_))...};
  719. (void)dummy;
  720. return same;
  721. }
  722. private:
  723. template <size_t ThisI>
  724. void AdvanceIfEnd() {
  725. if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
  726. bool last = ThisI == 0;
  727. if (last) {
  728. // We are done. Nothing else to propagate.
  729. return;
  730. }
  731. constexpr size_t NextI = ThisI - (ThisI != 0);
  732. std::get<ThisI>(current_) = std::get<ThisI>(begin_);
  733. ++std::get<NextI>(current_);
  734. AdvanceIfEnd<NextI>();
  735. }
  736. void ComputeCurrentValue() {
  737. if (!AtEnd())
  738. current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
  739. }
  740. bool AtEnd() const {
  741. bool at_end = false;
  742. bool dummy[] = {
  743. (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
  744. (void)dummy;
  745. return at_end;
  746. }
  747. const ParamGeneratorInterface<ParamType>* const base_;
  748. std::tuple<typename ParamGenerator<T>::iterator...> begin_;
  749. std::tuple<typename ParamGenerator<T>::iterator...> end_;
  750. std::tuple<typename ParamGenerator<T>::iterator...> current_;
  751. std::shared_ptr<ParamType> current_value_;
  752. };
  753. using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
  754. std::tuple<ParamGenerator<T>...> generators_;
  755. };
  756. template <class... Gen>
  757. class CartesianProductHolder {
  758. public:
  759. CartesianProductHolder(const Gen&... g) : generators_(g...) {}
  760. template <typename... T>
  761. operator ParamGenerator<::std::tuple<T...>>() const {
  762. return ParamGenerator<::std::tuple<T...>>(
  763. new CartesianProductGenerator<T...>(generators_));
  764. }
  765. private:
  766. std::tuple<Gen...> generators_;
  767. };
  768. } // namespace internal
  769. } // namespace testing
  770. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_