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