1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
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.
35 #include "gtest/gtest.h"
44 # include "src/gtest-internal-inl.h" // for UnitTestOptions
45 # include "test/googletest-param-test-test.h"
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;
59 using ::testing::internal::ParamGenerator;
60 using ::testing::internal::UnitTestOptions;
62 // Prints a value to a string.
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.
69 ::std::string PrintValue(const T& value) {
70 return testing::PrintToString(value);
73 // Verifies that a sequence generated by the generator and accessed
74 // via the iterator object matches the expected one using Google Test
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)
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";
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";
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
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";
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";
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());
123 it = generator.begin();
124 EXPECT_TRUE(it == generator.end());
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.
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();
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";
145 // Verifies that iterator assignment works as expected.
147 EXPECT_FALSE(*it == *it2);
149 EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
150 << "element same as its source points to";
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";
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++));
162 // Verifies that prefix and postfix operator++() advance an iterator
167 EXPECT_TRUE(*it == *it2);
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);
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);
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);
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);
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);
210 // Verifies that Range works with user-defined types that define
211 // copy constructor, operator=(), operator+(), and operator<().
214 explicit DogAdder(const char* a_value) : value_(a_value) {}
215 DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
217 DogAdder operator=(const DogAdder& other) {
219 value_ = other.value_;
222 DogAdder operator+(const DogAdder& other) const {
224 msg << value_.c_str() << other.value_.c_str();
225 return DogAdder(msg.GetString().c_str());
227 bool operator<(const DogAdder& other) const {
228 return value_ < other.value_;
230 const std::string& value() const { return value_; }
236 TEST(RangeTest, WorksWithACustomType) {
237 const ParamGenerator<DogAdder> gen =
238 Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
239 ParamGenerator<DogAdder>::iterator it = gen.begin();
241 ASSERT_FALSE(it == gen.end());
242 EXPECT_STREQ("cat", it->value().c_str());
244 ASSERT_FALSE(++it == gen.end());
245 EXPECT_STREQ("catdog", it->value().c_str());
247 EXPECT_TRUE(++it == gen.end());
252 explicit IntWrapper(int a_value) : value_(a_value) {}
253 IntWrapper(const IntWrapper& other) : value_(other.value_) {}
255 IntWrapper operator=(const IntWrapper& other) {
256 value_ = other.value_;
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_;
264 int value() const { return value_; }
270 TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
271 const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
272 ParamGenerator<IntWrapper>::iterator it = gen.begin();
274 ASSERT_FALSE(it == gen.end());
275 EXPECT_EQ(0, it->value());
277 ASSERT_FALSE(++it == gen.end());
278 EXPECT_EQ(1, it->value());
280 EXPECT_TRUE(++it == gen.end());
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);
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);
299 // Edge case. Tests that ValuesIn() with an array parameter containing a
300 // single element generates the single element sequence.
301 TEST(ValuesInTest, ValuesInSingleElementArray) {
303 const ParamGenerator<int> gen = ValuesIn(array);
304 VerifyGenerator(gen, array);
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;
315 const ParamGenerator<int> gen = ValuesIn(values);
317 const int expected_values[] = {3, 5, 8};
318 VerifyGenerator(gen, expected_values);
321 // Tests that ValuesIn() generates the expected sequence.
322 TEST(ValuesInTest, ValuesInIteratorRange) {
323 typedef ::std::vector<int> ContainerType;
324 ContainerType values;
328 const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
330 const int expected_values[] = {3, 5, 8};
331 VerifyGenerator(gen, expected_values);
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());
342 const int expected_values[] = {42};
343 VerifyGenerator(gen, expected_values);
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());
353 VerifyGeneratorIsEmpty(gen);
356 // Tests that the Values() generates the expected sequence.
357 TEST(ValuesTest, ValuesWorks) {
358 const ParamGenerator<int> gen = Values(3, 5, 8);
360 const int expected_values[] = {3, 5, 8};
361 VerifyGenerator(gen, expected_values);
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);
369 const double expected_values[] = {3.0, 5.0, 8.0};
370 VerifyGenerator(gen, expected_values);
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);
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);
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);
395 const int expected_values[] = {42};
396 VerifyGenerator(gen, expected_values);
399 // Tests that Bool() generates sequence (false, true).
400 TEST(BoolTest, BoolWorks) {
401 const ParamGenerator<bool> gen = Bool();
403 const bool expected_values[] = {false, true};
404 VerifyGenerator(gen, expected_values);
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));
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);
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);
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));
439 std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),
440 std::make_tuple(42, 1)};
441 VerifyGenerator(gen, expected_values);
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));
451 std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),
452 std::make_tuple(1, 42)};
453 VerifyGenerator(gen, expected_values);
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);
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);
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> >
480 Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),
481 Values(5), Values(6), Values(7), Values(8), Values(9));
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);
489 class NonDefaultConstructAssignString {
491 NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
493 const std::string& str() const { return str_; }
498 // Not default constructible
499 NonDefaultConstructAssignString();
501 void operator=(const NonDefaultConstructAssignString&);
504 TEST(CombineTest, NonDefaultConstructAssign) {
505 const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen =
506 Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
507 NonDefaultConstructAssignString("B")));
509 ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator
512 EXPECT_EQ(0, std::get<0>(*it));
513 EXPECT_EQ("A", std::get<1>(*it).str());
516 EXPECT_EQ(0, std::get<0>(*it));
517 EXPECT_EQ("B", std::get<1>(*it).str());
520 EXPECT_EQ(1, std::get<0>(*it));
521 EXPECT_EQ("A", std::get<1>(*it).str());
524 EXPECT_EQ(1, std::get<0>(*it));
525 EXPECT_EQ("B", std::get<1>(*it).str());
528 EXPECT_TRUE(it == gen.end());
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);
539 const int expected_values[] = {3, 4};
540 VerifyGenerator(gen, expected_values);
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.
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 {
555 static TestGenerationEnvironment* Instance() {
556 static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
560 void FixtureConstructorExecuted() { fixture_constructor_count_++; }
561 void SetUpExecuted() { set_up_count_++; }
562 void TearDownExecuted() { tear_down_count_++; }
563 void TestBodyExecuted() { test_body_count_++; }
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;
570 for (int i = 0; i < kExpectedCalls; ++i) {
572 msg << "TestsExpandedAndRun/" << i;
573 if (UnitTestOptions::FilterMatchesTest(
574 "TestExpansionModule/MultipleTestGenerationTest",
575 msg.GetString().c_str())) {
576 perform_check = true;
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.";
596 TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
597 tear_down_count_(0), test_body_count_(0) {}
599 int fixture_constructor_count_;
601 int tear_down_count_;
602 int test_body_count_;
604 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment);
607 const int test_generation_params[] = {36, 42, 72};
609 class TestGenerationTest : public TestWithParam<int> {
613 sizeof(test_generation_params)/sizeof(test_generation_params[0])
616 typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
618 TestGenerationTest() {
619 Environment::Instance()->FixtureConstructorExecuted();
620 current_parameter_ = GetParam();
622 void SetUp() override {
623 Environment::Instance()->SetUpExecuted();
624 EXPECT_EQ(current_parameter_, GetParam());
626 void TearDown() override {
627 Environment::Instance()->TearDownExecuted();
628 EXPECT_EQ(current_parameter_, GetParam());
631 static void SetUpTestSuite() {
632 bool all_tests_in_test_case_selected = true;
634 for (int i = 0; i < PARAMETER_COUNT; ++i) {
636 test_name << "TestsExpandedAndRun/" << i;
637 if ( !UnitTestOptions::FilterMatchesTest(
638 "TestExpansionModule/MultipleTestGenerationTest",
639 test_name.GetString())) {
640 all_tests_in_test_case_selected = false;
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.";
649 collected_parameters_.clear();
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());
661 EXPECT_TRUE(collected_parameters_ == expected_values);
665 int current_parameter_;
666 static vector<int> collected_parameters_;
669 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest);
671 vector<int> TestGenerationTest::collected_parameters_;
673 TEST_P(TestGenerationTest, TestsExpandedAndRun) {
674 Environment::Instance()->TestBodyExecuted();
675 EXPECT_EQ(current_parameter_, GetParam());
676 collected_parameters_.push_back(GetParam());
678 INSTANTIATE_TEST_SUITE_P(TestExpansionModule, TestGenerationTest,
679 ValuesIn(test_generation_params));
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
691 class GeneratorEvaluationTest : public TestWithParam<int> {
693 static int param_value() { return param_value_; }
694 static void set_param_value(int param_value) { param_value_ = param_value; }
697 static int param_value_;
699 int GeneratorEvaluationTest::param_value_ = 0;
701 TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
702 EXPECT_EQ(1, GetParam());
704 INSTANTIATE_TEST_SUITE_P(GenEvalModule, GeneratorEvaluationTest,
705 Values(GeneratorEvaluationTest::param_value()));
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);
716 INSTANTIATE_TEST_SUITE_P(ExternalGeneratorModule, ExternalGeneratorTest,
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);
727 // Tests that a parameterized test case can be instantiated with multiple
729 class MultipleInstantiationTest : public TestWithParam<int> {};
730 TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
732 INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
733 INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
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);
743 INSTANTIATE_TEST_SUITE_P(Sequence1, InstantiationInMultipleTranslationUnitsTest,
746 // Tests that each iteration of parameterized test runs in a separate test
748 class SeparateInstanceTest : public TestWithParam<int> {
750 SeparateInstanceTest() : count_(0) {}
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.";
762 static int global_count_;
764 int SeparateInstanceTest::global_count_ = 0;
766 TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
767 EXPECT_EQ(0, count_++);
770 INSTANTIATE_TEST_SUITE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
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> {};
779 TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
780 const ::testing::TestInfo* const test_info =
781 ::testing::UnitTest::GetInstance()->current_test_info();
783 EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name());
785 Message index_stream;
786 index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
787 EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
789 EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
792 INSTANTIATE_TEST_SUITE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
794 // Tests that macros in test names are expanded correctly.
795 class MacroNamingTest : public TestWithParam<int> {};
797 #define PREFIX_WITH_FOO(test_name) Foo##test_name
798 #define PREFIX_WITH_MACRO(test_name) Macro##test_name
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();
804 EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name());
805 EXPECT_STREQ("FooSomeTestName", test_info->name());
808 INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42));
810 // Tests the same thing for non-parametrized tests.
811 class MacroNamingTestNonParametrized : public ::testing::Test {};
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();
818 EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name());
819 EXPECT_STREQ("FooSomeTestName", test_info->name());
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) {}
829 struct CustomParamNameFunctor {
830 std::string operator()(const ::testing::TestParamInfo<std::string>& inf) {
835 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctor, CustomFunctorNamingTest,
836 Values(std::string("FunctorName")),
837 CustomParamNameFunctor());
839 INSTANTIATE_TEST_SUITE_P(AllAllowedCharacters, CustomFunctorNamingTest,
840 Values("abcdefghijklmnopqrstuvwxyz",
841 "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "01234567890_"),
842 CustomParamNameFunctor());
844 inline std::string CustomParamNameFunction(
845 const ::testing::TestParamInfo<std::string>& inf) {
849 class CustomFunctionNamingTest : public TestWithParam<std::string> {};
850 TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
852 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunction, CustomFunctionNamingTest,
853 Values(std::string("FunctionName")),
854 CustomParamNameFunction);
856 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctionP, CustomFunctionNamingTest,
857 Values(std::string("FunctionNameP")),
858 &CustomParamNameFunction);
860 // Test custom naming with a lambda
862 class CustomLambdaNamingTest : public TestWithParam<std::string> {};
863 TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
865 INSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest,
866 Values(std::string("LambdaName")),
867 [](const ::testing::TestParamInfo<std::string>& inf) {
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();
876 const ::testing::TestSuite* test_suite = unit_test->GetTestSuite(suite_num);
877 for (int test_num = 0; test_num < test_suite->total_test_count();
879 const ::testing::TestInfo* test_info = test_suite->GetTestInfo(test_num);
880 test_names.insert(std::string(test_info->name()));
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"));
889 // Test a numeric name to ensure PrintToStringParamName works correctly.
891 class CustomIntegerNamingTest : public TestWithParam<int> {};
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());
901 INSTANTIATE_TEST_SUITE_P(PrintToString, CustomIntegerNamingTest, Range(0, 5),
902 ::testing::PrintToStringParamName());
904 // Test a custom struct with PrintToString.
906 struct CustomStruct {
907 explicit CustomStruct(int value) : x(value) {}
911 std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
916 class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
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());
926 INSTANTIATE_TEST_SUITE_P(PrintToString, CustomStructNamingTest,
927 Values(CustomStruct(0), CustomStruct(1)),
928 ::testing::PrintToStringParamName());
930 // Test that using a stateful parameter naming function works as expected.
932 struct StatefulNamingFunctor {
933 StatefulNamingFunctor() : sum(0) {}
934 std::string operator()(const ::testing::TestParamInfo<int>& info) {
935 int value = info.param + sum;
937 return ::testing::PrintToString(value);
942 class StatefulNamingTest : public ::testing::TestWithParam<int> {
944 StatefulNamingTest() : sum_(0) {}
948 TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
949 const ::testing::TestInfo* const test_info =
950 ::testing::UnitTest::GetInstance()->current_test_info();
952 Message test_name_stream;
953 test_name_stream << "TestsReportCorrectNames/" << sum_;
954 EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
957 INSTANTIATE_TEST_SUITE_P(StatefulNamingFunctor, StatefulNamingTest, Range(0, 5),
958 StatefulNamingFunctor());
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
966 explicit Unstreamable(int value) : value_(value) {}
967 // -Wunused-private-field: dummy accessor for `value_`.
968 const int& dummy_value() const { return value_; }
974 class CommentTest : public TestWithParam<Unstreamable> {};
976 TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
977 const ::testing::TestInfo* const test_info =
978 ::testing::UnitTest::GetInstance()->current_test_info();
980 EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
983 INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
984 Values(Unstreamable(1)));
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 {
992 NonParameterizedBaseTest() : n_(17) { }
997 class ParameterizedDerivedTest : public NonParameterizedBaseTest,
998 public ::testing::WithParamInterface<int> {
1000 ParameterizedDerivedTest() : count_(0) { }
1002 static int global_count_;
1005 int ParameterizedDerivedTest::global_count_ = 0;
1007 TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
1011 TEST_P(ParameterizedDerivedTest, SeesSequence) {
1013 EXPECT_EQ(0, count_++);
1014 EXPECT_EQ(GetParam(), global_count_++);
1017 class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
1019 TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
1020 EXPECT_DEATH_IF_SUPPORTED(GetParam(),
1021 ".* value-parameterized test .*");
1024 INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
1027 // Tests param generator working with Enums
1034 class MyEnumTest : public testing::TestWithParam<MyEnums> {};
1036 TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
1037 INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,
1038 ::testing::Values(ENUM1, ENUM2, 0));
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);
1047 ::testing::InitGoogleTest(&argc, argv);
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);
1054 return RUN_ALL_TESTS();