googletest-param-test-test.cc 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. //
  30. // Tests for Google Test itself. This file verifies that the parameter
  31. // generators objects produce correct parameter sequences and that
  32. // Google Test runtime instantiates correct tests from those sequences.
  33. #include "test/googletest-param-test-test.h"
  34. #include <algorithm>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <functional>
  38. #include <iostream>
  39. #include <list>
  40. #include <set>
  41. #include <sstream>
  42. #include <string>
  43. #include <string_view>
  44. #include <tuple>
  45. #include <type_traits>
  46. #include <vector>
  47. #include "gtest/gtest.h"
  48. #include "src/gtest-internal-inl.h" // for UnitTestOptions
  49. using ::std::sort;
  50. using ::std::vector;
  51. using ::testing::AddGlobalTestEnvironment;
  52. using ::testing::Bool;
  53. using ::testing::Combine;
  54. using ::testing::ConvertGenerator;
  55. using ::testing::Message;
  56. using ::testing::Range;
  57. using ::testing::TestWithParam;
  58. using ::testing::Values;
  59. using ::testing::ValuesIn;
  60. using ::testing::internal::ParamGenerator;
  61. using ::testing::internal::UnitTestOptions;
  62. // Prints a value to a string.
  63. //
  64. // FIXME: remove PrintValue() when we move matchers and
  65. // EXPECT_THAT() from Google Mock to Google Test. At that time, we
  66. // can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as
  67. // EXPECT_THAT() and the matchers know how to print tuples.
  68. template <typename T>
  69. ::std::string PrintValue(const T& value) {
  70. return testing::PrintToString(value);
  71. }
  72. // Verifies that a sequence generated by the generator and accessed
  73. // via the iterator object matches the expected one using Google Test
  74. // assertions.
  75. template <typename T, size_t N>
  76. void VerifyGenerator(const ParamGenerator<T>& generator,
  77. const T (&expected_values)[N]) {
  78. typename ParamGenerator<T>::iterator it = generator.begin();
  79. for (size_t i = 0; i < N; ++i) {
  80. ASSERT_FALSE(it == generator.end())
  81. << "At element " << i << " when accessing via an iterator "
  82. << "created with the copy constructor.\n";
  83. // We cannot use EXPECT_EQ() here as the values may be tuples,
  84. // which don't support <<.
  85. EXPECT_TRUE(expected_values[i] == *it)
  86. << "where i is " << i << ", expected_values[i] is "
  87. << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
  88. << ", and 'it' is an iterator created with the copy constructor.\n";
  89. ++it;
  90. }
  91. EXPECT_TRUE(it == generator.end())
  92. << "At the presumed end of sequence when accessing via an iterator "
  93. << "created with the copy constructor.\n";
  94. // Test the iterator assignment. The following lines verify that
  95. // the sequence accessed via an iterator initialized via the
  96. // assignment operator (as opposed to a copy constructor) matches
  97. // just the same.
  98. it = generator.begin();
  99. for (size_t i = 0; i < N; ++i) {
  100. ASSERT_FALSE(it == generator.end())
  101. << "At element " << i << " when accessing via an iterator "
  102. << "created with the assignment operator.\n";
  103. EXPECT_TRUE(expected_values[i] == *it)
  104. << "where i is " << i << ", expected_values[i] is "
  105. << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
  106. << ", and 'it' is an iterator created with the copy constructor.\n";
  107. ++it;
  108. }
  109. EXPECT_TRUE(it == generator.end())
  110. << "At the presumed end of sequence when accessing via an iterator "
  111. << "created with the assignment operator.\n";
  112. }
  113. template <typename T>
  114. void VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {
  115. typename ParamGenerator<T>::iterator it = generator.begin();
  116. EXPECT_TRUE(it == generator.end());
  117. it = generator.begin();
  118. EXPECT_TRUE(it == generator.end());
  119. }
  120. // Generator tests. They test that each of the provided generator functions
  121. // generates an expected sequence of values. The general test pattern
  122. // instantiates a generator using one of the generator functions,
  123. // checks the sequence produced by the generator using its iterator API,
  124. // and then resets the iterator back to the beginning of the sequence
  125. // and checks the sequence again.
  126. // Tests that iterators produced by generator functions conform to the
  127. // ForwardIterator concept.
  128. TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {
  129. const ParamGenerator<int> gen = Range(0, 10);
  130. ParamGenerator<int>::iterator it = gen.begin();
  131. // Verifies that iterator initialization works as expected.
  132. ParamGenerator<int>::iterator it2 = it;
  133. EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the "
  134. << "element same as its source points to";
  135. // Verifies that iterator assignment works as expected.
  136. ++it;
  137. EXPECT_FALSE(*it == *it2);
  138. it2 = it;
  139. EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
  140. << "element same as its source points to";
  141. // Verifies that prefix operator++() returns *this.
  142. EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be "
  143. << "refer to the original object";
  144. // Verifies that the result of the postfix operator++ points to the value
  145. // pointed to by the original iterator.
  146. int original_value = *it; // Have to compute it outside of macro call to be
  147. // unaffected by the parameter evaluation order.
  148. EXPECT_EQ(original_value, *(it++));
  149. // Verifies that prefix and postfix operator++() advance an iterator
  150. // all the same.
  151. it2 = it;
  152. ++it;
  153. ++it2;
  154. EXPECT_TRUE(*it == *it2);
  155. }
  156. // Tests that Range() generates the expected sequence.
  157. TEST(RangeTest, IntRangeWithDefaultStep) {
  158. const ParamGenerator<int> gen = Range(0, 3);
  159. const int expected_values[] = {0, 1, 2};
  160. VerifyGenerator(gen, expected_values);
  161. }
  162. // Edge case. Tests that Range() generates the single element sequence
  163. // as expected when provided with range limits that are equal.
  164. TEST(RangeTest, IntRangeSingleValue) {
  165. const ParamGenerator<int> gen = Range(0, 1);
  166. const int expected_values[] = {0};
  167. VerifyGenerator(gen, expected_values);
  168. }
  169. // Edge case. Tests that Range() with generates empty sequence when
  170. // supplied with an empty range.
  171. TEST(RangeTest, IntRangeEmpty) {
  172. const ParamGenerator<int> gen = Range(0, 0);
  173. VerifyGeneratorIsEmpty(gen);
  174. }
  175. // Tests that Range() with custom step (greater then one) generates
  176. // the expected sequence.
  177. TEST(RangeTest, IntRangeWithCustomStep) {
  178. const ParamGenerator<int> gen = Range(0, 9, 3);
  179. const int expected_values[] = {0, 3, 6};
  180. VerifyGenerator(gen, expected_values);
  181. }
  182. // Tests that Range() with custom step (greater then one) generates
  183. // the expected sequence when the last element does not fall on the
  184. // upper range limit. Sequences generated by Range() must not have
  185. // elements beyond the range limits.
  186. TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {
  187. const ParamGenerator<int> gen = Range(0, 4, 3);
  188. const int expected_values[] = {0, 3};
  189. VerifyGenerator(gen, expected_values);
  190. }
  191. // Verifies that Range works with user-defined types that define
  192. // copy constructor, operator=(), operator+(), and operator<().
  193. class DogAdder {
  194. public:
  195. explicit DogAdder(const char* a_value) : value_(a_value) {}
  196. DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
  197. DogAdder operator=(const DogAdder& other) {
  198. if (this != &other) value_ = other.value_;
  199. return *this;
  200. }
  201. DogAdder operator+(const DogAdder& other) const {
  202. Message msg;
  203. msg << value_ << other.value_;
  204. return DogAdder(msg.GetString().c_str());
  205. }
  206. bool operator<(const DogAdder& other) const { return value_ < other.value_; }
  207. const std::string& value() const { return value_; }
  208. private:
  209. std::string value_;
  210. };
  211. TEST(RangeTest, WorksWithACustomType) {
  212. const ParamGenerator<DogAdder> gen =
  213. Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
  214. ParamGenerator<DogAdder>::iterator it = gen.begin();
  215. ASSERT_FALSE(it == gen.end());
  216. EXPECT_STREQ("cat", it->value().c_str());
  217. ASSERT_FALSE(++it == gen.end());
  218. EXPECT_STREQ("catdog", it->value().c_str());
  219. EXPECT_TRUE(++it == gen.end());
  220. }
  221. class IntWrapper {
  222. public:
  223. explicit IntWrapper(int a_value) : value_(a_value) {}
  224. IntWrapper(const IntWrapper& other) : value_(other.value_) {}
  225. IntWrapper operator=(const IntWrapper& other) {
  226. value_ = other.value_;
  227. return *this;
  228. }
  229. // operator+() adds a different type.
  230. IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }
  231. bool operator<(const IntWrapper& other) const {
  232. return value_ < other.value_;
  233. }
  234. int value() const { return value_; }
  235. private:
  236. int value_;
  237. };
  238. TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
  239. const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
  240. ParamGenerator<IntWrapper>::iterator it = gen.begin();
  241. ASSERT_FALSE(it == gen.end());
  242. EXPECT_EQ(0, it->value());
  243. ASSERT_FALSE(++it == gen.end());
  244. EXPECT_EQ(1, it->value());
  245. EXPECT_TRUE(++it == gen.end());
  246. }
  247. // Tests that ValuesIn() with an array parameter generates
  248. // the expected sequence.
  249. TEST(ValuesInTest, ValuesInArray) {
  250. int array[] = {3, 5, 8};
  251. const ParamGenerator<int> gen = ValuesIn(array);
  252. VerifyGenerator(gen, array);
  253. }
  254. // Tests that ValuesIn() with a const array parameter generates
  255. // the expected sequence.
  256. TEST(ValuesInTest, ValuesInConstArray) {
  257. const int array[] = {3, 5, 8};
  258. const ParamGenerator<int> gen = ValuesIn(array);
  259. VerifyGenerator(gen, array);
  260. }
  261. // Edge case. Tests that ValuesIn() with an array parameter containing a
  262. // single element generates the single element sequence.
  263. TEST(ValuesInTest, ValuesInSingleElementArray) {
  264. int array[] = {42};
  265. const ParamGenerator<int> gen = ValuesIn(array);
  266. VerifyGenerator(gen, array);
  267. }
  268. // Tests that ValuesIn() generates the expected sequence for an STL
  269. // container (vector).
  270. TEST(ValuesInTest, ValuesInVector) {
  271. typedef ::std::vector<int> ContainerType;
  272. ContainerType values;
  273. values.push_back(3);
  274. values.push_back(5);
  275. values.push_back(8);
  276. const ParamGenerator<int> gen = ValuesIn(values);
  277. const int expected_values[] = {3, 5, 8};
  278. VerifyGenerator(gen, expected_values);
  279. }
  280. // Tests that ValuesIn() generates the expected sequence.
  281. TEST(ValuesInTest, ValuesInIteratorRange) {
  282. typedef ::std::vector<int> ContainerType;
  283. ContainerType values;
  284. values.push_back(3);
  285. values.push_back(5);
  286. values.push_back(8);
  287. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  288. const int expected_values[] = {3, 5, 8};
  289. VerifyGenerator(gen, expected_values);
  290. }
  291. // Edge case. Tests that ValuesIn() provided with an iterator range specifying a
  292. // single value generates a single-element sequence.
  293. TEST(ValuesInTest, ValuesInSingleElementIteratorRange) {
  294. typedef ::std::vector<int> ContainerType;
  295. ContainerType values;
  296. values.push_back(42);
  297. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  298. const int expected_values[] = {42};
  299. VerifyGenerator(gen, expected_values);
  300. }
  301. // Edge case. Tests that ValuesIn() provided with an empty iterator range
  302. // generates an empty sequence.
  303. TEST(ValuesInTest, ValuesInEmptyIteratorRange) {
  304. typedef ::std::vector<int> ContainerType;
  305. ContainerType values;
  306. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  307. VerifyGeneratorIsEmpty(gen);
  308. }
  309. // Tests that the Values() generates the expected sequence.
  310. TEST(ValuesTest, ValuesWorks) {
  311. const ParamGenerator<int> gen = Values(3, 5, 8);
  312. const int expected_values[] = {3, 5, 8};
  313. VerifyGenerator(gen, expected_values);
  314. }
  315. // Tests that Values() generates the expected sequences from elements of
  316. // different types convertible to ParamGenerator's parameter type.
  317. TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
  318. const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);
  319. const double expected_values[] = {3.0, 5.0, 8.0};
  320. VerifyGenerator(gen, expected_values);
  321. }
  322. TEST(ValuesTest, ValuesWorksForMaxLengthList) {
  323. const ParamGenerator<int> gen =
  324. Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
  325. 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
  326. 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
  327. 420, 430, 440, 450, 460, 470, 480, 490, 500);
  328. const int expected_values[] = {
  329. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,
  330. 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
  331. 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
  332. 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
  333. VerifyGenerator(gen, expected_values);
  334. }
  335. // Edge case test. Tests that single-parameter Values() generates the sequence
  336. // with the single value.
  337. TEST(ValuesTest, ValuesWithSingleParameter) {
  338. const ParamGenerator<int> gen = Values(42);
  339. const int expected_values[] = {42};
  340. VerifyGenerator(gen, expected_values);
  341. }
  342. // Tests that Bool() generates sequence (false, true).
  343. TEST(BoolTest, BoolWorks) {
  344. const ParamGenerator<bool> gen = Bool();
  345. const bool expected_values[] = {false, true};
  346. VerifyGenerator(gen, expected_values);
  347. }
  348. // Tests that Combine() with two parameters generates the expected sequence.
  349. TEST(CombineTest, CombineWithTwoParameters) {
  350. const char* foo = "foo";
  351. const char* bar = "bar";
  352. const ParamGenerator<std::tuple<const char*, int>> gen =
  353. Combine(Values(foo, bar), Values(3, 4));
  354. std::tuple<const char*, int> expected_values[] = {
  355. std::make_tuple(foo, 3), std::make_tuple(foo, 4), std::make_tuple(bar, 3),
  356. std::make_tuple(bar, 4)};
  357. VerifyGenerator(gen, expected_values);
  358. }
  359. // Tests that Combine() with three parameters generates the expected sequence.
  360. TEST(CombineTest, CombineWithThreeParameters) {
  361. const ParamGenerator<std::tuple<int, int, int>> gen =
  362. Combine(Values(0, 1), Values(3, 4), Values(5, 6));
  363. std::tuple<int, int, int> expected_values[] = {
  364. std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6),
  365. std::make_tuple(0, 4, 5), std::make_tuple(0, 4, 6),
  366. std::make_tuple(1, 3, 5), std::make_tuple(1, 3, 6),
  367. std::make_tuple(1, 4, 5), std::make_tuple(1, 4, 6)};
  368. VerifyGenerator(gen, expected_values);
  369. }
  370. // Tests that the Combine() with the first parameter generating a single value
  371. // sequence generates a sequence with the number of elements equal to the
  372. // number of elements in the sequence generated by the second parameter.
  373. TEST(CombineTest, CombineWithFirstParameterSingleValue) {
  374. const ParamGenerator<std::tuple<int, int>> gen =
  375. Combine(Values(42), Values(0, 1));
  376. std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),
  377. std::make_tuple(42, 1)};
  378. VerifyGenerator(gen, expected_values);
  379. }
  380. // Tests that the Combine() with the second parameter generating a single value
  381. // sequence generates a sequence with the number of elements equal to the
  382. // number of elements in the sequence generated by the first parameter.
  383. TEST(CombineTest, CombineWithSecondParameterSingleValue) {
  384. const ParamGenerator<std::tuple<int, int>> gen =
  385. Combine(Values(0, 1), Values(42));
  386. std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),
  387. std::make_tuple(1, 42)};
  388. VerifyGenerator(gen, expected_values);
  389. }
  390. // Tests that when the first parameter produces an empty sequence,
  391. // Combine() produces an empty sequence, too.
  392. TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
  393. const ParamGenerator<std::tuple<int, int>> gen =
  394. Combine(Range(0, 0), Values(0, 1));
  395. VerifyGeneratorIsEmpty(gen);
  396. }
  397. // Tests that when the second parameter produces an empty sequence,
  398. // Combine() produces an empty sequence, too.
  399. TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
  400. const ParamGenerator<std::tuple<int, int>> gen =
  401. Combine(Values(0, 1), Range(1, 1));
  402. VerifyGeneratorIsEmpty(gen);
  403. }
  404. // Edge case. Tests that combine works with the maximum number
  405. // of parameters supported by Google Test (currently 10).
  406. TEST(CombineTest, CombineWithMaxNumberOfParameters) {
  407. const char* foo = "foo";
  408. const char* bar = "bar";
  409. const ParamGenerator<
  410. std::tuple<const char*, int, int, int, int, int, int, int, int, int>>
  411. gen =
  412. Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),
  413. Values(5), Values(6), Values(7), Values(8), Values(9));
  414. std::tuple<const char*, int, int, int, int, int, int, int, int, int>
  415. expected_values[] = {std::make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
  416. std::make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
  417. VerifyGenerator(gen, expected_values);
  418. }
  419. class NonDefaultConstructAssignString {
  420. public:
  421. NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
  422. NonDefaultConstructAssignString() = delete;
  423. NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =
  424. default;
  425. NonDefaultConstructAssignString& operator=(
  426. const NonDefaultConstructAssignString&) = delete;
  427. ~NonDefaultConstructAssignString() = default;
  428. const std::string& str() const { return str_; }
  429. private:
  430. std::string str_;
  431. };
  432. TEST(CombineTest, NonDefaultConstructAssign) {
  433. const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>> gen =
  434. Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
  435. NonDefaultConstructAssignString("B")));
  436. ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>>::iterator
  437. it = gen.begin();
  438. EXPECT_EQ(0, std::get<0>(*it));
  439. EXPECT_EQ("A", std::get<1>(*it).str());
  440. ++it;
  441. EXPECT_EQ(0, std::get<0>(*it));
  442. EXPECT_EQ("B", std::get<1>(*it).str());
  443. ++it;
  444. EXPECT_EQ(1, std::get<0>(*it));
  445. EXPECT_EQ("A", std::get<1>(*it).str());
  446. ++it;
  447. EXPECT_EQ(1, std::get<0>(*it));
  448. EXPECT_EQ("B", std::get<1>(*it).str());
  449. ++it;
  450. EXPECT_TRUE(it == gen.end());
  451. }
  452. template <typename T>
  453. class ConstructFromT {
  454. public:
  455. explicit ConstructFromT(const T& t) : t_(t) {}
  456. template <typename... Args,
  457. typename std::enable_if<sizeof...(Args) != 1, int>::type = 0>
  458. ConstructFromT(Args&&... args) : t_(std::forward<Args>(args)...) {}
  459. bool operator==(const ConstructFromT& other) const { return other.t_ == t_; }
  460. const T& get() const { return t_; }
  461. private:
  462. T t_;
  463. };
  464. TEST(ConvertTest, CombineWithTwoParameters) {
  465. const char* foo = "foo";
  466. const char* bar = "bar";
  467. const ParamGenerator<ConstructFromT<std::tuple<const char*, int>>> gen =
  468. ConvertGenerator<std::tuple<const char*, int>>(
  469. Combine(Values(foo, bar), Values(3, 4)));
  470. ConstructFromT<std::tuple<const char*, int>> expected_values[] = {
  471. {foo, 3}, {foo, 4}, {bar, 3}, {bar, 4}};
  472. VerifyGenerator(gen, expected_values);
  473. }
  474. TEST(ConvertTest, NonDefaultConstructAssign) {
  475. const ParamGenerator<
  476. ConstructFromT<std::tuple<int, NonDefaultConstructAssignString>>>
  477. gen = ConvertGenerator<std::tuple<int, NonDefaultConstructAssignString>>(
  478. Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
  479. NonDefaultConstructAssignString("B"))));
  480. ParamGenerator<ConstructFromT<
  481. std::tuple<int, NonDefaultConstructAssignString>>>::iterator it =
  482. gen.begin();
  483. EXPECT_EQ(0, std::get<0>(it->get()));
  484. EXPECT_EQ("A", std::get<1>(it->get()).str());
  485. ++it;
  486. EXPECT_EQ(0, std::get<0>(it->get()));
  487. EXPECT_EQ("B", std::get<1>(it->get()).str());
  488. ++it;
  489. EXPECT_EQ(1, std::get<0>(it->get()));
  490. EXPECT_EQ("A", std::get<1>(it->get()).str());
  491. ++it;
  492. EXPECT_EQ(1, std::get<0>(it->get()));
  493. EXPECT_EQ("B", std::get<1>(it->get()).str());
  494. ++it;
  495. EXPECT_TRUE(it == gen.end());
  496. }
  497. TEST(ConvertTest, WithConverterLambdaAndDeducedType) {
  498. const ParamGenerator<ConstructFromT<int8_t>> gen =
  499. ConvertGenerator(Values("0", std::string("1")), [](const std::string& s) {
  500. size_t pos;
  501. int64_t value = std::stoll(s, &pos);
  502. EXPECT_EQ(pos, s.size());
  503. return value;
  504. });
  505. ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
  506. ConstructFromT<int8_t>(1)};
  507. VerifyGenerator(gen, expected_values);
  508. }
  509. TEST(ConvertTest, WithConverterLambdaAndExplicitType) {
  510. auto convert_generator = ConvertGenerator<std::string>(
  511. Values("0", std::string("1")), [](std::string_view s) {
  512. size_t pos;
  513. int64_t value = std::stoll(std::string(s), &pos);
  514. EXPECT_EQ(pos, s.size());
  515. return value;
  516. });
  517. constexpr bool is_correct_type = std::is_same_v<
  518. decltype(convert_generator),
  519. testing::internal::ParamConverterGenerator<
  520. std::string, std::function<int64_t(std::string_view)>>>;
  521. EXPECT_TRUE(is_correct_type);
  522. const ParamGenerator<ConstructFromT<int8_t>> gen = convert_generator;
  523. ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
  524. ConstructFromT<int8_t>(1)};
  525. VerifyGenerator(gen, expected_values);
  526. }
  527. TEST(ConvertTest, WithConverterFunctionPointer) {
  528. int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
  529. size_t pos;
  530. int64_t value = std::stoll(s, &pos);
  531. EXPECT_EQ(pos, s.size());
  532. return value;
  533. };
  534. const ParamGenerator<ConstructFromT<int8_t>> gen =
  535. ConvertGenerator(Values("0", std::string("1")), func_ptr);
  536. ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
  537. ConstructFromT<int8_t>(1)};
  538. VerifyGenerator(gen, expected_values);
  539. }
  540. TEST(ConvertTest, WithConverterFunctionReference) {
  541. int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
  542. size_t pos;
  543. int64_t value = std::stoll(s, &pos);
  544. EXPECT_EQ(pos, s.size());
  545. return value;
  546. };
  547. int64_t (&func_ref)(const std::string&) = *func_ptr;
  548. const ParamGenerator<ConstructFromT<int8_t>> gen =
  549. ConvertGenerator(Values("0", std::string("1")), func_ref);
  550. ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
  551. ConstructFromT<int8_t>(1)};
  552. VerifyGenerator(gen, expected_values);
  553. }
  554. // Tests that an generator produces correct sequence after being
  555. // assigned from another generator.
  556. TEST(ParamGeneratorTest, AssignmentWorks) {
  557. ParamGenerator<int> gen = Values(1, 2);
  558. const ParamGenerator<int> gen2 = Values(3, 4);
  559. gen = gen2;
  560. const int expected_values[] = {3, 4};
  561. VerifyGenerator(gen, expected_values);
  562. }
  563. // This test verifies that the tests are expanded and run as specified:
  564. // one test per element from the sequence produced by the generator
  565. // specified in INSTANTIATE_TEST_SUITE_P. It also verifies that the test's
  566. // fixture constructor, SetUp(), and TearDown() have run and have been
  567. // supplied with the correct parameters.
  568. // The use of environment object allows detection of the case where no test
  569. // case functionality is run at all. In this case TearDownTestSuite will not
  570. // be able to detect missing tests, naturally.
  571. template <int kExpectedCalls>
  572. class TestGenerationEnvironment : public ::testing::Environment {
  573. public:
  574. static TestGenerationEnvironment* Instance() {
  575. static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
  576. return instance;
  577. }
  578. void FixtureConstructorExecuted() { fixture_constructor_count_++; }
  579. void SetUpExecuted() { set_up_count_++; }
  580. void TearDownExecuted() { tear_down_count_++; }
  581. void TestBodyExecuted() { test_body_count_++; }
  582. void TearDown() override {
  583. // If all MultipleTestGenerationTest tests have been de-selected
  584. // by the filter flag, the following checks make no sense.
  585. bool perform_check = false;
  586. for (int i = 0; i < kExpectedCalls; ++i) {
  587. Message msg;
  588. msg << "TestsExpandedAndRun/" << i;
  589. if (UnitTestOptions::FilterMatchesTest(
  590. "TestExpansionModule/MultipleTestGenerationTest",
  591. msg.GetString().c_str())) {
  592. perform_check = true;
  593. }
  594. }
  595. if (perform_check) {
  596. EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)
  597. << "Fixture constructor of ParamTestGenerationTest test case "
  598. << "has not been run as expected.";
  599. EXPECT_EQ(kExpectedCalls, set_up_count_)
  600. << "Fixture SetUp method of ParamTestGenerationTest test case "
  601. << "has not been run as expected.";
  602. EXPECT_EQ(kExpectedCalls, tear_down_count_)
  603. << "Fixture TearDown method of ParamTestGenerationTest test case "
  604. << "has not been run as expected.";
  605. EXPECT_EQ(kExpectedCalls, test_body_count_)
  606. << "Test in ParamTestGenerationTest test case "
  607. << "has not been run as expected.";
  608. }
  609. }
  610. private:
  611. TestGenerationEnvironment()
  612. : fixture_constructor_count_(0),
  613. set_up_count_(0),
  614. tear_down_count_(0),
  615. test_body_count_(0) {}
  616. int fixture_constructor_count_;
  617. int set_up_count_;
  618. int tear_down_count_;
  619. int test_body_count_;
  620. TestGenerationEnvironment(const TestGenerationEnvironment&) = delete;
  621. TestGenerationEnvironment& operator=(const TestGenerationEnvironment&) =
  622. delete;
  623. };
  624. const int test_generation_params[] = {36, 42, 72};
  625. class TestGenerationTest : public TestWithParam<int> {
  626. public:
  627. enum {
  628. PARAMETER_COUNT =
  629. sizeof(test_generation_params) / sizeof(test_generation_params[0])
  630. };
  631. typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
  632. TestGenerationTest() {
  633. Environment::Instance()->FixtureConstructorExecuted();
  634. current_parameter_ = GetParam();
  635. }
  636. void SetUp() override {
  637. Environment::Instance()->SetUpExecuted();
  638. EXPECT_EQ(current_parameter_, GetParam());
  639. }
  640. void TearDown() override {
  641. Environment::Instance()->TearDownExecuted();
  642. EXPECT_EQ(current_parameter_, GetParam());
  643. }
  644. static void SetUpTestSuite() {
  645. bool all_tests_in_test_case_selected = true;
  646. for (int i = 0; i < PARAMETER_COUNT; ++i) {
  647. Message test_name;
  648. test_name << "TestsExpandedAndRun/" << i;
  649. if (!UnitTestOptions::FilterMatchesTest(
  650. "TestExpansionModule/MultipleTestGenerationTest",
  651. test_name.GetString())) {
  652. all_tests_in_test_case_selected = false;
  653. }
  654. }
  655. EXPECT_TRUE(all_tests_in_test_case_selected)
  656. << "When running the TestGenerationTest test case all of its tests\n"
  657. << "must be selected by the filter flag for the test case to pass.\n"
  658. << "If not all of them are enabled, we can't reliably conclude\n"
  659. << "that the correct number of tests have been generated.";
  660. collected_parameters_.clear();
  661. }
  662. static void TearDownTestSuite() {
  663. vector<int> expected_values(test_generation_params,
  664. test_generation_params + PARAMETER_COUNT);
  665. // Test execution order is not guaranteed by Google Test,
  666. // so the order of values in collected_parameters_ can be
  667. // different and we have to sort to compare.
  668. sort(expected_values.begin(), expected_values.end());
  669. sort(collected_parameters_.begin(), collected_parameters_.end());
  670. EXPECT_TRUE(collected_parameters_ == expected_values);
  671. }
  672. protected:
  673. int current_parameter_;
  674. static vector<int> collected_parameters_;
  675. private:
  676. TestGenerationTest(const TestGenerationTest&) = delete;
  677. TestGenerationTest& operator=(const TestGenerationTest&) = delete;
  678. };
  679. vector<int> TestGenerationTest::collected_parameters_;
  680. TEST_P(TestGenerationTest, TestsExpandedAndRun) {
  681. Environment::Instance()->TestBodyExecuted();
  682. EXPECT_EQ(current_parameter_, GetParam());
  683. collected_parameters_.push_back(GetParam());
  684. }
  685. INSTANTIATE_TEST_SUITE_P(TestExpansionModule, TestGenerationTest,
  686. ValuesIn(test_generation_params));
  687. // This test verifies that the element sequence (third parameter of
  688. // INSTANTIATE_TEST_SUITE_P) is evaluated in InitGoogleTest() and neither at
  689. // the call site of INSTANTIATE_TEST_SUITE_P nor in RUN_ALL_TESTS(). For
  690. // that, we declare param_value_ to be a static member of
  691. // GeneratorEvaluationTest and initialize it to 0. We set it to 1 in
  692. // main(), just before invocation of InitGoogleTest(). After calling
  693. // InitGoogleTest(), we set the value to 2. If the sequence is evaluated
  694. // before or after InitGoogleTest, INSTANTIATE_TEST_SUITE_P will create a
  695. // test with parameter other than 1, and the test body will fail the
  696. // assertion.
  697. class GeneratorEvaluationTest : public TestWithParam<int> {
  698. public:
  699. static int param_value() { return param_value_; }
  700. static void set_param_value(int param_value) { param_value_ = param_value; }
  701. private:
  702. static int param_value_;
  703. };
  704. int GeneratorEvaluationTest::param_value_ = 0;
  705. TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
  706. EXPECT_EQ(1, GetParam());
  707. }
  708. INSTANTIATE_TEST_SUITE_P(GenEvalModule, GeneratorEvaluationTest,
  709. Values(GeneratorEvaluationTest::param_value()));
  710. // Tests that generators defined in a different translation unit are
  711. // functional. Generator extern_gen is defined in gtest-param-test_test2.cc.
  712. extern ParamGenerator<int> extern_gen;
  713. class ExternalGeneratorTest : public TestWithParam<int> {};
  714. TEST_P(ExternalGeneratorTest, ExternalGenerator) {
  715. // Sequence produced by extern_gen contains only a single value
  716. // which we verify here.
  717. EXPECT_EQ(GetParam(), 33);
  718. }
  719. INSTANTIATE_TEST_SUITE_P(ExternalGeneratorModule, ExternalGeneratorTest,
  720. extern_gen);
  721. // Tests that a parameterized test case can be defined in one translation
  722. // unit and instantiated in another. This test will be instantiated in
  723. // gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is
  724. // defined in gtest-param-test_test.h.
  725. TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
  726. EXPECT_EQ(0, GetParam() % 33);
  727. }
  728. // Tests that a parameterized test case can be instantiated with multiple
  729. // generators.
  730. class MultipleInstantiationTest : public TestWithParam<int> {};
  731. TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}
  732. INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
  733. INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
  734. // Tests that a parameterized test case can be instantiated
  735. // in multiple translation units. This test will be instantiated
  736. // here and in gtest-param-test_test2.cc.
  737. // InstantiationInMultipleTranslationUnitsTest fixture class
  738. // is defined in gtest-param-test_test.h.
  739. TEST_P(InstantiationInMultipleTranslationUnitsTest, IsMultipleOf42) {
  740. EXPECT_EQ(0, GetParam() % 42);
  741. }
  742. INSTANTIATE_TEST_SUITE_P(Sequence1, InstantiationInMultipleTranslationUnitsTest,
  743. Values(42, 42 * 2));
  744. // Tests that each iteration of parameterized test runs in a separate test
  745. // object.
  746. class SeparateInstanceTest : public TestWithParam<int> {
  747. public:
  748. SeparateInstanceTest() : count_(0) {}
  749. static void TearDownTestSuite() {
  750. EXPECT_GE(global_count_, 2)
  751. << "If some (but not all) SeparateInstanceTest tests have been "
  752. << "filtered out this test will fail. Make sure that all "
  753. << "GeneratorEvaluationTest are selected or de-selected together "
  754. << "by the test filter.";
  755. }
  756. protected:
  757. int count_;
  758. static int global_count_;
  759. };
  760. int SeparateInstanceTest::global_count_ = 0;
  761. TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
  762. EXPECT_EQ(0, count_++);
  763. global_count_++;
  764. }
  765. INSTANTIATE_TEST_SUITE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
  766. // Tests that all instantiations of a test have named appropriately. Test
  767. // defined with TEST_P(TestSuiteName, TestName) and instantiated with
  768. // INSTANTIATE_TEST_SUITE_P(SequenceName, TestSuiteName, generator) must be
  769. // named SequenceName/TestSuiteName.TestName/i, where i is the 0-based index of
  770. // the sequence element used to instantiate the test.
  771. class NamingTest : public TestWithParam<int> {};
  772. TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
  773. const ::testing::TestInfo* const test_info =
  774. ::testing::UnitTest::GetInstance()->current_test_info();
  775. EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name());
  776. Message index_stream;
  777. index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
  778. EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
  779. EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
  780. }
  781. INSTANTIATE_TEST_SUITE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
  782. // Tests that macros in test names are expanded correctly.
  783. class MacroNamingTest : public TestWithParam<int> {};
  784. #define PREFIX_WITH_FOO(test_name) Foo##test_name
  785. #define PREFIX_WITH_MACRO(test_name) Macro##test_name
  786. TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {
  787. const ::testing::TestInfo* const test_info =
  788. ::testing::UnitTest::GetInstance()->current_test_info();
  789. EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name());
  790. EXPECT_STREQ("FooSomeTestName/0", test_info->name());
  791. }
  792. INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42));
  793. // Tests the same thing for non-parametrized tests.
  794. class MacroNamingTestNonParametrized : public ::testing::Test {};
  795. TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized),
  796. PREFIX_WITH_FOO(SomeTestName)) {
  797. const ::testing::TestInfo* const test_info =
  798. ::testing::UnitTest::GetInstance()->current_test_info();
  799. EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name());
  800. EXPECT_STREQ("FooSomeTestName", test_info->name());
  801. }
  802. TEST(MacroNameing, LookupNames) {
  803. std::set<std::string> know_suite_names, know_test_names;
  804. const auto& ins = testing::UnitTest::GetInstance();
  805. int ts = 0;
  806. while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) {
  807. know_suite_names.insert(suite->name());
  808. int ti = 0;
  809. while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) {
  810. know_test_names.insert(std::string(suite->name()) + "." + info->name());
  811. }
  812. }
  813. // Check that the expected form of the test suit name actually exists.
  814. EXPECT_NE( //
  815. know_suite_names.find("FortyTwo/MacroNamingTest"),
  816. know_suite_names.end());
  817. EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
  818. know_suite_names.end());
  819. // Check that the expected form of the test name actually exists.
  820. EXPECT_NE( //
  821. know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
  822. know_test_names.end());
  823. EXPECT_NE(
  824. know_test_names.find("MacroNamingTestNonParametrized.FooSomeTestName"),
  825. know_test_names.end());
  826. }
  827. // Tests that user supplied custom parameter names are working correctly.
  828. // Runs the test with a builtin helper method which uses PrintToString,
  829. // as well as a custom function and custom functor to ensure all possible
  830. // uses work correctly.
  831. class CustomFunctorNamingTest : public TestWithParam<std::string> {};
  832. TEST_P(CustomFunctorNamingTest, CustomTestNames) {}
  833. struct CustomParamNameFunctor {
  834. std::string operator()(const ::testing::TestParamInfo<std::string>& inf) {
  835. return inf.param;
  836. }
  837. };
  838. INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctor, CustomFunctorNamingTest,
  839. Values(std::string("FunctorName")),
  840. CustomParamNameFunctor());
  841. INSTANTIATE_TEST_SUITE_P(AllAllowedCharacters, CustomFunctorNamingTest,
  842. Values("abcdefghijklmnopqrstuvwxyz",
  843. "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "01234567890_"),
  844. CustomParamNameFunctor());
  845. inline std::string CustomParamNameFunction(
  846. const ::testing::TestParamInfo<std::string>& inf) {
  847. return inf.param;
  848. }
  849. class CustomFunctionNamingTest : public TestWithParam<std::string> {};
  850. TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
  851. INSTANTIATE_TEST_SUITE_P(CustomParamNameFunction, CustomFunctionNamingTest,
  852. Values(std::string("FunctionName")),
  853. CustomParamNameFunction);
  854. INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctionP, CustomFunctionNamingTest,
  855. Values(std::string("FunctionNameP")),
  856. &CustomParamNameFunction);
  857. // Test custom naming with a lambda
  858. class CustomLambdaNamingTest : public TestWithParam<std::string> {};
  859. TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
  860. INSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest,
  861. Values(std::string("LambdaName")),
  862. [](const ::testing::TestParamInfo<std::string>& inf) {
  863. return inf.param;
  864. });
  865. TEST(CustomNamingTest, CheckNameRegistry) {
  866. const auto& unit_test = ::testing::UnitTest::GetInstance();
  867. std::set<std::string> test_names;
  868. for (int suite_num = 0; suite_num < unit_test->total_test_suite_count();
  869. ++suite_num) {
  870. const ::testing::TestSuite* test_suite = unit_test->GetTestSuite(suite_num);
  871. for (int test_num = 0; test_num < test_suite->total_test_count();
  872. ++test_num) {
  873. const ::testing::TestInfo* test_info = test_suite->GetTestInfo(test_num);
  874. test_names.insert(std::string(test_info->name()));
  875. }
  876. }
  877. EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName"));
  878. EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName"));
  879. EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionNameP"));
  880. EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName"));
  881. }
  882. // Test a numeric name to ensure PrintToStringParamName works correctly.
  883. class CustomIntegerNamingTest : public TestWithParam<int> {};
  884. TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
  885. const ::testing::TestInfo* const test_info =
  886. ::testing::UnitTest::GetInstance()->current_test_info();
  887. Message test_name_stream;
  888. test_name_stream << "TestsReportCorrectNames/" << GetParam();
  889. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  890. }
  891. INSTANTIATE_TEST_SUITE_P(PrintToString, CustomIntegerNamingTest, Range(0, 5),
  892. ::testing::PrintToStringParamName());
  893. // Test a custom struct with PrintToString.
  894. struct CustomStruct {
  895. explicit CustomStruct(int value) : x(value) {}
  896. int x;
  897. };
  898. std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
  899. stream << val.x;
  900. return stream;
  901. }
  902. class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
  903. TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
  904. const ::testing::TestInfo* const test_info =
  905. ::testing::UnitTest::GetInstance()->current_test_info();
  906. Message test_name_stream;
  907. test_name_stream << "TestsReportCorrectNames/" << GetParam();
  908. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  909. }
  910. INSTANTIATE_TEST_SUITE_P(PrintToString, CustomStructNamingTest,
  911. Values(CustomStruct(0), CustomStruct(1)),
  912. ::testing::PrintToStringParamName());
  913. // Test that using a stateful parameter naming function works as expected.
  914. struct StatefulNamingFunctor {
  915. StatefulNamingFunctor() : sum(0) {}
  916. std::string operator()(const ::testing::TestParamInfo<int>& info) {
  917. int value = info.param + sum;
  918. sum += info.param;
  919. return ::testing::PrintToString(value);
  920. }
  921. int sum;
  922. };
  923. class StatefulNamingTest : public ::testing::TestWithParam<int> {
  924. protected:
  925. StatefulNamingTest() : sum_(0) {}
  926. int sum_;
  927. };
  928. TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
  929. const ::testing::TestInfo* const test_info =
  930. ::testing::UnitTest::GetInstance()->current_test_info();
  931. sum_ += GetParam();
  932. Message test_name_stream;
  933. test_name_stream << "TestsReportCorrectNames/" << sum_;
  934. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  935. }
  936. INSTANTIATE_TEST_SUITE_P(StatefulNamingFunctor, StatefulNamingTest, Range(0, 5),
  937. StatefulNamingFunctor());
  938. // Class that cannot be streamed into an ostream. It needs to be copyable
  939. // (and, in case of MSVC, also assignable) in order to be a test parameter
  940. // type. Its default copy constructor and assignment operator do exactly
  941. // what we need.
  942. class Unstreamable {
  943. public:
  944. explicit Unstreamable(int value) : value_(value) {}
  945. // -Wunused-private-field: dummy accessor for `value_`.
  946. const int& dummy_value() const { return value_; }
  947. private:
  948. int value_;
  949. };
  950. class CommentTest : public TestWithParam<Unstreamable> {};
  951. TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
  952. const ::testing::TestInfo* const test_info =
  953. ::testing::UnitTest::GetInstance()->current_test_info();
  954. EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
  955. }
  956. INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
  957. Values(Unstreamable(1)));
  958. // Verify that we can create a hierarchy of test fixtures, where the base
  959. // class fixture is not parameterized and the derived class is. In this case
  960. // ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We
  961. // perform simple tests on both.
  962. class NonParameterizedBaseTest : public ::testing::Test {
  963. public:
  964. NonParameterizedBaseTest() : n_(17) {}
  965. protected:
  966. int n_;
  967. };
  968. class ParameterizedDerivedTest : public NonParameterizedBaseTest,
  969. public ::testing::WithParamInterface<int> {
  970. protected:
  971. ParameterizedDerivedTest() : count_(0) {}
  972. int count_;
  973. static int global_count_;
  974. };
  975. int ParameterizedDerivedTest::global_count_ = 0;
  976. TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
  977. TEST_P(ParameterizedDerivedTest, SeesSequence) {
  978. EXPECT_EQ(17, n_);
  979. EXPECT_EQ(0, count_++);
  980. EXPECT_EQ(GetParam(), global_count_++);
  981. }
  982. class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
  983. TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
  984. EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
  985. }
  986. INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
  987. Range(0, 5));
  988. // Tests param generator working with Enums
  989. enum MyEnums {
  990. ENUM1 = 1,
  991. ENUM2 = 3,
  992. ENUM3 = 8,
  993. };
  994. class MyEnumTest : public testing::TestWithParam<MyEnums> {};
  995. TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
  996. INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,
  997. ::testing::Values(ENUM1, ENUM2, 0));
  998. namespace works_here {
  999. // Never used not instantiated, this should work.
  1000. class NotUsedTest : public testing::TestWithParam<int> {};
  1001. ///////
  1002. // Never used not instantiated, this should work.
  1003. template <typename T>
  1004. class NotUsedTypeTest : public testing::Test {};
  1005. TYPED_TEST_SUITE_P(NotUsedTypeTest);
  1006. // Used but not instantiated, this would fail. but...
  1007. class NotInstantiatedTest : public testing::TestWithParam<int> {};
  1008. // ... we mark is as allowed.
  1009. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
  1010. TEST_P(NotInstantiatedTest, Used) {}
  1011. using OtherName = NotInstantiatedTest;
  1012. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
  1013. TEST_P(OtherName, Used) {}
  1014. // Used but not instantiated, this would fail. but...
  1015. template <typename T>
  1016. class NotInstantiatedTypeTest : public testing::Test {};
  1017. TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
  1018. // ... we mark is as allowed.
  1019. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
  1020. TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
  1021. REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
  1022. } // namespace works_here
  1023. int main(int argc, char** argv) {
  1024. // Used in TestGenerationTest test suite.
  1025. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
  1026. // Used in GeneratorEvaluationTest test suite. Tests that the updated value
  1027. // will be picked up for instantiating tests in GeneratorEvaluationTest.
  1028. GeneratorEvaluationTest::set_param_value(1);
  1029. ::testing::InitGoogleTest(&argc, argv);
  1030. // Used in GeneratorEvaluationTest test suite. Tests that value updated
  1031. // here will NOT be used for instantiating tests in
  1032. // GeneratorEvaluationTest.
  1033. GeneratorEvaluationTest::set_param_value(2);
  1034. return RUN_ALL_TESTS();
  1035. }