gtest-param-test_test.cc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. // Author: vladl@google.com (Vlad Losev)
  31. //
  32. // Tests for Google Test itself. This file verifies that the parameter
  33. // generators objects produce correct parameter sequences and that
  34. // Google Test runtime instantiates correct tests from those sequences.
  35. #include "gtest/gtest.h"
  36. #if GTEST_HAS_PARAM_TEST
  37. # include <algorithm>
  38. # include <iostream>
  39. # include <list>
  40. # include <sstream>
  41. # include <string>
  42. # include <vector>
  43. // To include gtest-internal-inl.h.
  44. # define GTEST_IMPLEMENTATION_ 1
  45. # include "src/gtest-internal-inl.h" // for UnitTestOptions
  46. # undef GTEST_IMPLEMENTATION_
  47. # include "test/gtest-param-test_test.h"
  48. using ::std::vector;
  49. using ::std::sort;
  50. using ::testing::AddGlobalTestEnvironment;
  51. using ::testing::Bool;
  52. using ::testing::Message;
  53. using ::testing::Range;
  54. using ::testing::TestWithParam;
  55. using ::testing::Values;
  56. using ::testing::ValuesIn;
  57. # if GTEST_HAS_COMBINE
  58. using ::testing::Combine;
  59. using ::std::tr1::get;
  60. using ::std::tr1::make_tuple;
  61. using ::std::tr1::tuple;
  62. # endif // GTEST_HAS_COMBINE
  63. using ::testing::internal::ParamGenerator;
  64. using ::testing::internal::UnitTestOptions;
  65. // Prints a value to a string.
  66. //
  67. // TODO(wan@google.com): remove PrintValue() when we move matchers and
  68. // EXPECT_THAT() from Google Mock to Google Test. At that time, we
  69. // can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as
  70. // EXPECT_THAT() and the matchers know how to print tuples.
  71. template <typename T>
  72. ::std::string PrintValue(const T& value) {
  73. ::std::stringstream stream;
  74. stream << value;
  75. return stream.str();
  76. }
  77. # if GTEST_HAS_COMBINE
  78. // These overloads allow printing tuples in our tests. We cannot
  79. // define an operator<< for tuples, as that definition needs to be in
  80. // the std namespace in order to be picked up by Google Test via
  81. // Argument-Dependent Lookup, yet defining anything in the std
  82. // namespace in non-STL code is undefined behavior.
  83. template <typename T1, typename T2>
  84. ::std::string PrintValue(const tuple<T1, T2>& value) {
  85. ::std::stringstream stream;
  86. stream << "(" << get<0>(value) << ", " << get<1>(value) << ")";
  87. return stream.str();
  88. }
  89. template <typename T1, typename T2, typename T3>
  90. ::std::string PrintValue(const tuple<T1, T2, T3>& value) {
  91. ::std::stringstream stream;
  92. stream << "(" << get<0>(value) << ", " << get<1>(value)
  93. << ", "<< get<2>(value) << ")";
  94. return stream.str();
  95. }
  96. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  97. typename T6, typename T7, typename T8, typename T9, typename T10>
  98. ::std::string PrintValue(
  99. const tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& value) {
  100. ::std::stringstream stream;
  101. stream << "(" << get<0>(value) << ", " << get<1>(value)
  102. << ", "<< get<2>(value) << ", " << get<3>(value)
  103. << ", "<< get<4>(value) << ", " << get<5>(value)
  104. << ", "<< get<6>(value) << ", " << get<7>(value)
  105. << ", "<< get<8>(value) << ", " << get<9>(value) << ")";
  106. return stream.str();
  107. }
  108. # endif // GTEST_HAS_COMBINE
  109. // Verifies that a sequence generated by the generator and accessed
  110. // via the iterator object matches the expected one using Google Test
  111. // assertions.
  112. template <typename T, size_t N>
  113. void VerifyGenerator(const ParamGenerator<T>& generator,
  114. const T (&expected_values)[N]) {
  115. typename ParamGenerator<T>::iterator it = generator.begin();
  116. for (size_t i = 0; i < N; ++i) {
  117. ASSERT_FALSE(it == generator.end())
  118. << "At element " << i << " when accessing via an iterator "
  119. << "created with the copy constructor.\n";
  120. // We cannot use EXPECT_EQ() here as the values may be tuples,
  121. // which don't support <<.
  122. EXPECT_TRUE(expected_values[i] == *it)
  123. << "where i is " << i
  124. << ", expected_values[i] is " << PrintValue(expected_values[i])
  125. << ", *it is " << PrintValue(*it)
  126. << ", and 'it' is an iterator created with the copy constructor.\n";
  127. it++;
  128. }
  129. EXPECT_TRUE(it == generator.end())
  130. << "At the presumed end of sequence when accessing via an iterator "
  131. << "created with the copy constructor.\n";
  132. // Test the iterator assignment. The following lines verify that
  133. // the sequence accessed via an iterator initialized via the
  134. // assignment operator (as opposed to a copy constructor) matches
  135. // just the same.
  136. it = generator.begin();
  137. for (size_t i = 0; i < N; ++i) {
  138. ASSERT_FALSE(it == generator.end())
  139. << "At element " << i << " when accessing via an iterator "
  140. << "created with the assignment operator.\n";
  141. EXPECT_TRUE(expected_values[i] == *it)
  142. << "where i is " << i
  143. << ", expected_values[i] is " << PrintValue(expected_values[i])
  144. << ", *it is " << PrintValue(*it)
  145. << ", and 'it' is an iterator created with the copy constructor.\n";
  146. it++;
  147. }
  148. EXPECT_TRUE(it == generator.end())
  149. << "At the presumed end of sequence when accessing via an iterator "
  150. << "created with the assignment operator.\n";
  151. }
  152. template <typename T>
  153. void VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {
  154. typename ParamGenerator<T>::iterator it = generator.begin();
  155. EXPECT_TRUE(it == generator.end());
  156. it = generator.begin();
  157. EXPECT_TRUE(it == generator.end());
  158. }
  159. // Generator tests. They test that each of the provided generator functions
  160. // generates an expected sequence of values. The general test pattern
  161. // instantiates a generator using one of the generator functions,
  162. // checks the sequence produced by the generator using its iterator API,
  163. // and then resets the iterator back to the beginning of the sequence
  164. // and checks the sequence again.
  165. // Tests that iterators produced by generator functions conform to the
  166. // ForwardIterator concept.
  167. TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {
  168. const ParamGenerator<int> gen = Range(0, 10);
  169. ParamGenerator<int>::iterator it = gen.begin();
  170. // Verifies that iterator initialization works as expected.
  171. ParamGenerator<int>::iterator it2 = it;
  172. EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the "
  173. << "element same as its source points to";
  174. // Verifies that iterator assignment works as expected.
  175. it++;
  176. EXPECT_FALSE(*it == *it2);
  177. it2 = it;
  178. EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
  179. << "element same as its source points to";
  180. // Verifies that prefix operator++() returns *this.
  181. EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be "
  182. << "refer to the original object";
  183. // Verifies that the result of the postfix operator++ points to the value
  184. // pointed to by the original iterator.
  185. int original_value = *it; // Have to compute it outside of macro call to be
  186. // unaffected by the parameter evaluation order.
  187. EXPECT_EQ(original_value, *(it++));
  188. // Verifies that prefix and postfix operator++() advance an iterator
  189. // all the same.
  190. it2 = it;
  191. it++;
  192. ++it2;
  193. EXPECT_TRUE(*it == *it2);
  194. }
  195. // Tests that Range() generates the expected sequence.
  196. TEST(RangeTest, IntRangeWithDefaultStep) {
  197. const ParamGenerator<int> gen = Range(0, 3);
  198. const int expected_values[] = {0, 1, 2};
  199. VerifyGenerator(gen, expected_values);
  200. }
  201. // Edge case. Tests that Range() generates the single element sequence
  202. // as expected when provided with range limits that are equal.
  203. TEST(RangeTest, IntRangeSingleValue) {
  204. const ParamGenerator<int> gen = Range(0, 1);
  205. const int expected_values[] = {0};
  206. VerifyGenerator(gen, expected_values);
  207. }
  208. // Edge case. Tests that Range() with generates empty sequence when
  209. // supplied with an empty range.
  210. TEST(RangeTest, IntRangeEmpty) {
  211. const ParamGenerator<int> gen = Range(0, 0);
  212. VerifyGeneratorIsEmpty(gen);
  213. }
  214. // Tests that Range() with custom step (greater then one) generates
  215. // the expected sequence.
  216. TEST(RangeTest, IntRangeWithCustomStep) {
  217. const ParamGenerator<int> gen = Range(0, 9, 3);
  218. const int expected_values[] = {0, 3, 6};
  219. VerifyGenerator(gen, expected_values);
  220. }
  221. // Tests that Range() with custom step (greater then one) generates
  222. // the expected sequence when the last element does not fall on the
  223. // upper range limit. Sequences generated by Range() must not have
  224. // elements beyond the range limits.
  225. TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {
  226. const ParamGenerator<int> gen = Range(0, 4, 3);
  227. const int expected_values[] = {0, 3};
  228. VerifyGenerator(gen, expected_values);
  229. }
  230. // Verifies that Range works with user-defined types that define
  231. // copy constructor, operator=(), operator+(), and operator<().
  232. class DogAdder {
  233. public:
  234. explicit DogAdder(const char* a_value) : value_(a_value) {}
  235. DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
  236. DogAdder operator=(const DogAdder& other) {
  237. if (this != &other)
  238. value_ = other.value_;
  239. return *this;
  240. }
  241. DogAdder operator+(const DogAdder& other) const {
  242. Message msg;
  243. msg << value_.c_str() << other.value_.c_str();
  244. return DogAdder(msg.GetString().c_str());
  245. }
  246. bool operator<(const DogAdder& other) const {
  247. return value_ < other.value_;
  248. }
  249. const std::string& value() const { return value_; }
  250. private:
  251. std::string value_;
  252. };
  253. TEST(RangeTest, WorksWithACustomType) {
  254. const ParamGenerator<DogAdder> gen =
  255. Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
  256. ParamGenerator<DogAdder>::iterator it = gen.begin();
  257. ASSERT_FALSE(it == gen.end());
  258. EXPECT_STREQ("cat", it->value().c_str());
  259. ASSERT_FALSE(++it == gen.end());
  260. EXPECT_STREQ("catdog", it->value().c_str());
  261. EXPECT_TRUE(++it == gen.end());
  262. }
  263. class IntWrapper {
  264. public:
  265. explicit IntWrapper(int a_value) : value_(a_value) {}
  266. IntWrapper(const IntWrapper& other) : value_(other.value_) {}
  267. IntWrapper operator=(const IntWrapper& other) {
  268. value_ = other.value_;
  269. return *this;
  270. }
  271. // operator+() adds a different type.
  272. IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }
  273. bool operator<(const IntWrapper& other) const {
  274. return value_ < other.value_;
  275. }
  276. int value() const { return value_; }
  277. private:
  278. int value_;
  279. };
  280. TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
  281. const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
  282. ParamGenerator<IntWrapper>::iterator it = gen.begin();
  283. ASSERT_FALSE(it == gen.end());
  284. EXPECT_EQ(0, it->value());
  285. ASSERT_FALSE(++it == gen.end());
  286. EXPECT_EQ(1, it->value());
  287. EXPECT_TRUE(++it == gen.end());
  288. }
  289. // Tests that ValuesIn() with an array parameter generates
  290. // the expected sequence.
  291. TEST(ValuesInTest, ValuesInArray) {
  292. int array[] = {3, 5, 8};
  293. const ParamGenerator<int> gen = ValuesIn(array);
  294. VerifyGenerator(gen, array);
  295. }
  296. // Tests that ValuesIn() with a const array parameter generates
  297. // the expected sequence.
  298. TEST(ValuesInTest, ValuesInConstArray) {
  299. const int array[] = {3, 5, 8};
  300. const ParamGenerator<int> gen = ValuesIn(array);
  301. VerifyGenerator(gen, array);
  302. }
  303. // Edge case. Tests that ValuesIn() with an array parameter containing a
  304. // single element generates the single element sequence.
  305. TEST(ValuesInTest, ValuesInSingleElementArray) {
  306. int array[] = {42};
  307. const ParamGenerator<int> gen = ValuesIn(array);
  308. VerifyGenerator(gen, array);
  309. }
  310. // Tests that ValuesIn() generates the expected sequence for an STL
  311. // container (vector).
  312. TEST(ValuesInTest, ValuesInVector) {
  313. typedef ::std::vector<int> ContainerType;
  314. ContainerType values;
  315. values.push_back(3);
  316. values.push_back(5);
  317. values.push_back(8);
  318. const ParamGenerator<int> gen = ValuesIn(values);
  319. const int expected_values[] = {3, 5, 8};
  320. VerifyGenerator(gen, expected_values);
  321. }
  322. // Tests that ValuesIn() generates the expected sequence.
  323. TEST(ValuesInTest, ValuesInIteratorRange) {
  324. typedef ::std::vector<int> ContainerType;
  325. ContainerType values;
  326. values.push_back(3);
  327. values.push_back(5);
  328. values.push_back(8);
  329. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  330. const int expected_values[] = {3, 5, 8};
  331. VerifyGenerator(gen, expected_values);
  332. }
  333. // Edge case. Tests that ValuesIn() provided with an iterator range specifying a
  334. // single value generates a single-element sequence.
  335. TEST(ValuesInTest, ValuesInSingleElementIteratorRange) {
  336. typedef ::std::vector<int> ContainerType;
  337. ContainerType values;
  338. values.push_back(42);
  339. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  340. const int expected_values[] = {42};
  341. VerifyGenerator(gen, expected_values);
  342. }
  343. // Edge case. Tests that ValuesIn() provided with an empty iterator range
  344. // generates an empty sequence.
  345. TEST(ValuesInTest, ValuesInEmptyIteratorRange) {
  346. typedef ::std::vector<int> ContainerType;
  347. ContainerType values;
  348. const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
  349. VerifyGeneratorIsEmpty(gen);
  350. }
  351. // Tests that the Values() generates the expected sequence.
  352. TEST(ValuesTest, ValuesWorks) {
  353. const ParamGenerator<int> gen = Values(3, 5, 8);
  354. const int expected_values[] = {3, 5, 8};
  355. VerifyGenerator(gen, expected_values);
  356. }
  357. // Tests that Values() generates the expected sequences from elements of
  358. // different types convertible to ParamGenerator's parameter type.
  359. TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
  360. const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);
  361. const double expected_values[] = {3.0, 5.0, 8.0};
  362. VerifyGenerator(gen, expected_values);
  363. }
  364. TEST(ValuesTest, ValuesWorksForMaxLengthList) {
  365. const ParamGenerator<int> gen = Values(
  366. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
  367. 110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
  368. 210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
  369. 310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
  370. 410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
  371. const int expected_values[] = {
  372. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
  373. 110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
  374. 210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
  375. 310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
  376. 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
  377. VerifyGenerator(gen, expected_values);
  378. }
  379. // Edge case test. Tests that single-parameter Values() generates the sequence
  380. // with the single value.
  381. TEST(ValuesTest, ValuesWithSingleParameter) {
  382. const ParamGenerator<int> gen = Values(42);
  383. const int expected_values[] = {42};
  384. VerifyGenerator(gen, expected_values);
  385. }
  386. // Tests that Bool() generates sequence (false, true).
  387. TEST(BoolTest, BoolWorks) {
  388. const ParamGenerator<bool> gen = Bool();
  389. const bool expected_values[] = {false, true};
  390. VerifyGenerator(gen, expected_values);
  391. }
  392. # if GTEST_HAS_COMBINE
  393. // Tests that Combine() with two parameters generates the expected sequence.
  394. TEST(CombineTest, CombineWithTwoParameters) {
  395. const char* foo = "foo";
  396. const char* bar = "bar";
  397. const ParamGenerator<tuple<const char*, int> > gen =
  398. Combine(Values(foo, bar), Values(3, 4));
  399. tuple<const char*, int> expected_values[] = {
  400. make_tuple(foo, 3), make_tuple(foo, 4),
  401. make_tuple(bar, 3), make_tuple(bar, 4)};
  402. VerifyGenerator(gen, expected_values);
  403. }
  404. // Tests that Combine() with three parameters generates the expected sequence.
  405. TEST(CombineTest, CombineWithThreeParameters) {
  406. const ParamGenerator<tuple<int, int, int> > gen = Combine(Values(0, 1),
  407. Values(3, 4),
  408. Values(5, 6));
  409. tuple<int, int, int> expected_values[] = {
  410. make_tuple(0, 3, 5), make_tuple(0, 3, 6),
  411. make_tuple(0, 4, 5), make_tuple(0, 4, 6),
  412. make_tuple(1, 3, 5), make_tuple(1, 3, 6),
  413. make_tuple(1, 4, 5), make_tuple(1, 4, 6)};
  414. VerifyGenerator(gen, expected_values);
  415. }
  416. // Tests that the Combine() with the first parameter generating a single value
  417. // sequence generates a sequence with the number of elements equal to the
  418. // number of elements in the sequence generated by the second parameter.
  419. TEST(CombineTest, CombineWithFirstParameterSingleValue) {
  420. const ParamGenerator<tuple<int, int> > gen = Combine(Values(42),
  421. Values(0, 1));
  422. tuple<int, int> expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)};
  423. VerifyGenerator(gen, expected_values);
  424. }
  425. // Tests that the Combine() with the second parameter generating a single value
  426. // sequence generates a sequence with the number of elements equal to the
  427. // number of elements in the sequence generated by the first parameter.
  428. TEST(CombineTest, CombineWithSecondParameterSingleValue) {
  429. const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
  430. Values(42));
  431. tuple<int, int> expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)};
  432. VerifyGenerator(gen, expected_values);
  433. }
  434. // Tests that when the first parameter produces an empty sequence,
  435. // Combine() produces an empty sequence, too.
  436. TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
  437. const ParamGenerator<tuple<int, int> > gen = Combine(Range(0, 0),
  438. Values(0, 1));
  439. VerifyGeneratorIsEmpty(gen);
  440. }
  441. // Tests that when the second parameter produces an empty sequence,
  442. // Combine() produces an empty sequence, too.
  443. TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
  444. const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
  445. Range(1, 1));
  446. VerifyGeneratorIsEmpty(gen);
  447. }
  448. // Edge case. Tests that combine works with the maximum number
  449. // of parameters supported by Google Test (currently 10).
  450. TEST(CombineTest, CombineWithMaxNumberOfParameters) {
  451. const char* foo = "foo";
  452. const char* bar = "bar";
  453. const ParamGenerator<tuple<const char*, int, int, int, int, int, int, int,
  454. int, int> > gen = Combine(Values(foo, bar),
  455. Values(1), Values(2),
  456. Values(3), Values(4),
  457. Values(5), Values(6),
  458. Values(7), Values(8),
  459. Values(9));
  460. tuple<const char*, int, int, int, int, int, int, int, int, int>
  461. expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
  462. make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
  463. VerifyGenerator(gen, expected_values);
  464. }
  465. # endif // GTEST_HAS_COMBINE
  466. // Tests that an generator produces correct sequence after being
  467. // assigned from another generator.
  468. TEST(ParamGeneratorTest, AssignmentWorks) {
  469. ParamGenerator<int> gen = Values(1, 2);
  470. const ParamGenerator<int> gen2 = Values(3, 4);
  471. gen = gen2;
  472. const int expected_values[] = {3, 4};
  473. VerifyGenerator(gen, expected_values);
  474. }
  475. // This test verifies that the tests are expanded and run as specified:
  476. // one test per element from the sequence produced by the generator
  477. // specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's
  478. // fixture constructor, SetUp(), and TearDown() have run and have been
  479. // supplied with the correct parameters.
  480. // The use of environment object allows detection of the case where no test
  481. // case functionality is run at all. In this case TestCaseTearDown will not
  482. // be able to detect missing tests, naturally.
  483. template <int kExpectedCalls>
  484. class TestGenerationEnvironment : public ::testing::Environment {
  485. public:
  486. static TestGenerationEnvironment* Instance() {
  487. static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
  488. return instance;
  489. }
  490. void FixtureConstructorExecuted() { fixture_constructor_count_++; }
  491. void SetUpExecuted() { set_up_count_++; }
  492. void TearDownExecuted() { tear_down_count_++; }
  493. void TestBodyExecuted() { test_body_count_++; }
  494. virtual void TearDown() {
  495. // If all MultipleTestGenerationTest tests have been de-selected
  496. // by the filter flag, the following checks make no sense.
  497. bool perform_check = false;
  498. for (int i = 0; i < kExpectedCalls; ++i) {
  499. Message msg;
  500. msg << "TestsExpandedAndRun/" << i;
  501. if (UnitTestOptions::FilterMatchesTest(
  502. "TestExpansionModule/MultipleTestGenerationTest",
  503. msg.GetString().c_str())) {
  504. perform_check = true;
  505. }
  506. }
  507. if (perform_check) {
  508. EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)
  509. << "Fixture constructor of ParamTestGenerationTest test case "
  510. << "has not been run as expected.";
  511. EXPECT_EQ(kExpectedCalls, set_up_count_)
  512. << "Fixture SetUp method of ParamTestGenerationTest test case "
  513. << "has not been run as expected.";
  514. EXPECT_EQ(kExpectedCalls, tear_down_count_)
  515. << "Fixture TearDown method of ParamTestGenerationTest test case "
  516. << "has not been run as expected.";
  517. EXPECT_EQ(kExpectedCalls, test_body_count_)
  518. << "Test in ParamTestGenerationTest test case "
  519. << "has not been run as expected.";
  520. }
  521. }
  522. private:
  523. TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
  524. tear_down_count_(0), test_body_count_(0) {}
  525. int fixture_constructor_count_;
  526. int set_up_count_;
  527. int tear_down_count_;
  528. int test_body_count_;
  529. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment);
  530. };
  531. const int test_generation_params[] = {36, 42, 72};
  532. class TestGenerationTest : public TestWithParam<int> {
  533. public:
  534. enum {
  535. PARAMETER_COUNT =
  536. sizeof(test_generation_params)/sizeof(test_generation_params[0])
  537. };
  538. typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
  539. TestGenerationTest() {
  540. Environment::Instance()->FixtureConstructorExecuted();
  541. current_parameter_ = GetParam();
  542. }
  543. virtual void SetUp() {
  544. Environment::Instance()->SetUpExecuted();
  545. EXPECT_EQ(current_parameter_, GetParam());
  546. }
  547. virtual void TearDown() {
  548. Environment::Instance()->TearDownExecuted();
  549. EXPECT_EQ(current_parameter_, GetParam());
  550. }
  551. static void SetUpTestCase() {
  552. bool all_tests_in_test_case_selected = true;
  553. for (int i = 0; i < PARAMETER_COUNT; ++i) {
  554. Message test_name;
  555. test_name << "TestsExpandedAndRun/" << i;
  556. if ( !UnitTestOptions::FilterMatchesTest(
  557. "TestExpansionModule/MultipleTestGenerationTest",
  558. test_name.GetString())) {
  559. all_tests_in_test_case_selected = false;
  560. }
  561. }
  562. EXPECT_TRUE(all_tests_in_test_case_selected)
  563. << "When running the TestGenerationTest test case all of its tests\n"
  564. << "must be selected by the filter flag for the test case to pass.\n"
  565. << "If not all of them are enabled, we can't reliably conclude\n"
  566. << "that the correct number of tests have been generated.";
  567. collected_parameters_.clear();
  568. }
  569. static void TearDownTestCase() {
  570. vector<int> expected_values(test_generation_params,
  571. test_generation_params + PARAMETER_COUNT);
  572. // Test execution order is not guaranteed by Google Test,
  573. // so the order of values in collected_parameters_ can be
  574. // different and we have to sort to compare.
  575. sort(expected_values.begin(), expected_values.end());
  576. sort(collected_parameters_.begin(), collected_parameters_.end());
  577. EXPECT_TRUE(collected_parameters_ == expected_values);
  578. }
  579. protected:
  580. int current_parameter_;
  581. static vector<int> collected_parameters_;
  582. private:
  583. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest);
  584. };
  585. vector<int> TestGenerationTest::collected_parameters_;
  586. TEST_P(TestGenerationTest, TestsExpandedAndRun) {
  587. Environment::Instance()->TestBodyExecuted();
  588. EXPECT_EQ(current_parameter_, GetParam());
  589. collected_parameters_.push_back(GetParam());
  590. }
  591. INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest,
  592. ValuesIn(test_generation_params));
  593. // This test verifies that the element sequence (third parameter of
  594. // INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at
  595. // the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For
  596. // that, we declare param_value_ to be a static member of
  597. // GeneratorEvaluationTest and initialize it to 0. We set it to 1 in
  598. // main(), just before invocation of InitGoogleTest(). After calling
  599. // InitGoogleTest(), we set the value to 2. If the sequence is evaluated
  600. // before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a
  601. // test with parameter other than 1, and the test body will fail the
  602. // assertion.
  603. class GeneratorEvaluationTest : public TestWithParam<int> {
  604. public:
  605. static int param_value() { return param_value_; }
  606. static void set_param_value(int param_value) { param_value_ = param_value; }
  607. private:
  608. static int param_value_;
  609. };
  610. int GeneratorEvaluationTest::param_value_ = 0;
  611. TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
  612. EXPECT_EQ(1, GetParam());
  613. }
  614. INSTANTIATE_TEST_CASE_P(GenEvalModule,
  615. GeneratorEvaluationTest,
  616. Values(GeneratorEvaluationTest::param_value()));
  617. // Tests that generators defined in a different translation unit are
  618. // functional. Generator extern_gen is defined in gtest-param-test_test2.cc.
  619. extern ParamGenerator<int> extern_gen;
  620. class ExternalGeneratorTest : public TestWithParam<int> {};
  621. TEST_P(ExternalGeneratorTest, ExternalGenerator) {
  622. // Sequence produced by extern_gen contains only a single value
  623. // which we verify here.
  624. EXPECT_EQ(GetParam(), 33);
  625. }
  626. INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule,
  627. ExternalGeneratorTest,
  628. extern_gen);
  629. // Tests that a parameterized test case can be defined in one translation
  630. // unit and instantiated in another. This test will be instantiated in
  631. // gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is
  632. // defined in gtest-param-test_test.h.
  633. TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
  634. EXPECT_EQ(0, GetParam() % 33);
  635. }
  636. // Tests that a parameterized test case can be instantiated with multiple
  637. // generators.
  638. class MultipleInstantiationTest : public TestWithParam<int> {};
  639. TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
  640. }
  641. INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
  642. INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
  643. // Tests that a parameterized test case can be instantiated
  644. // in multiple translation units. This test will be instantiated
  645. // here and in gtest-param-test_test2.cc.
  646. // InstantiationInMultipleTranslationUnitsTest fixture class
  647. // is defined in gtest-param-test_test.h.
  648. TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) {
  649. EXPECT_EQ(0, GetParam() % 42);
  650. }
  651. INSTANTIATE_TEST_CASE_P(Sequence1,
  652. InstantiationInMultipleTranslaionUnitsTest,
  653. Values(42, 42*2));
  654. // Tests that each iteration of parameterized test runs in a separate test
  655. // object.
  656. class SeparateInstanceTest : public TestWithParam<int> {
  657. public:
  658. SeparateInstanceTest() : count_(0) {}
  659. static void TearDownTestCase() {
  660. EXPECT_GE(global_count_, 2)
  661. << "If some (but not all) SeparateInstanceTest tests have been "
  662. << "filtered out this test will fail. Make sure that all "
  663. << "GeneratorEvaluationTest are selected or de-selected together "
  664. << "by the test filter.";
  665. }
  666. protected:
  667. int count_;
  668. static int global_count_;
  669. };
  670. int SeparateInstanceTest::global_count_ = 0;
  671. TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
  672. EXPECT_EQ(0, count_++);
  673. global_count_++;
  674. }
  675. INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
  676. // Tests that all instantiations of a test have named appropriately. Test
  677. // defined with TEST_P(TestCaseName, TestName) and instantiated with
  678. // INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named
  679. // SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the
  680. // sequence element used to instantiate the test.
  681. class NamingTest : public TestWithParam<int> {};
  682. TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
  683. const ::testing::TestInfo* const test_info =
  684. ::testing::UnitTest::GetInstance()->current_test_info();
  685. EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name());
  686. Message index_stream;
  687. index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
  688. EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
  689. EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
  690. }
  691. INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
  692. // Class that cannot be streamed into an ostream. It needs to be copyable
  693. // (and, in case of MSVC, also assignable) in order to be a test parameter
  694. // type. Its default copy constructor and assignment operator do exactly
  695. // what we need.
  696. class Unstreamable {
  697. public:
  698. explicit Unstreamable(int value) : value_(value) {}
  699. private:
  700. int value_;
  701. };
  702. class CommentTest : public TestWithParam<Unstreamable> {};
  703. TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
  704. const ::testing::TestInfo* const test_info =
  705. ::testing::UnitTest::GetInstance()->current_test_info();
  706. EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
  707. }
  708. INSTANTIATE_TEST_CASE_P(InstantiationWithComments,
  709. CommentTest,
  710. Values(Unstreamable(1)));
  711. // Verify that we can create a hierarchy of test fixtures, where the base
  712. // class fixture is not parameterized and the derived class is. In this case
  713. // ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We
  714. // perform simple tests on both.
  715. class NonParameterizedBaseTest : public ::testing::Test {
  716. public:
  717. NonParameterizedBaseTest() : n_(17) { }
  718. protected:
  719. int n_;
  720. };
  721. class ParameterizedDerivedTest : public NonParameterizedBaseTest,
  722. public ::testing::WithParamInterface<int> {
  723. protected:
  724. ParameterizedDerivedTest() : count_(0) { }
  725. int count_;
  726. static int global_count_;
  727. };
  728. int ParameterizedDerivedTest::global_count_ = 0;
  729. TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
  730. EXPECT_EQ(17, n_);
  731. }
  732. TEST_P(ParameterizedDerivedTest, SeesSequence) {
  733. EXPECT_EQ(17, n_);
  734. EXPECT_EQ(0, count_++);
  735. EXPECT_EQ(GetParam(), global_count_++);
  736. }
  737. class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
  738. TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
  739. EXPECT_DEATH_IF_SUPPORTED(GetParam(),
  740. ".* value-parameterized test .*");
  741. }
  742. INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5));
  743. #endif // GTEST_HAS_PARAM_TEST
  744. TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) {
  745. #if GTEST_HAS_COMBINE && !GTEST_HAS_PARAM_TEST
  746. FAIL() << "GTEST_HAS_COMBINE is defined while GTEST_HAS_PARAM_TEST is not\n"
  747. #endif
  748. }
  749. int main(int argc, char **argv) {
  750. #if GTEST_HAS_PARAM_TEST
  751. // Used in TestGenerationTest test case.
  752. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
  753. // Used in GeneratorEvaluationTest test case. Tests that the updated value
  754. // will be picked up for instantiating tests in GeneratorEvaluationTest.
  755. GeneratorEvaluationTest::set_param_value(1);
  756. #endif // GTEST_HAS_PARAM_TEST
  757. ::testing::InitGoogleTest(&argc, argv);
  758. #if GTEST_HAS_PARAM_TEST
  759. // Used in GeneratorEvaluationTest test case. Tests that value updated
  760. // here will NOT be used for instantiating tests in
  761. // GeneratorEvaluationTest.
  762. GeneratorEvaluationTest::set_param_value(2);
  763. #endif // GTEST_HAS_PARAM_TEST
  764. return RUN_ALL_TESTS();
  765. }