gtest-param-util.h 35 KB

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