gtest-param-test_test.cc
Go to the documentation of this file.
00001 // Copyright 2008, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: vladl@google.com (Vlad Losev)
00031 //
00032 // Tests for Google Test itself. This file verifies that the parameter
00033 // generators objects produce correct parameter sequences and that
00034 // Google Test runtime instantiates correct tests from those sequences.
00035 
00036 #include "gtest/gtest.h"
00037 
00038 #if GTEST_HAS_PARAM_TEST
00039 
00040 # include <algorithm>
00041 # include <iostream>
00042 # include <list>
00043 # include <sstream>
00044 # include <string>
00045 # include <vector>
00046 
00047 // To include gtest-internal-inl.h.
00048 # define GTEST_IMPLEMENTATION_ 1
00049 # include "src/gtest-internal-inl.h"  // for UnitTestOptions
00050 # undef GTEST_IMPLEMENTATION_
00051 
00052 # include "test/gtest-param-test_test.h"
00053 
00054 using ::std::vector;
00055 using ::std::sort;
00056 
00057 using ::testing::AddGlobalTestEnvironment;
00058 using ::testing::Bool;
00059 using ::testing::Message;
00060 using ::testing::Range;
00061 using ::testing::TestWithParam;
00062 using ::testing::Values;
00063 using ::testing::ValuesIn;
00064 
00065 # if GTEST_HAS_COMBINE
00066 using ::testing::Combine;
00067 using ::testing::get;
00068 using ::testing::make_tuple;
00069 using ::testing::tuple;
00070 # endif  // GTEST_HAS_COMBINE
00071 
00072 using ::testing::internal::ParamGenerator;
00073 using ::testing::internal::UnitTestOptions;
00074 
00075 // Prints a value to a string.
00076 //
00077 // TODO(wan@google.com): remove PrintValue() when we move matchers and
00078 // EXPECT_THAT() from Google Mock to Google Test.  At that time, we
00079 // can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as
00080 // EXPECT_THAT() and the matchers know how to print tuples.
00081 template <typename T>
00082 ::std::string PrintValue(const T& value) {
00083   ::std::stringstream stream;
00084   stream << value;
00085   return stream.str();
00086 }
00087 
00088 # if GTEST_HAS_COMBINE
00089 
00090 // These overloads allow printing tuples in our tests.  We cannot
00091 // define an operator<< for tuples, as that definition needs to be in
00092 // the std namespace in order to be picked up by Google Test via
00093 // Argument-Dependent Lookup, yet defining anything in the std
00094 // namespace in non-STL code is undefined behavior.
00095 
00096 template <typename T1, typename T2>
00097 ::std::string PrintValue(const tuple<T1, T2>& value) {
00098   ::std::stringstream stream;
00099   stream << "(" << get<0>(value) << ", " << get<1>(value) << ")";
00100   return stream.str();
00101 }
00102 
00103 template <typename T1, typename T2, typename T3>
00104 ::std::string PrintValue(const tuple<T1, T2, T3>& value) {
00105   ::std::stringstream stream;
00106   stream << "(" << get<0>(value) << ", " << get<1>(value)
00107          << ", "<< get<2>(value) << ")";
00108   return stream.str();
00109 }
00110 
00111 template <typename T1, typename T2, typename T3, typename T4, typename T5,
00112           typename T6, typename T7, typename T8, typename T9, typename T10>
00113 ::std::string PrintValue(
00114     const tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& value) {
00115   ::std::stringstream stream;
00116   stream << "(" << get<0>(value) << ", " << get<1>(value)
00117          << ", "<< get<2>(value) << ", " << get<3>(value)
00118          << ", "<< get<4>(value) << ", " << get<5>(value)
00119          << ", "<< get<6>(value) << ", " << get<7>(value)
00120          << ", "<< get<8>(value) << ", " << get<9>(value) << ")";
00121   return stream.str();
00122 }
00123 
00124 # endif  // GTEST_HAS_COMBINE
00125 
00126 // Verifies that a sequence generated by the generator and accessed
00127 // via the iterator object matches the expected one using Google Test
00128 // assertions.
00129 template <typename T, size_t N>
00130 void VerifyGenerator(const ParamGenerator<T>& generator,
00131                      const T (&expected_values)[N]) {
00132   typename ParamGenerator<T>::iterator it = generator.begin();
00133   for (size_t i = 0; i < N; ++i) {
00134     ASSERT_FALSE(it == generator.end())
00135         << "At element " << i << " when accessing via an iterator "
00136         << "created with the copy constructor.\n";
00137     // We cannot use EXPECT_EQ() here as the values may be tuples,
00138     // which don't support <<.
00139     EXPECT_TRUE(expected_values[i] == *it)
00140         << "where i is " << i
00141         << ", expected_values[i] is " << PrintValue(expected_values[i])
00142         << ", *it is " << PrintValue(*it)
00143         << ", and 'it' is an iterator created with the copy constructor.\n";
00144     it++;
00145   }
00146   EXPECT_TRUE(it == generator.end())
00147         << "At the presumed end of sequence when accessing via an iterator "
00148         << "created with the copy constructor.\n";
00149 
00150   // Test the iterator assignment. The following lines verify that
00151   // the sequence accessed via an iterator initialized via the
00152   // assignment operator (as opposed to a copy constructor) matches
00153   // just the same.
00154   it = generator.begin();
00155   for (size_t i = 0; i < N; ++i) {
00156     ASSERT_FALSE(it == generator.end())
00157         << "At element " << i << " when accessing via an iterator "
00158         << "created with the assignment operator.\n";
00159     EXPECT_TRUE(expected_values[i] == *it)
00160         << "where i is " << i
00161         << ", expected_values[i] is " << PrintValue(expected_values[i])
00162         << ", *it is " << PrintValue(*it)
00163         << ", and 'it' is an iterator created with the copy constructor.\n";
00164     it++;
00165   }
00166   EXPECT_TRUE(it == generator.end())
00167         << "At the presumed end of sequence when accessing via an iterator "
00168         << "created with the assignment operator.\n";
00169 }
00170 
00171 template <typename T>
00172 void VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {
00173   typename ParamGenerator<T>::iterator it = generator.begin();
00174   EXPECT_TRUE(it == generator.end());
00175 
00176   it = generator.begin();
00177   EXPECT_TRUE(it == generator.end());
00178 }
00179 
00180 // Generator tests. They test that each of the provided generator functions
00181 // generates an expected sequence of values. The general test pattern
00182 // instantiates a generator using one of the generator functions,
00183 // checks the sequence produced by the generator using its iterator API,
00184 // and then resets the iterator back to the beginning of the sequence
00185 // and checks the sequence again.
00186 
00187 // Tests that iterators produced by generator functions conform to the
00188 // ForwardIterator concept.
00189 TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {
00190   const ParamGenerator<int> gen = Range(0, 10);
00191   ParamGenerator<int>::iterator it = gen.begin();
00192 
00193   // Verifies that iterator initialization works as expected.
00194   ParamGenerator<int>::iterator it2 = it;
00195   EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the "
00196                            << "element same as its source points to";
00197 
00198   // Verifies that iterator assignment works as expected.
00199   it++;
00200   EXPECT_FALSE(*it == *it2);
00201   it2 = it;
00202   EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
00203                            << "element same as its source points to";
00204 
00205   // Verifies that prefix operator++() returns *this.
00206   EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be "
00207                           << "refer to the original object";
00208 
00209   // Verifies that the result of the postfix operator++ points to the value
00210   // pointed to by the original iterator.
00211   int original_value = *it;  // Have to compute it outside of macro call to be
00212                              // unaffected by the parameter evaluation order.
00213   EXPECT_EQ(original_value, *(it++));
00214 
00215   // Verifies that prefix and postfix operator++() advance an iterator
00216   // all the same.
00217   it2 = it;
00218   it++;
00219   ++it2;
00220   EXPECT_TRUE(*it == *it2);
00221 }
00222 
00223 // Tests that Range() generates the expected sequence.
00224 TEST(RangeTest, IntRangeWithDefaultStep) {
00225   const ParamGenerator<int> gen = Range(0, 3);
00226   const int expected_values[] = {0, 1, 2};
00227   VerifyGenerator(gen, expected_values);
00228 }
00229 
00230 // Edge case. Tests that Range() generates the single element sequence
00231 // as expected when provided with range limits that are equal.
00232 TEST(RangeTest, IntRangeSingleValue) {
00233   const ParamGenerator<int> gen = Range(0, 1);
00234   const int expected_values[] = {0};
00235   VerifyGenerator(gen, expected_values);
00236 }
00237 
00238 // Edge case. Tests that Range() with generates empty sequence when
00239 // supplied with an empty range.
00240 TEST(RangeTest, IntRangeEmpty) {
00241   const ParamGenerator<int> gen = Range(0, 0);
00242   VerifyGeneratorIsEmpty(gen);
00243 }
00244 
00245 // Tests that Range() with custom step (greater then one) generates
00246 // the expected sequence.
00247 TEST(RangeTest, IntRangeWithCustomStep) {
00248   const ParamGenerator<int> gen = Range(0, 9, 3);
00249   const int expected_values[] = {0, 3, 6};
00250   VerifyGenerator(gen, expected_values);
00251 }
00252 
00253 // Tests that Range() with custom step (greater then one) generates
00254 // the expected sequence when the last element does not fall on the
00255 // upper range limit. Sequences generated by Range() must not have
00256 // elements beyond the range limits.
00257 TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {
00258   const ParamGenerator<int> gen = Range(0, 4, 3);
00259   const int expected_values[] = {0, 3};
00260   VerifyGenerator(gen, expected_values);
00261 }
00262 
00263 // Verifies that Range works with user-defined types that define
00264 // copy constructor, operator=(), operator+(), and operator<().
00265 class DogAdder {
00266  public:
00267   explicit DogAdder(const char* a_value) : value_(a_value) {}
00268   DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
00269 
00270   DogAdder operator=(const DogAdder& other) {
00271     if (this != &other)
00272       value_ = other.value_;
00273     return *this;
00274   }
00275   DogAdder operator+(const DogAdder& other) const {
00276     Message msg;
00277     msg << value_.c_str() << other.value_.c_str();
00278     return DogAdder(msg.GetString().c_str());
00279   }
00280   bool operator<(const DogAdder& other) const {
00281     return value_ < other.value_;
00282   }
00283   const std::string& value() const { return value_; }
00284 
00285  private:
00286   std::string value_;
00287 };
00288 
00289 TEST(RangeTest, WorksWithACustomType) {
00290   const ParamGenerator<DogAdder> gen =
00291       Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
00292   ParamGenerator<DogAdder>::iterator it = gen.begin();
00293 
00294   ASSERT_FALSE(it == gen.end());
00295   EXPECT_STREQ("cat", it->value().c_str());
00296 
00297   ASSERT_FALSE(++it == gen.end());
00298   EXPECT_STREQ("catdog", it->value().c_str());
00299 
00300   EXPECT_TRUE(++it == gen.end());
00301 }
00302 
00303 class IntWrapper {
00304  public:
00305   explicit IntWrapper(int a_value) : value_(a_value) {}
00306   IntWrapper(const IntWrapper& other) : value_(other.value_) {}
00307 
00308   IntWrapper operator=(const IntWrapper& other) {
00309     value_ = other.value_;
00310     return *this;
00311   }
00312   // operator+() adds a different type.
00313   IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }
00314   bool operator<(const IntWrapper& other) const {
00315     return value_ < other.value_;
00316   }
00317   int value() const { return value_; }
00318 
00319  private:
00320   int value_;
00321 };
00322 
00323 TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
00324   const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
00325   ParamGenerator<IntWrapper>::iterator it = gen.begin();
00326 
00327   ASSERT_FALSE(it == gen.end());
00328   EXPECT_EQ(0, it->value());
00329 
00330   ASSERT_FALSE(++it == gen.end());
00331   EXPECT_EQ(1, it->value());
00332 
00333   EXPECT_TRUE(++it == gen.end());
00334 }
00335 
00336 // Tests that ValuesIn() with an array parameter generates
00337 // the expected sequence.
00338 TEST(ValuesInTest, ValuesInArray) {
00339   int array[] = {3, 5, 8};
00340   const ParamGenerator<int> gen = ValuesIn(array);
00341   VerifyGenerator(gen, array);
00342 }
00343 
00344 // Tests that ValuesIn() with a const array parameter generates
00345 // the expected sequence.
00346 TEST(ValuesInTest, ValuesInConstArray) {
00347   const int array[] = {3, 5, 8};
00348   const ParamGenerator<int> gen = ValuesIn(array);
00349   VerifyGenerator(gen, array);
00350 }
00351 
00352 // Edge case. Tests that ValuesIn() with an array parameter containing a
00353 // single element generates the single element sequence.
00354 TEST(ValuesInTest, ValuesInSingleElementArray) {
00355   int array[] = {42};
00356   const ParamGenerator<int> gen = ValuesIn(array);
00357   VerifyGenerator(gen, array);
00358 }
00359 
00360 // Tests that ValuesIn() generates the expected sequence for an STL
00361 // container (vector).
00362 TEST(ValuesInTest, ValuesInVector) {
00363   typedef ::std::vector<int> ContainerType;
00364   ContainerType values;
00365   values.push_back(3);
00366   values.push_back(5);
00367   values.push_back(8);
00368   const ParamGenerator<int> gen = ValuesIn(values);
00369 
00370   const int expected_values[] = {3, 5, 8};
00371   VerifyGenerator(gen, expected_values);
00372 }
00373 
00374 // Tests that ValuesIn() generates the expected sequence.
00375 TEST(ValuesInTest, ValuesInIteratorRange) {
00376   typedef ::std::vector<int> ContainerType;
00377   ContainerType values;
00378   values.push_back(3);
00379   values.push_back(5);
00380   values.push_back(8);
00381   const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
00382 
00383   const int expected_values[] = {3, 5, 8};
00384   VerifyGenerator(gen, expected_values);
00385 }
00386 
00387 // Edge case. Tests that ValuesIn() provided with an iterator range specifying a
00388 // single value generates a single-element sequence.
00389 TEST(ValuesInTest, ValuesInSingleElementIteratorRange) {
00390   typedef ::std::vector<int> ContainerType;
00391   ContainerType values;
00392   values.push_back(42);
00393   const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
00394 
00395   const int expected_values[] = {42};
00396   VerifyGenerator(gen, expected_values);
00397 }
00398 
00399 // Edge case. Tests that ValuesIn() provided with an empty iterator range
00400 // generates an empty sequence.
00401 TEST(ValuesInTest, ValuesInEmptyIteratorRange) {
00402   typedef ::std::vector<int> ContainerType;
00403   ContainerType values;
00404   const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
00405 
00406   VerifyGeneratorIsEmpty(gen);
00407 }
00408 
00409 // Tests that the Values() generates the expected sequence.
00410 TEST(ValuesTest, ValuesWorks) {
00411   const ParamGenerator<int> gen = Values(3, 5, 8);
00412 
00413   const int expected_values[] = {3, 5, 8};
00414   VerifyGenerator(gen, expected_values);
00415 }
00416 
00417 // Tests that Values() generates the expected sequences from elements of
00418 // different types convertible to ParamGenerator's parameter type.
00419 TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
00420   const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);
00421 
00422   const double expected_values[] = {3.0, 5.0, 8.0};
00423   VerifyGenerator(gen, expected_values);
00424 }
00425 
00426 TEST(ValuesTest, ValuesWorksForMaxLengthList) {
00427   const ParamGenerator<int> gen = Values(
00428       10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
00429       110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
00430       210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
00431       310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
00432       410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
00433 
00434   const int expected_values[] = {
00435       10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
00436       110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
00437       210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
00438       310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
00439       410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
00440   VerifyGenerator(gen, expected_values);
00441 }
00442 
00443 // Edge case test. Tests that single-parameter Values() generates the sequence
00444 // with the single value.
00445 TEST(ValuesTest, ValuesWithSingleParameter) {
00446   const ParamGenerator<int> gen = Values(42);
00447 
00448   const int expected_values[] = {42};
00449   VerifyGenerator(gen, expected_values);
00450 }
00451 
00452 // Tests that Bool() generates sequence (false, true).
00453 TEST(BoolTest, BoolWorks) {
00454   const ParamGenerator<bool> gen = Bool();
00455 
00456   const bool expected_values[] = {false, true};
00457   VerifyGenerator(gen, expected_values);
00458 }
00459 
00460 # if GTEST_HAS_COMBINE
00461 
00462 // Tests that Combine() with two parameters generates the expected sequence.
00463 TEST(CombineTest, CombineWithTwoParameters) {
00464   const char* foo = "foo";
00465   const char* bar = "bar";
00466   const ParamGenerator<tuple<const char*, int> > gen =
00467       Combine(Values(foo, bar), Values(3, 4));
00468 
00469   tuple<const char*, int> expected_values[] = {
00470     make_tuple(foo, 3), make_tuple(foo, 4),
00471     make_tuple(bar, 3), make_tuple(bar, 4)};
00472   VerifyGenerator(gen, expected_values);
00473 }
00474 
00475 // Tests that Combine() with three parameters generates the expected sequence.
00476 TEST(CombineTest, CombineWithThreeParameters) {
00477   const ParamGenerator<tuple<int, int, int> > gen = Combine(Values(0, 1),
00478                                                             Values(3, 4),
00479                                                             Values(5, 6));
00480   tuple<int, int, int> expected_values[] = {
00481     make_tuple(0, 3, 5), make_tuple(0, 3, 6),
00482     make_tuple(0, 4, 5), make_tuple(0, 4, 6),
00483     make_tuple(1, 3, 5), make_tuple(1, 3, 6),
00484     make_tuple(1, 4, 5), make_tuple(1, 4, 6)};
00485   VerifyGenerator(gen, expected_values);
00486 }
00487 
00488 // Tests that the Combine() with the first parameter generating a single value
00489 // sequence generates a sequence with the number of elements equal to the
00490 // number of elements in the sequence generated by the second parameter.
00491 TEST(CombineTest, CombineWithFirstParameterSingleValue) {
00492   const ParamGenerator<tuple<int, int> > gen = Combine(Values(42),
00493                                                        Values(0, 1));
00494 
00495   tuple<int, int> expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)};
00496   VerifyGenerator(gen, expected_values);
00497 }
00498 
00499 // Tests that the Combine() with the second parameter generating a single value
00500 // sequence generates a sequence with the number of elements equal to the
00501 // number of elements in the sequence generated by the first parameter.
00502 TEST(CombineTest, CombineWithSecondParameterSingleValue) {
00503   const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
00504                                                        Values(42));
00505 
00506   tuple<int, int> expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)};
00507   VerifyGenerator(gen, expected_values);
00508 }
00509 
00510 // Tests that when the first parameter produces an empty sequence,
00511 // Combine() produces an empty sequence, too.
00512 TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
00513   const ParamGenerator<tuple<int, int> > gen = Combine(Range(0, 0),
00514                                                        Values(0, 1));
00515   VerifyGeneratorIsEmpty(gen);
00516 }
00517 
00518 // Tests that when the second parameter produces an empty sequence,
00519 // Combine() produces an empty sequence, too.
00520 TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
00521   const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1),
00522                                                        Range(1, 1));
00523   VerifyGeneratorIsEmpty(gen);
00524 }
00525 
00526 // Edge case. Tests that combine works with the maximum number
00527 // of parameters supported by Google Test (currently 10).
00528 TEST(CombineTest, CombineWithMaxNumberOfParameters) {
00529   const char* foo = "foo";
00530   const char* bar = "bar";
00531   const ParamGenerator<tuple<const char*, int, int, int, int, int, int, int,
00532                              int, int> > gen = Combine(Values(foo, bar),
00533                                                        Values(1), Values(2),
00534                                                        Values(3), Values(4),
00535                                                        Values(5), Values(6),
00536                                                        Values(7), Values(8),
00537                                                        Values(9));
00538 
00539   tuple<const char*, int, int, int, int, int, int, int, int, int>
00540       expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
00541                            make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
00542   VerifyGenerator(gen, expected_values);
00543 }
00544 
00545 # endif  // GTEST_HAS_COMBINE
00546 
00547 // Tests that an generator produces correct sequence after being
00548 // assigned from another generator.
00549 TEST(ParamGeneratorTest, AssignmentWorks) {
00550   ParamGenerator<int> gen = Values(1, 2);
00551   const ParamGenerator<int> gen2 = Values(3, 4);
00552   gen = gen2;
00553 
00554   const int expected_values[] = {3, 4};
00555   VerifyGenerator(gen, expected_values);
00556 }
00557 
00558 // This test verifies that the tests are expanded and run as specified:
00559 // one test per element from the sequence produced by the generator
00560 // specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's
00561 // fixture constructor, SetUp(), and TearDown() have run and have been
00562 // supplied with the correct parameters.
00563 
00564 // The use of environment object allows detection of the case where no test
00565 // case functionality is run at all. In this case TestCaseTearDown will not
00566 // be able to detect missing tests, naturally.
00567 template <int kExpectedCalls>
00568 class TestGenerationEnvironment : public ::testing::Environment {
00569  public:
00570   static TestGenerationEnvironment* Instance() {
00571     static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
00572     return instance;
00573   }
00574 
00575   void FixtureConstructorExecuted() { fixture_constructor_count_++; }
00576   void SetUpExecuted() { set_up_count_++; }
00577   void TearDownExecuted() { tear_down_count_++; }
00578   void TestBodyExecuted() { test_body_count_++; }
00579 
00580   virtual void TearDown() {
00581     // If all MultipleTestGenerationTest tests have been de-selected
00582     // by the filter flag, the following checks make no sense.
00583     bool perform_check = false;
00584 
00585     for (int i = 0; i < kExpectedCalls; ++i) {
00586       Message msg;
00587       msg << "TestsExpandedAndRun/" << i;
00588       if (UnitTestOptions::FilterMatchesTest(
00589              "TestExpansionModule/MultipleTestGenerationTest",
00590               msg.GetString().c_str())) {
00591         perform_check = true;
00592       }
00593     }
00594     if (perform_check) {
00595       EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)
00596           << "Fixture constructor of ParamTestGenerationTest test case "
00597           << "has not been run as expected.";
00598       EXPECT_EQ(kExpectedCalls, set_up_count_)
00599           << "Fixture SetUp method of ParamTestGenerationTest test case "
00600           << "has not been run as expected.";
00601       EXPECT_EQ(kExpectedCalls, tear_down_count_)
00602           << "Fixture TearDown method of ParamTestGenerationTest test case "
00603           << "has not been run as expected.";
00604       EXPECT_EQ(kExpectedCalls, test_body_count_)
00605           << "Test in ParamTestGenerationTest test case "
00606           << "has not been run as expected.";
00607     }
00608   }
00609 
00610  private:
00611   TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
00612                                 tear_down_count_(0), test_body_count_(0) {}
00613 
00614   int fixture_constructor_count_;
00615   int set_up_count_;
00616   int tear_down_count_;
00617   int test_body_count_;
00618 
00619   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment);
00620 };
00621 
00622 const int test_generation_params[] = {36, 42, 72};
00623 
00624 class TestGenerationTest : public TestWithParam<int> {
00625  public:
00626   enum {
00627     PARAMETER_COUNT =
00628         sizeof(test_generation_params)/sizeof(test_generation_params[0])
00629   };
00630 
00631   typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
00632 
00633   TestGenerationTest() {
00634     Environment::Instance()->FixtureConstructorExecuted();
00635     current_parameter_ = GetParam();
00636   }
00637   virtual void SetUp() {
00638     Environment::Instance()->SetUpExecuted();
00639     EXPECT_EQ(current_parameter_, GetParam());
00640   }
00641   virtual void TearDown() {
00642     Environment::Instance()->TearDownExecuted();
00643     EXPECT_EQ(current_parameter_, GetParam());
00644   }
00645 
00646   static void SetUpTestCase() {
00647     bool all_tests_in_test_case_selected = true;
00648 
00649     for (int i = 0; i < PARAMETER_COUNT; ++i) {
00650       Message test_name;
00651       test_name << "TestsExpandedAndRun/" << i;
00652       if ( !UnitTestOptions::FilterMatchesTest(
00653                 "TestExpansionModule/MultipleTestGenerationTest",
00654                 test_name.GetString())) {
00655         all_tests_in_test_case_selected = false;
00656       }
00657     }
00658     EXPECT_TRUE(all_tests_in_test_case_selected)
00659         << "When running the TestGenerationTest test case all of its tests\n"
00660         << "must be selected by the filter flag for the test case to pass.\n"
00661         << "If not all of them are enabled, we can't reliably conclude\n"
00662         << "that the correct number of tests have been generated.";
00663 
00664     collected_parameters_.clear();
00665   }
00666 
00667   static void TearDownTestCase() {
00668     vector<int> expected_values(test_generation_params,
00669                                 test_generation_params + PARAMETER_COUNT);
00670     // Test execution order is not guaranteed by Google Test,
00671     // so the order of values in collected_parameters_ can be
00672     // different and we have to sort to compare.
00673     sort(expected_values.begin(), expected_values.end());
00674     sort(collected_parameters_.begin(), collected_parameters_.end());
00675 
00676     EXPECT_TRUE(collected_parameters_ == expected_values);
00677   }
00678 
00679  protected:
00680   int current_parameter_;
00681   static vector<int> collected_parameters_;
00682 
00683  private:
00684   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest);
00685 };
00686 vector<int> TestGenerationTest::collected_parameters_;
00687 
00688 TEST_P(TestGenerationTest, TestsExpandedAndRun) {
00689   Environment::Instance()->TestBodyExecuted();
00690   EXPECT_EQ(current_parameter_, GetParam());
00691   collected_parameters_.push_back(GetParam());
00692 }
00693 INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest,
00694                         ValuesIn(test_generation_params));
00695 
00696 // This test verifies that the element sequence (third parameter of
00697 // INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at
00698 // the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS().  For
00699 // that, we declare param_value_ to be a static member of
00700 // GeneratorEvaluationTest and initialize it to 0.  We set it to 1 in
00701 // main(), just before invocation of InitGoogleTest().  After calling
00702 // InitGoogleTest(), we set the value to 2.  If the sequence is evaluated
00703 // before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a
00704 // test with parameter other than 1, and the test body will fail the
00705 // assertion.
00706 class GeneratorEvaluationTest : public TestWithParam<int> {
00707  public:
00708   static int param_value() { return param_value_; }
00709   static void set_param_value(int param_value) { param_value_ = param_value; }
00710 
00711  private:
00712   static int param_value_;
00713 };
00714 int GeneratorEvaluationTest::param_value_ = 0;
00715 
00716 TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
00717   EXPECT_EQ(1, GetParam());
00718 }
00719 INSTANTIATE_TEST_CASE_P(GenEvalModule,
00720                         GeneratorEvaluationTest,
00721                         Values(GeneratorEvaluationTest::param_value()));
00722 
00723 // Tests that generators defined in a different translation unit are
00724 // functional. Generator extern_gen is defined in gtest-param-test_test2.cc.
00725 extern ParamGenerator<int> extern_gen;
00726 class ExternalGeneratorTest : public TestWithParam<int> {};
00727 TEST_P(ExternalGeneratorTest, ExternalGenerator) {
00728   // Sequence produced by extern_gen contains only a single value
00729   // which we verify here.
00730   EXPECT_EQ(GetParam(), 33);
00731 }
00732 INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule,
00733                         ExternalGeneratorTest,
00734                         extern_gen);
00735 
00736 // Tests that a parameterized test case can be defined in one translation
00737 // unit and instantiated in another. This test will be instantiated in
00738 // gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is
00739 // defined in gtest-param-test_test.h.
00740 TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
00741   EXPECT_EQ(0, GetParam() % 33);
00742 }
00743 
00744 // Tests that a parameterized test case can be instantiated with multiple
00745 // generators.
00746 class MultipleInstantiationTest : public TestWithParam<int> {};
00747 TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
00748 }
00749 INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
00750 INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
00751 
00752 // Tests that a parameterized test case can be instantiated
00753 // in multiple translation units. This test will be instantiated
00754 // here and in gtest-param-test_test2.cc.
00755 // InstantiationInMultipleTranslationUnitsTest fixture class
00756 // is defined in gtest-param-test_test.h.
00757 TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) {
00758   EXPECT_EQ(0, GetParam() % 42);
00759 }
00760 INSTANTIATE_TEST_CASE_P(Sequence1,
00761                         InstantiationInMultipleTranslaionUnitsTest,
00762                         Values(42, 42*2));
00763 
00764 // Tests that each iteration of parameterized test runs in a separate test
00765 // object.
00766 class SeparateInstanceTest : public TestWithParam<int> {
00767  public:
00768   SeparateInstanceTest() : count_(0) {}
00769 
00770   static void TearDownTestCase() {
00771     EXPECT_GE(global_count_, 2)
00772         << "If some (but not all) SeparateInstanceTest tests have been "
00773         << "filtered out this test will fail. Make sure that all "
00774         << "GeneratorEvaluationTest are selected or de-selected together "
00775         << "by the test filter.";
00776   }
00777 
00778  protected:
00779   int count_;
00780   static int global_count_;
00781 };
00782 int SeparateInstanceTest::global_count_ = 0;
00783 
00784 TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
00785   EXPECT_EQ(0, count_++);
00786   global_count_++;
00787 }
00788 INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
00789 
00790 // Tests that all instantiations of a test have named appropriately. Test
00791 // defined with TEST_P(TestCaseName, TestName) and instantiated with
00792 // INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named
00793 // SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the
00794 // sequence element used to instantiate the test.
00795 class NamingTest : public TestWithParam<int> {};
00796 
00797 TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
00798   const ::testing::TestInfo* const test_info =
00799      ::testing::UnitTest::GetInstance()->current_test_info();
00800 
00801   EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name());
00802 
00803   Message index_stream;
00804   index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
00805   EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
00806 
00807   EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
00808 }
00809 
00810 INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
00811 
00812 // Class that cannot be streamed into an ostream.  It needs to be copyable
00813 // (and, in case of MSVC, also assignable) in order to be a test parameter
00814 // type.  Its default copy constructor and assignment operator do exactly
00815 // what we need.
00816 class Unstreamable {
00817  public:
00818   explicit Unstreamable(int value) : value_(value) {}
00819 
00820  private:
00821   int value_;
00822 };
00823 
00824 class CommentTest : public TestWithParam<Unstreamable> {};
00825 
00826 TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
00827   const ::testing::TestInfo* const test_info =
00828      ::testing::UnitTest::GetInstance()->current_test_info();
00829 
00830   EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
00831 }
00832 
00833 INSTANTIATE_TEST_CASE_P(InstantiationWithComments,
00834                         CommentTest,
00835                         Values(Unstreamable(1)));
00836 
00837 // Verify that we can create a hierarchy of test fixtures, where the base
00838 // class fixture is not parameterized and the derived class is. In this case
00839 // ParameterizedDerivedTest inherits from NonParameterizedBaseTest.  We
00840 // perform simple tests on both.
00841 class NonParameterizedBaseTest : public ::testing::Test {
00842  public:
00843   NonParameterizedBaseTest() : n_(17) { }
00844  protected:
00845   int n_;
00846 };
00847 
00848 class ParameterizedDerivedTest : public NonParameterizedBaseTest,
00849                                  public ::testing::WithParamInterface<int> {
00850  protected:
00851   ParameterizedDerivedTest() : count_(0) { }
00852   int count_;
00853   static int global_count_;
00854 };
00855 
00856 int ParameterizedDerivedTest::global_count_ = 0;
00857 
00858 TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
00859   EXPECT_EQ(17, n_);
00860 }
00861 
00862 TEST_P(ParameterizedDerivedTest, SeesSequence) {
00863   EXPECT_EQ(17, n_);
00864   EXPECT_EQ(0, count_++);
00865   EXPECT_EQ(GetParam(), global_count_++);
00866 }
00867 
00868 class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
00869 
00870 TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
00871   EXPECT_DEATH_IF_SUPPORTED(GetParam(),
00872                             ".* value-parameterized test .*");
00873 }
00874 
00875 INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5));
00876 
00877 #endif  // GTEST_HAS_PARAM_TEST
00878 
00879 TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) {
00880 #if GTEST_HAS_COMBINE && !GTEST_HAS_PARAM_TEST
00881   FAIL() << "GTEST_HAS_COMBINE is defined while GTEST_HAS_PARAM_TEST is not\n"
00882 #endif
00883 }
00884 
00885 int main(int argc, char **argv) {
00886 #if GTEST_HAS_PARAM_TEST
00887   // Used in TestGenerationTest test case.
00888   AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
00889   // Used in GeneratorEvaluationTest test case. Tests that the updated value
00890   // will be picked up for instantiating tests in GeneratorEvaluationTest.
00891   GeneratorEvaluationTest::set_param_value(1);
00892 #endif  // GTEST_HAS_PARAM_TEST
00893 
00894   ::testing::InitGoogleTest(&argc, argv);
00895 
00896 #if GTEST_HAS_PARAM_TEST
00897   // Used in GeneratorEvaluationTest test case. Tests that value updated
00898   // here will NOT be used for instantiating tests in
00899   // GeneratorEvaluationTest.
00900   GeneratorEvaluationTest::set_param_value(2);
00901 #endif  // GTEST_HAS_PARAM_TEST
00902 
00903   return RUN_ALL_TESTS();
00904 }


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:03