gtest-param-util.h 37 KB

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