gtest-param-util.h 34 KB

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