gtest-param-util.h 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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() {}
  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() {}
  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 {}
  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 {}
  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 {}
  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 {}
  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() {}
  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() {}
  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() {}
  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() {}
  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. #ifdef _MSC_VER
  699. #pragma warning(push)
  700. #pragma warning(disable : 4100)
  701. #endif
  702. template <typename... Ts>
  703. class ValueArray {
  704. public:
  705. explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
  706. template <typename T>
  707. operator ParamGenerator<T>() const { // NOLINT
  708. return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
  709. }
  710. private:
  711. template <typename T, size_t... I>
  712. std::vector<T> MakeVector(IndexSequence<I...>) const {
  713. return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
  714. }
  715. FlatTuple<Ts...> v_;
  716. };
  717. #ifdef _MSC_VER
  718. #pragma warning(pop)
  719. #endif
  720. template <typename... T>
  721. class CartesianProductGenerator
  722. : public ParamGeneratorInterface<::std::tuple<T...>> {
  723. public:
  724. typedef ::std::tuple<T...> ParamType;
  725. CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
  726. : generators_(g) {}
  727. ~CartesianProductGenerator() override {}
  728. ParamIteratorInterface<ParamType>* Begin() const override {
  729. return new Iterator(this, generators_, false);
  730. }
  731. ParamIteratorInterface<ParamType>* End() const override {
  732. return new Iterator(this, generators_, true);
  733. }
  734. private:
  735. template <class I>
  736. class IteratorImpl;
  737. template <size_t... I>
  738. class IteratorImpl<IndexSequence<I...>>
  739. : public ParamIteratorInterface<ParamType> {
  740. public:
  741. IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
  742. const std::tuple<ParamGenerator<T>...>& generators,
  743. bool is_end)
  744. : base_(base),
  745. begin_(std::get<I>(generators).begin()...),
  746. end_(std::get<I>(generators).end()...),
  747. current_(is_end ? end_ : begin_) {
  748. ComputeCurrentValue();
  749. }
  750. ~IteratorImpl() override {}
  751. const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
  752. return base_;
  753. }
  754. // Advance should not be called on beyond-of-range iterators
  755. // so no component iterators must be beyond end of range, either.
  756. void Advance() override {
  757. assert(!AtEnd());
  758. // Advance the last iterator.
  759. ++std::get<sizeof...(T) - 1>(current_);
  760. // if that reaches end, propagate that up.
  761. AdvanceIfEnd<sizeof...(T) - 1>();
  762. ComputeCurrentValue();
  763. }
  764. ParamIteratorInterface<ParamType>* Clone() const override {
  765. return new IteratorImpl(*this);
  766. }
  767. const ParamType* Current() const override { return current_value_.get(); }
  768. bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
  769. // Having the same base generator guarantees that the other
  770. // iterator is of the same type and we can downcast.
  771. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  772. << "The program attempted to compare iterators "
  773. << "from different generators." << std::endl;
  774. const IteratorImpl* typed_other =
  775. CheckedDowncastToActualType<const IteratorImpl>(&other);
  776. // We must report iterators equal if they both point beyond their
  777. // respective ranges. That can happen in a variety of fashions,
  778. // so we have to consult AtEnd().
  779. if (AtEnd() && typed_other->AtEnd()) return true;
  780. bool same = true;
  781. bool dummy[] = {
  782. (same = same && std::get<I>(current_) ==
  783. std::get<I>(typed_other->current_))...};
  784. (void)dummy;
  785. return same;
  786. }
  787. private:
  788. template <size_t ThisI>
  789. void AdvanceIfEnd() {
  790. if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
  791. bool last = ThisI == 0;
  792. if (last) {
  793. // We are done. Nothing else to propagate.
  794. return;
  795. }
  796. constexpr size_t NextI = ThisI - (ThisI != 0);
  797. std::get<ThisI>(current_) = std::get<ThisI>(begin_);
  798. ++std::get<NextI>(current_);
  799. AdvanceIfEnd<NextI>();
  800. }
  801. void ComputeCurrentValue() {
  802. if (!AtEnd())
  803. current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
  804. }
  805. bool AtEnd() const {
  806. bool at_end = false;
  807. bool dummy[] = {
  808. (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
  809. (void)dummy;
  810. return at_end;
  811. }
  812. const ParamGeneratorInterface<ParamType>* const base_;
  813. std::tuple<typename ParamGenerator<T>::iterator...> begin_;
  814. std::tuple<typename ParamGenerator<T>::iterator...> end_;
  815. std::tuple<typename ParamGenerator<T>::iterator...> current_;
  816. std::shared_ptr<ParamType> current_value_;
  817. };
  818. using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
  819. std::tuple<ParamGenerator<T>...> generators_;
  820. };
  821. template <class... Gen>
  822. class CartesianProductHolder {
  823. public:
  824. CartesianProductHolder(const Gen&... g) : generators_(g...) {}
  825. template <typename... T>
  826. operator ParamGenerator<::std::tuple<T...>>() const {
  827. return ParamGenerator<::std::tuple<T...>>(
  828. new CartesianProductGenerator<T...>(generators_));
  829. }
  830. private:
  831. std::tuple<Gen...> generators_;
  832. };
  833. template <typename From, typename To>
  834. class ParamGeneratorConverter : public ParamGeneratorInterface<To> {
  835. public:
  836. ParamGeneratorConverter(ParamGenerator<From> gen) // NOLINT
  837. : generator_(std::move(gen)) {}
  838. ParamIteratorInterface<To>* Begin() const override {
  839. return new Iterator(this, generator_.begin(), generator_.end());
  840. }
  841. ParamIteratorInterface<To>* End() const override {
  842. return new Iterator(this, generator_.end(), generator_.end());
  843. }
  844. private:
  845. class Iterator : public ParamIteratorInterface<To> {
  846. public:
  847. Iterator(const ParamGeneratorInterface<To>* base, ParamIterator<From> it,
  848. ParamIterator<From> end)
  849. : base_(base), it_(it), end_(end) {
  850. if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
  851. }
  852. ~Iterator() override {}
  853. const ParamGeneratorInterface<To>* BaseGenerator() const override {
  854. return base_;
  855. }
  856. void Advance() override {
  857. ++it_;
  858. if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
  859. }
  860. ParamIteratorInterface<To>* Clone() const override {
  861. return new Iterator(*this);
  862. }
  863. const To* Current() const override { return value_.get(); }
  864. bool Equals(const ParamIteratorInterface<To>& other) const override {
  865. // Having the same base generator guarantees that the other
  866. // iterator is of the same type and we can downcast.
  867. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  868. << "The program attempted to compare iterators "
  869. << "from different generators." << std::endl;
  870. const ParamIterator<From> other_it =
  871. CheckedDowncastToActualType<const Iterator>(&other)->it_;
  872. return it_ == other_it;
  873. }
  874. private:
  875. Iterator(const Iterator& other) = default;
  876. const ParamGeneratorInterface<To>* const base_;
  877. ParamIterator<From> it_;
  878. ParamIterator<From> end_;
  879. std::shared_ptr<To> value_;
  880. }; // class ParamGeneratorConverter::Iterator
  881. ParamGenerator<From> generator_;
  882. }; // class ParamGeneratorConverter
  883. template <class Gen>
  884. class ParamConverterGenerator {
  885. public:
  886. ParamConverterGenerator(ParamGenerator<Gen> g) // NOLINT
  887. : generator_(std::move(g)) {}
  888. template <typename T>
  889. operator ParamGenerator<T>() const { // NOLINT
  890. return ParamGenerator<T>(new ParamGeneratorConverter<Gen, T>(generator_));
  891. }
  892. private:
  893. ParamGenerator<Gen> generator_;
  894. };
  895. } // namespace internal
  896. } // namespace testing
  897. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_