gtest-param-test_test.cc 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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 ::testing::get;
  60. using ::testing::make_tuple;
  61. using ::testing::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. // Tests that user supplied custom parameter names are working correctly.
  693. // Runs the test with a builtin helper method which uses PrintToString,
  694. // as well as a custom function and custom functor to ensure all possible
  695. // uses work correctly.
  696. class CustomFunctorNamingTest : public TestWithParam<std::string> {};
  697. TEST_P(CustomFunctorNamingTest, CustomTestNames) {}
  698. struct CustomParamNameFunctor {
  699. std::string operator()(const ::testing::TestParamInfo<std::string>& info) {
  700. return info.param;
  701. }
  702. };
  703. INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor,
  704. CustomFunctorNamingTest,
  705. Values(std::string("FunctorName")),
  706. CustomParamNameFunctor());
  707. INSTANTIATE_TEST_CASE_P(AllAllowedCharacters,
  708. CustomFunctorNamingTest,
  709. Values("abcdefghijklmnopqrstuvwxyz",
  710. "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  711. "01234567890_"),
  712. CustomParamNameFunctor());
  713. inline std::string CustomParamNameFunction(
  714. const ::testing::TestParamInfo<std::string>& info) {
  715. return info.param;
  716. }
  717. class CustomFunctionNamingTest : public TestWithParam<std::string> {};
  718. TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
  719. INSTANTIATE_TEST_CASE_P(CustomParamNameFunction,
  720. CustomFunctionNamingTest,
  721. Values(std::string("FunctionName")),
  722. CustomParamNameFunction);
  723. #if GTEST_LANG_CXX11
  724. // Test custom naming with a lambda
  725. class CustomLambdaNamingTest : public TestWithParam<std::string> {};
  726. TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
  727. INSTANTIATE_TEST_CASE_P(CustomParamNameLambda,
  728. CustomLambdaNamingTest,
  729. Values(std::string("LambdaName")),
  730. [](const ::testing::TestParamInfo<std::string>& info) {
  731. return info.param;
  732. });
  733. #endif // GTEST_LANG_CXX11
  734. TEST(CustomNamingTest, CheckNameRegistry) {
  735. ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance();
  736. std::set<std::string> test_names;
  737. for (int case_num = 0;
  738. case_num < unit_test->total_test_case_count();
  739. ++case_num) {
  740. const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num);
  741. for (int test_num = 0;
  742. test_num < test_case->total_test_count();
  743. ++test_num) {
  744. const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num);
  745. test_names.insert(std::string(test_info->name()));
  746. }
  747. }
  748. EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName"));
  749. EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName"));
  750. #if GTEST_LANG_CXX11
  751. EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName"));
  752. #endif // GTEST_LANG_CXX11
  753. }
  754. // Test a numeric name to ensure PrintToStringParamName works correctly.
  755. class CustomIntegerNamingTest : public TestWithParam<int> {};
  756. TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
  757. const ::testing::TestInfo* const test_info =
  758. ::testing::UnitTest::GetInstance()->current_test_info();
  759. Message test_name_stream;
  760. test_name_stream << "TestsReportCorrectNames/" << GetParam();
  761. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  762. }
  763. INSTANTIATE_TEST_CASE_P(PrintToString,
  764. CustomIntegerNamingTest,
  765. Range(0, 5),
  766. ::testing::PrintToStringParamName());
  767. // Test a custom struct with PrintToString.
  768. struct CustomStruct {
  769. explicit CustomStruct(int value) : x(value) {}
  770. int x;
  771. };
  772. std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
  773. stream << val.x;
  774. return stream;
  775. }
  776. class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
  777. TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
  778. const ::testing::TestInfo* const test_info =
  779. ::testing::UnitTest::GetInstance()->current_test_info();
  780. Message test_name_stream;
  781. test_name_stream << "TestsReportCorrectNames/" << GetParam();
  782. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  783. }
  784. INSTANTIATE_TEST_CASE_P(PrintToString,
  785. CustomStructNamingTest,
  786. Values(CustomStruct(0), CustomStruct(1)),
  787. ::testing::PrintToStringParamName());
  788. // Test that using a stateful parameter naming function works as expected.
  789. struct StatefulNamingFunctor {
  790. StatefulNamingFunctor() : sum(0) {}
  791. std::string operator()(const ::testing::TestParamInfo<int>& info) {
  792. int value = info.param + sum;
  793. sum += info.param;
  794. return ::testing::PrintToString(value);
  795. }
  796. int sum;
  797. };
  798. class StatefulNamingTest : public ::testing::TestWithParam<int> {
  799. protected:
  800. StatefulNamingTest() : sum_(0) {}
  801. int sum_;
  802. };
  803. TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
  804. const ::testing::TestInfo* const test_info =
  805. ::testing::UnitTest::GetInstance()->current_test_info();
  806. sum_ += GetParam();
  807. Message test_name_stream;
  808. test_name_stream << "TestsReportCorrectNames/" << sum_;
  809. EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
  810. }
  811. INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor,
  812. StatefulNamingTest,
  813. Range(0, 5),
  814. StatefulNamingFunctor());
  815. // Class that cannot be streamed into an ostream. It needs to be copyable
  816. // (and, in case of MSVC, also assignable) in order to be a test parameter
  817. // type. Its default copy constructor and assignment operator do exactly
  818. // what we need.
  819. class Unstreamable {
  820. public:
  821. explicit Unstreamable(int value) : value_(value) {}
  822. private:
  823. int value_;
  824. };
  825. class CommentTest : public TestWithParam<Unstreamable> {};
  826. TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
  827. const ::testing::TestInfo* const test_info =
  828. ::testing::UnitTest::GetInstance()->current_test_info();
  829. EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
  830. }
  831. INSTANTIATE_TEST_CASE_P(InstantiationWithComments,
  832. CommentTest,
  833. Values(Unstreamable(1)));
  834. // Verify that we can create a hierarchy of test fixtures, where the base
  835. // class fixture is not parameterized and the derived class is. In this case
  836. // ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We
  837. // perform simple tests on both.
  838. class NonParameterizedBaseTest : public ::testing::Test {
  839. public:
  840. NonParameterizedBaseTest() : n_(17) { }
  841. protected:
  842. int n_;
  843. };
  844. class ParameterizedDerivedTest : public NonParameterizedBaseTest,
  845. public ::testing::WithParamInterface<int> {
  846. protected:
  847. ParameterizedDerivedTest() : count_(0) { }
  848. int count_;
  849. static int global_count_;
  850. };
  851. int ParameterizedDerivedTest::global_count_ = 0;
  852. TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
  853. EXPECT_EQ(17, n_);
  854. }
  855. TEST_P(ParameterizedDerivedTest, SeesSequence) {
  856. EXPECT_EQ(17, n_);
  857. EXPECT_EQ(0, count_++);
  858. EXPECT_EQ(GetParam(), global_count_++);
  859. }
  860. class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
  861. TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
  862. EXPECT_DEATH_IF_SUPPORTED(GetParam(),
  863. ".* value-parameterized test .*");
  864. }
  865. INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5));
  866. #endif // GTEST_HAS_PARAM_TEST
  867. TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) {
  868. #if GTEST_HAS_COMBINE && !GTEST_HAS_PARAM_TEST
  869. FAIL() << "GTEST_HAS_COMBINE is defined while GTEST_HAS_PARAM_TEST is not\n"
  870. #endif
  871. }
  872. int main(int argc, char **argv) {
  873. #if GTEST_HAS_PARAM_TEST
  874. // Used in TestGenerationTest test case.
  875. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
  876. // Used in GeneratorEvaluationTest test case. Tests that the updated value
  877. // will be picked up for instantiating tests in GeneratorEvaluationTest.
  878. GeneratorEvaluationTest::set_param_value(1);
  879. #endif // GTEST_HAS_PARAM_TEST
  880. ::testing::InitGoogleTest(&argc, argv);
  881. #if GTEST_HAS_PARAM_TEST
  882. // Used in GeneratorEvaluationTest test case. Tests that value updated
  883. // here will NOT be used for instantiating tests in
  884. // GeneratorEvaluationTest.
  885. GeneratorEvaluationTest::set_param_value(2);
  886. #endif // GTEST_HAS_PARAM_TEST
  887. return RUN_ALL_TESTS();
  888. }