googletest-param-test-test.cc 42 KB

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