gtest-param-util.h 37 KB

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