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