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 "test/googletest-param-test-test.h"
36
37 #include <algorithm>
38 #include <cstddef>
39 #include <cstdint>
40 #include <functional>
41 #include <iostream>
42 #include <list>
43 #include <set>
44 #include <sstream>
45 #include <string>
46 #include <string_view>
47 #include <tuple>
48 #include <type_traits>
49 #include <vector>
50
51 #include "gtest/gtest.h"
52 #include "src/gtest-internal-inl.h" // for UnitTestOptions
53
54 using ::std::sort;
55 using ::std::vector;
56
57 using ::testing::AddGlobalTestEnvironment;
58 using ::testing::Bool;
59 using ::testing::Combine;
60 using ::testing::ConvertGenerator;
61 using ::testing::Message;
62 using ::testing::Range;
63 using ::testing::TestWithParam;
64 using ::testing::Values;
65 using ::testing::ValuesIn;
66
67 using ::testing::internal::ParamGenerator;
68 using ::testing::internal::UnitTestOptions;
69
70 // Prints a value to a string.
71 //
72 // FIXME: remove PrintValue() when we move matchers and
73 // EXPECT_THAT() from Google Mock to Google Test. At that time, we
74 // can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as
75 // EXPECT_THAT() and the matchers know how to print tuples.
76 template <typename T>
PrintValue(const T & value)77 ::std::string PrintValue(const T& value) {
78 return testing::PrintToString(value);
79 }
80
81 // Verifies that a sequence generated by the generator and accessed
82 // via the iterator object matches the expected one using Google Test
83 // assertions.
84 template <typename T, size_t N>
VerifyGenerator(const ParamGenerator<T> & generator,const T (& expected_values)[N])85 void VerifyGenerator(const ParamGenerator<T>& generator,
86 const T (&expected_values)[N]) {
87 typename ParamGenerator<T>::iterator it = generator.begin();
88 for (size_t i = 0; i < N; ++i) {
89 ASSERT_FALSE(it == generator.end())
90 << "At element " << i << " when accessing via an iterator "
91 << "created with the copy constructor.\n";
92 // We cannot use EXPECT_EQ() here as the values may be tuples,
93 // which don't support <<.
94 EXPECT_TRUE(expected_values[i] == *it)
95 << "where i is " << i << ", expected_values[i] is "
96 << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
97 << ", and 'it' is an iterator created with the copy constructor.\n";
98 ++it;
99 }
100 EXPECT_TRUE(it == generator.end())
101 << "At the presumed end of sequence when accessing via an iterator "
102 << "created with the copy constructor.\n";
103
104 // Test the iterator assignment. The following lines verify that
105 // the sequence accessed via an iterator initialized via the
106 // assignment operator (as opposed to a copy constructor) matches
107 // just the same.
108 it = generator.begin();
109 for (size_t i = 0; i < N; ++i) {
110 ASSERT_FALSE(it == generator.end())
111 << "At element " << i << " when accessing via an iterator "
112 << "created with the assignment operator.\n";
113 EXPECT_TRUE(expected_values[i] == *it)
114 << "where i is " << i << ", expected_values[i] is "
115 << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
116 << ", and 'it' is an iterator created with the copy constructor.\n";
117 ++it;
118 }
119 EXPECT_TRUE(it == generator.end())
120 << "At the presumed end of sequence when accessing via an iterator "
121 << "created with the assignment operator.\n";
122 }
123
124 template <typename T>
VerifyGeneratorIsEmpty(const ParamGenerator<T> & generator)125 void VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {
126 typename ParamGenerator<T>::iterator it = generator.begin();
127 EXPECT_TRUE(it == generator.end());
128
129 it = generator.begin();
130 EXPECT_TRUE(it == generator.end());
131 }
132
133 // Generator tests. They test that each of the provided generator functions
134 // generates an expected sequence of values. The general test pattern
135 // instantiates a generator using one of the generator functions,
136 // checks the sequence produced by the generator using its iterator API,
137 // and then resets the iterator back to the beginning of the sequence
138 // and checks the sequence again.
139
140 // Tests that iterators produced by generator functions conform to the
141 // ForwardIterator concept.
TEST(IteratorTest,ParamIteratorConformsToForwardIteratorConcept)142 TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {
143 const ParamGenerator<int> gen = Range(0, 10);
144 ParamGenerator<int>::iterator it = gen.begin();
145
146 // Verifies that iterator initialization works as expected.
147 ParamGenerator<int>::iterator it2 = it;
148 EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the "
149 << "element same as its source points to";
150
151 // Verifies that iterator assignment works as expected.
152 ++it;
153 EXPECT_FALSE(*it == *it2);
154 it2 = it;
155 EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the "
156 << "element same as its source points to";
157
158 // Verifies that prefix operator++() returns *this.
159 EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be "
160 << "refer to the original object";
161
162 // Verifies that the result of the postfix operator++ points to the value
163 // pointed to by the original iterator.
164 int original_value = *it; // Have to compute it outside of macro call to be
165 // unaffected by the parameter evaluation order.
166 EXPECT_EQ(original_value, *(it++));
167
168 // Verifies that prefix and postfix operator++() advance an iterator
169 // all the same.
170 it2 = it;
171 ++it;
172 ++it2;
173 EXPECT_TRUE(*it == *it2);
174 }
175
176 // Tests that Range() generates the expected sequence.
TEST(RangeTest,IntRangeWithDefaultStep)177 TEST(RangeTest, IntRangeWithDefaultStep) {
178 const ParamGenerator<int> gen = Range(0, 3);
179 const int expected_values[] = {0, 1, 2};
180 VerifyGenerator(gen, expected_values);
181 }
182
183 // Edge case. Tests that Range() generates the single element sequence
184 // as expected when provided with range limits that are equal.
TEST(RangeTest,IntRangeSingleValue)185 TEST(RangeTest, IntRangeSingleValue) {
186 const ParamGenerator<int> gen = Range(0, 1);
187 const int expected_values[] = {0};
188 VerifyGenerator(gen, expected_values);
189 }
190
191 // Edge case. Tests that Range() with generates empty sequence when
192 // supplied with an empty range.
TEST(RangeTest,IntRangeEmpty)193 TEST(RangeTest, IntRangeEmpty) {
194 const ParamGenerator<int> gen = Range(0, 0);
195 VerifyGeneratorIsEmpty(gen);
196 }
197
198 // Tests that Range() with custom step (greater then one) generates
199 // the expected sequence.
TEST(RangeTest,IntRangeWithCustomStep)200 TEST(RangeTest, IntRangeWithCustomStep) {
201 const ParamGenerator<int> gen = Range(0, 9, 3);
202 const int expected_values[] = {0, 3, 6};
203 VerifyGenerator(gen, expected_values);
204 }
205
206 // Tests that Range() with custom step (greater then one) generates
207 // the expected sequence when the last element does not fall on the
208 // upper range limit. Sequences generated by Range() must not have
209 // elements beyond the range limits.
TEST(RangeTest,IntRangeWithCustomStepOverUpperBound)210 TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {
211 const ParamGenerator<int> gen = Range(0, 4, 3);
212 const int expected_values[] = {0, 3};
213 VerifyGenerator(gen, expected_values);
214 }
215
216 // Verifies that Range works with user-defined types that define
217 // copy constructor, operator=(), operator+(), and operator<().
218 class DogAdder {
219 public:
DogAdder(const char * a_value)220 explicit DogAdder(const char* a_value) : value_(a_value) {}
DogAdder(const DogAdder & other)221 DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
222
operator =(const DogAdder & other)223 DogAdder operator=(const DogAdder& other) {
224 if (this != &other) value_ = other.value_;
225 return *this;
226 }
operator +(const DogAdder & other) const227 DogAdder operator+(const DogAdder& other) const {
228 Message msg;
229 msg << value_ << other.value_;
230 return DogAdder(msg.GetString().c_str());
231 }
operator <(const DogAdder & other) const232 bool operator<(const DogAdder& other) const { return value_ < other.value_; }
value() const233 const std::string& value() const { return value_; }
234
235 private:
236 std::string value_;
237 };
238
TEST(RangeTest,WorksWithACustomType)239 TEST(RangeTest, WorksWithACustomType) {
240 const ParamGenerator<DogAdder> gen =
241 Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog"));
242 ParamGenerator<DogAdder>::iterator it = gen.begin();
243
244 ASSERT_FALSE(it == gen.end());
245 EXPECT_STREQ("cat", it->value().c_str());
246
247 ASSERT_FALSE(++it == gen.end());
248 EXPECT_STREQ("catdog", it->value().c_str());
249
250 EXPECT_TRUE(++it == gen.end());
251 }
252
253 class IntWrapper {
254 public:
IntWrapper(int a_value)255 explicit IntWrapper(int a_value) : value_(a_value) {}
IntWrapper(const IntWrapper & other)256 IntWrapper(const IntWrapper& other) : value_(other.value_) {}
257
operator =(const IntWrapper & other)258 IntWrapper operator=(const IntWrapper& other) {
259 value_ = other.value_;
260 return *this;
261 }
262 // operator+() adds a different type.
operator +(int other) const263 IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }
operator <(const IntWrapper & other) const264 bool operator<(const IntWrapper& other) const {
265 return value_ < other.value_;
266 }
value() const267 int value() const { return value_; }
268
269 private:
270 int value_;
271 };
272
TEST(RangeTest,WorksWithACustomTypeWithDifferentIncrementType)273 TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {
274 const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));
275 ParamGenerator<IntWrapper>::iterator it = gen.begin();
276
277 ASSERT_FALSE(it == gen.end());
278 EXPECT_EQ(0, it->value());
279
280 ASSERT_FALSE(++it == gen.end());
281 EXPECT_EQ(1, it->value());
282
283 EXPECT_TRUE(++it == gen.end());
284 }
285
286 // Tests that ValuesIn() with an array parameter generates
287 // the expected sequence.
TEST(ValuesInTest,ValuesInArray)288 TEST(ValuesInTest, ValuesInArray) {
289 int array[] = {3, 5, 8};
290 const ParamGenerator<int> gen = ValuesIn(array);
291 VerifyGenerator(gen, array);
292 }
293
294 // Tests that ValuesIn() with a const array parameter generates
295 // the expected sequence.
TEST(ValuesInTest,ValuesInConstArray)296 TEST(ValuesInTest, ValuesInConstArray) {
297 const int array[] = {3, 5, 8};
298 const ParamGenerator<int> gen = ValuesIn(array);
299 VerifyGenerator(gen, array);
300 }
301
302 // Edge case. Tests that ValuesIn() with an array parameter containing a
303 // single element generates the single element sequence.
TEST(ValuesInTest,ValuesInSingleElementArray)304 TEST(ValuesInTest, ValuesInSingleElementArray) {
305 int array[] = {42};
306 const ParamGenerator<int> gen = ValuesIn(array);
307 VerifyGenerator(gen, array);
308 }
309
310 // Tests that ValuesIn() generates the expected sequence for an STL
311 // container (vector).
TEST(ValuesInTest,ValuesInVector)312 TEST(ValuesInTest, ValuesInVector) {
313 typedef ::std::vector<int> ContainerType;
314 ContainerType values;
315 values.push_back(3);
316 values.push_back(5);
317 values.push_back(8);
318 const ParamGenerator<int> gen = ValuesIn(values);
319
320 const int expected_values[] = {3, 5, 8};
321 VerifyGenerator(gen, expected_values);
322 }
323
324 // Tests that ValuesIn() generates the expected sequence.
TEST(ValuesInTest,ValuesInIteratorRange)325 TEST(ValuesInTest, ValuesInIteratorRange) {
326 typedef ::std::vector<int> ContainerType;
327 ContainerType values;
328 values.push_back(3);
329 values.push_back(5);
330 values.push_back(8);
331 const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
332
333 const int expected_values[] = {3, 5, 8};
334 VerifyGenerator(gen, expected_values);
335 }
336
337 // Edge case. Tests that ValuesIn() provided with an iterator range specifying a
338 // single value generates a single-element sequence.
TEST(ValuesInTest,ValuesInSingleElementIteratorRange)339 TEST(ValuesInTest, ValuesInSingleElementIteratorRange) {
340 typedef ::std::vector<int> ContainerType;
341 ContainerType values;
342 values.push_back(42);
343 const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
344
345 const int expected_values[] = {42};
346 VerifyGenerator(gen, expected_values);
347 }
348
349 // Edge case. Tests that ValuesIn() provided with an empty iterator range
350 // generates an empty sequence.
TEST(ValuesInTest,ValuesInEmptyIteratorRange)351 TEST(ValuesInTest, ValuesInEmptyIteratorRange) {
352 typedef ::std::vector<int> ContainerType;
353 ContainerType values;
354 const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());
355
356 VerifyGeneratorIsEmpty(gen);
357 }
358
359 // Tests that the Values() generates the expected sequence.
TEST(ValuesTest,ValuesWorks)360 TEST(ValuesTest, ValuesWorks) {
361 const ParamGenerator<int> gen = Values(3, 5, 8);
362
363 const int expected_values[] = {3, 5, 8};
364 VerifyGenerator(gen, expected_values);
365 }
366
367 // Tests that Values() generates the expected sequences from elements of
368 // different types convertible to ParamGenerator's parameter type.
TEST(ValuesTest,ValuesWorksForValuesOfCompatibleTypes)369 TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
370 const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);
371
372 const double expected_values[] = {3.0, 5.0, 8.0};
373 VerifyGenerator(gen, expected_values);
374 }
375
TEST(ValuesTest,ValuesWorksForMaxLengthList)376 TEST(ValuesTest, ValuesWorksForMaxLengthList) {
377 const ParamGenerator<int> gen =
378 Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
379 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
380 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
381 420, 430, 440, 450, 460, 470, 480, 490, 500);
382
383 const int expected_values[] = {
384 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,
385 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
386 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
387 400, 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.
TEST(ValuesTest,ValuesWithSingleParameter)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).
TEST(BoolTest,BoolWorks)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.
TEST(CombineTest,CombineWithTwoParameters)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.
TEST(CombineTest,CombineWithThreeParameters)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.
TEST(CombineTest,CombineWithFirstParameterSingleValue)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.
TEST(CombineTest,CombineWithSecondParameterSingleValue)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.
TEST(CombineTest,CombineWithFirstParameterEmptyRange)459 TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
460 const ParamGenerator<std::tuple<int, int>> gen =
461 Combine(Range(0, 0), Values(0, 1));
462 VerifyGeneratorIsEmpty(gen);
463 }
464
465 // Tests that when the second parameter produces an empty sequence,
466 // Combine() produces an empty sequence, too.
TEST(CombineTest,CombineWithSecondParameterEmptyRange)467 TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
468 const ParamGenerator<std::tuple<int, int>> gen =
469 Combine(Values(0, 1), Range(1, 1));
470 VerifyGeneratorIsEmpty(gen);
471 }
472
473 // Edge case. Tests that combine works with the maximum number
474 // of parameters supported by Google Test (currently 10).
TEST(CombineTest,CombineWithMaxNumberOfParameters)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
490 class NonDefaultConstructAssignString {
491 public:
NonDefaultConstructAssignString(const std::string & s)492 NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
493 NonDefaultConstructAssignString() = delete;
494 NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =
495 default;
496 NonDefaultConstructAssignString& operator=(
497 const NonDefaultConstructAssignString&) = delete;
498 ~NonDefaultConstructAssignString() = default;
499
str() const500 const std::string& str() const { return str_; }
501
502 private:
503 std::string str_;
504 };
505
TEST(CombineTest,NonDefaultConstructAssign)506 TEST(CombineTest, NonDefaultConstructAssign) {
507 const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>> gen =
508 Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
509 NonDefaultConstructAssignString("B")));
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 template <typename T>
534 class ConstructFromT {
535 public:
ConstructFromT(const T & t)536 explicit ConstructFromT(const T& t) : t_(t) {}
537 template <typename... Args,
538 typename std::enable_if<sizeof...(Args) != 1, int>::type = 0>
ConstructFromT(Args &&...args)539 ConstructFromT(Args&&... args) : t_(std::forward<Args>(args)...) {}
540
operator ==(const ConstructFromT & other) const541 bool operator==(const ConstructFromT& other) const { return other.t_ == t_; }
542
get() const543 const T& get() const { return t_; }
544
545 private:
546 T t_;
547 };
548
TEST(ConvertTest,CombineWithTwoParameters)549 TEST(ConvertTest, CombineWithTwoParameters) {
550 const char* foo = "foo";
551 const char* bar = "bar";
552 const ParamGenerator<ConstructFromT<std::tuple<const char*, int>>> gen =
553 ConvertGenerator<std::tuple<const char*, int>>(
554 Combine(Values(foo, bar), Values(3, 4)));
555
556 ConstructFromT<std::tuple<const char*, int>> expected_values[] = {
557 {foo, 3}, {foo, 4}, {bar, 3}, {bar, 4}};
558 VerifyGenerator(gen, expected_values);
559 }
560
TEST(ConvertTest,NonDefaultConstructAssign)561 TEST(ConvertTest, NonDefaultConstructAssign) {
562 const ParamGenerator<
563 ConstructFromT<std::tuple<int, NonDefaultConstructAssignString>>>
564 gen = ConvertGenerator<std::tuple<int, NonDefaultConstructAssignString>>(
565 Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
566 NonDefaultConstructAssignString("B"))));
567
568 ParamGenerator<ConstructFromT<
569 std::tuple<int, NonDefaultConstructAssignString>>>::iterator it =
570 gen.begin();
571
572 EXPECT_EQ(0, std::get<0>(it->get()));
573 EXPECT_EQ("A", std::get<1>(it->get()).str());
574 ++it;
575
576 EXPECT_EQ(0, std::get<0>(it->get()));
577 EXPECT_EQ("B", std::get<1>(it->get()).str());
578 ++it;
579
580 EXPECT_EQ(1, std::get<0>(it->get()));
581 EXPECT_EQ("A", std::get<1>(it->get()).str());
582 ++it;
583
584 EXPECT_EQ(1, std::get<0>(it->get()));
585 EXPECT_EQ("B", std::get<1>(it->get()).str());
586 ++it;
587
588 EXPECT_TRUE(it == gen.end());
589 }
590
TEST(ConvertTest,WithConverterLambdaAndDeducedType)591 TEST(ConvertTest, WithConverterLambdaAndDeducedType) {
592 const ParamGenerator<ConstructFromT<int8_t>> gen =
593 ConvertGenerator(Values("0", std::string("1")), [](const std::string& s) {
594 size_t pos;
595 int64_t value = std::stoll(s, &pos);
596 EXPECT_EQ(pos, s.size());
597 return value;
598 });
599
600 ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
601 ConstructFromT<int8_t>(1)};
602 VerifyGenerator(gen, expected_values);
603 }
604
TEST(ConvertTest,WithConverterLambdaAndExplicitType)605 TEST(ConvertTest, WithConverterLambdaAndExplicitType) {
606 auto convert_generator = ConvertGenerator<std::string>(
607 Values("0", std::string("1")), [](std::string_view s) {
608 size_t pos;
609 int64_t value = std::stoll(std::string(s), &pos);
610 EXPECT_EQ(pos, s.size());
611 return value;
612 });
613 constexpr bool is_correct_type = std::is_same_v<
614 decltype(convert_generator),
615 testing::internal::ParamConverterGenerator<
616 std::string, std::function<int64_t(std::string_view)>>>;
617 EXPECT_TRUE(is_correct_type);
618 const ParamGenerator<ConstructFromT<int8_t>> gen = convert_generator;
619
620 ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
621 ConstructFromT<int8_t>(1)};
622 VerifyGenerator(gen, expected_values);
623 }
624
TEST(ConvertTest,WithConverterFunctionPointer)625 TEST(ConvertTest, WithConverterFunctionPointer) {
626 int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
627 size_t pos;
628 int64_t value = std::stoll(s, &pos);
629 EXPECT_EQ(pos, s.size());
630 return value;
631 };
632 const ParamGenerator<ConstructFromT<int8_t>> gen =
633 ConvertGenerator(Values("0", std::string("1")), func_ptr);
634
635 ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
636 ConstructFromT<int8_t>(1)};
637 VerifyGenerator(gen, expected_values);
638 }
639
TEST(ConvertTest,WithConverterFunctionReference)640 TEST(ConvertTest, WithConverterFunctionReference) {
641 int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
642 size_t pos;
643 int64_t value = std::stoll(s, &pos);
644 EXPECT_EQ(pos, s.size());
645 return value;
646 };
647 int64_t (&func_ref)(const std::string&) = *func_ptr;
648 const ParamGenerator<ConstructFromT<int8_t>> gen =
649 ConvertGenerator(Values("0", std::string("1")), func_ref);
650
651 ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
652 ConstructFromT<int8_t>(1)};
653 VerifyGenerator(gen, expected_values);
654 }
655
656 // Tests that an generator produces correct sequence after being
657 // assigned from another generator.
TEST(ParamGeneratorTest,AssignmentWorks)658 TEST(ParamGeneratorTest, AssignmentWorks) {
659 ParamGenerator<int> gen = Values(1, 2);
660 const ParamGenerator<int> gen2 = Values(3, 4);
661 gen = gen2;
662
663 const int expected_values[] = {3, 4};
664 VerifyGenerator(gen, expected_values);
665 }
666
667 // This test verifies that the tests are expanded and run as specified:
668 // one test per element from the sequence produced by the generator
669 // specified in INSTANTIATE_TEST_SUITE_P. It also verifies that the test's
670 // fixture constructor, SetUp(), and TearDown() have run and have been
671 // supplied with the correct parameters.
672
673 // The use of environment object allows detection of the case where no test
674 // case functionality is run at all. In this case TearDownTestSuite will not
675 // be able to detect missing tests, naturally.
676 template <int kExpectedCalls>
677 class TestGenerationEnvironment : public ::testing::Environment {
678 public:
Instance()679 static TestGenerationEnvironment* Instance() {
680 static TestGenerationEnvironment* instance = new TestGenerationEnvironment;
681 return instance;
682 }
683
FixtureConstructorExecuted()684 void FixtureConstructorExecuted() { fixture_constructor_count_++; }
SetUpExecuted()685 void SetUpExecuted() { set_up_count_++; }
TearDownExecuted()686 void TearDownExecuted() { tear_down_count_++; }
TestBodyExecuted()687 void TestBodyExecuted() { test_body_count_++; }
688
TearDown()689 void TearDown() override {
690 // If all MultipleTestGenerationTest tests have been de-selected
691 // by the filter flag, the following checks make no sense.
692 bool perform_check = false;
693
694 for (int i = 0; i < kExpectedCalls; ++i) {
695 Message msg;
696 msg << "TestsExpandedAndRun/" << i;
697 if (UnitTestOptions::FilterMatchesTest(
698 "TestExpansionModule/MultipleTestGenerationTest",
699 msg.GetString().c_str())) {
700 perform_check = true;
701 }
702 }
703 if (perform_check) {
704 EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)
705 << "Fixture constructor of ParamTestGenerationTest test case "
706 << "has not been run as expected.";
707 EXPECT_EQ(kExpectedCalls, set_up_count_)
708 << "Fixture SetUp method of ParamTestGenerationTest test case "
709 << "has not been run as expected.";
710 EXPECT_EQ(kExpectedCalls, tear_down_count_)
711 << "Fixture TearDown method of ParamTestGenerationTest test case "
712 << "has not been run as expected.";
713 EXPECT_EQ(kExpectedCalls, test_body_count_)
714 << "Test in ParamTestGenerationTest test case "
715 << "has not been run as expected.";
716 }
717 }
718
719 private:
TestGenerationEnvironment()720 TestGenerationEnvironment()
721 : fixture_constructor_count_(0),
722 set_up_count_(0),
723 tear_down_count_(0),
724 test_body_count_(0) {}
725
726 int fixture_constructor_count_;
727 int set_up_count_;
728 int tear_down_count_;
729 int test_body_count_;
730
731 TestGenerationEnvironment(const TestGenerationEnvironment&) = delete;
732 TestGenerationEnvironment& operator=(const TestGenerationEnvironment&) =
733 delete;
734 };
735
736 const int test_generation_params[] = {36, 42, 72};
737
738 class TestGenerationTest : public TestWithParam<int> {
739 public:
740 enum {
741 PARAMETER_COUNT =
742 sizeof(test_generation_params) / sizeof(test_generation_params[0])
743 };
744
745 typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
746
TestGenerationTest()747 TestGenerationTest() {
748 Environment::Instance()->FixtureConstructorExecuted();
749 current_parameter_ = GetParam();
750 }
SetUp()751 void SetUp() override {
752 Environment::Instance()->SetUpExecuted();
753 EXPECT_EQ(current_parameter_, GetParam());
754 }
TearDown()755 void TearDown() override {
756 Environment::Instance()->TearDownExecuted();
757 EXPECT_EQ(current_parameter_, GetParam());
758 }
759
SetUpTestSuite()760 static void SetUpTestSuite() {
761 bool all_tests_in_test_case_selected = true;
762
763 for (int i = 0; i < PARAMETER_COUNT; ++i) {
764 Message test_name;
765 test_name << "TestsExpandedAndRun/" << i;
766 if (!UnitTestOptions::FilterMatchesTest(
767 "TestExpansionModule/MultipleTestGenerationTest",
768 test_name.GetString())) {
769 all_tests_in_test_case_selected = false;
770 }
771 }
772 EXPECT_TRUE(all_tests_in_test_case_selected)
773 << "When running the TestGenerationTest test case all of its tests\n"
774 << "must be selected by the filter flag for the test case to pass.\n"
775 << "If not all of them are enabled, we can't reliably conclude\n"
776 << "that the correct number of tests have been generated.";
777
778 collected_parameters_.clear();
779 }
780
TearDownTestSuite()781 static void TearDownTestSuite() {
782 vector<int> expected_values(test_generation_params,
783 test_generation_params + PARAMETER_COUNT);
784 // Test execution order is not guaranteed by Google Test,
785 // so the order of values in collected_parameters_ can be
786 // different and we have to sort to compare.
787 sort(expected_values.begin(), expected_values.end());
788 sort(collected_parameters_.begin(), collected_parameters_.end());
789
790 EXPECT_TRUE(collected_parameters_ == expected_values);
791 }
792
793 protected:
794 int current_parameter_;
795 static vector<int> collected_parameters_;
796
797 private:
798 TestGenerationTest(const TestGenerationTest&) = delete;
799 TestGenerationTest& operator=(const TestGenerationTest&) = delete;
800 };
801 vector<int> TestGenerationTest::collected_parameters_;
802
TEST_P(TestGenerationTest,TestsExpandedAndRun)803 TEST_P(TestGenerationTest, TestsExpandedAndRun) {
804 Environment::Instance()->TestBodyExecuted();
805 EXPECT_EQ(current_parameter_, GetParam());
806 collected_parameters_.push_back(GetParam());
807 }
808 INSTANTIATE_TEST_SUITE_P(TestExpansionModule, TestGenerationTest,
809 ValuesIn(test_generation_params));
810
811 // This test verifies that the element sequence (third parameter of
812 // INSTANTIATE_TEST_SUITE_P) is evaluated in InitGoogleTest() and neither at
813 // the call site of INSTANTIATE_TEST_SUITE_P nor in RUN_ALL_TESTS(). For
814 // that, we declare param_value_ to be a static member of
815 // GeneratorEvaluationTest and initialize it to 0. We set it to 1 in
816 // main(), just before invocation of InitGoogleTest(). After calling
817 // InitGoogleTest(), we set the value to 2. If the sequence is evaluated
818 // before or after InitGoogleTest, INSTANTIATE_TEST_SUITE_P will create a
819 // test with parameter other than 1, and the test body will fail the
820 // assertion.
821 class GeneratorEvaluationTest : public TestWithParam<int> {
822 public:
param_value()823 static int param_value() { return param_value_; }
set_param_value(int param_value)824 static void set_param_value(int param_value) { param_value_ = param_value; }
825
826 private:
827 static int param_value_;
828 };
829 int GeneratorEvaluationTest::param_value_ = 0;
830
TEST_P(GeneratorEvaluationTest,GeneratorsEvaluatedInMain)831 TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {
832 EXPECT_EQ(1, GetParam());
833 }
834 INSTANTIATE_TEST_SUITE_P(GenEvalModule, GeneratorEvaluationTest,
835 Values(GeneratorEvaluationTest::param_value()));
836
837 // Tests that generators defined in a different translation unit are
838 // functional. Generator extern_gen is defined in gtest-param-test_test2.cc.
839 extern ParamGenerator<int> extern_gen;
840 class ExternalGeneratorTest : public TestWithParam<int> {};
TEST_P(ExternalGeneratorTest,ExternalGenerator)841 TEST_P(ExternalGeneratorTest, ExternalGenerator) {
842 // Sequence produced by extern_gen contains only a single value
843 // which we verify here.
844 EXPECT_EQ(GetParam(), 33);
845 }
846 INSTANTIATE_TEST_SUITE_P(ExternalGeneratorModule, ExternalGeneratorTest,
847 extern_gen);
848
849 // Tests that a parameterized test case can be defined in one translation
850 // unit and instantiated in another. This test will be instantiated in
851 // gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is
852 // defined in gtest-param-test_test.h.
TEST_P(ExternalInstantiationTest,IsMultipleOf33)853 TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
854 EXPECT_EQ(0, GetParam() % 33);
855 }
856
857 // Tests that a parameterized test case can be instantiated with multiple
858 // generators.
859 class MultipleInstantiationTest : public TestWithParam<int> {};
TEST_P(MultipleInstantiationTest,AllowsMultipleInstances)860 TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}
861 INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
862 INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
863
864 // Tests that a parameterized test case can be instantiated
865 // in multiple translation units. This test will be instantiated
866 // here and in gtest-param-test_test2.cc.
867 // InstantiationInMultipleTranslationUnitsTest fixture class
868 // is defined in gtest-param-test_test.h.
TEST_P(InstantiationInMultipleTranslationUnitsTest,IsMultipleOf42)869 TEST_P(InstantiationInMultipleTranslationUnitsTest, IsMultipleOf42) {
870 EXPECT_EQ(0, GetParam() % 42);
871 }
872 INSTANTIATE_TEST_SUITE_P(Sequence1, InstantiationInMultipleTranslationUnitsTest,
873 Values(42, 42 * 2));
874
875 // Tests that each iteration of parameterized test runs in a separate test
876 // object.
877 class SeparateInstanceTest : public TestWithParam<int> {
878 public:
SeparateInstanceTest()879 SeparateInstanceTest() : count_(0) {}
880
TearDownTestSuite()881 static void TearDownTestSuite() {
882 EXPECT_GE(global_count_, 2)
883 << "If some (but not all) SeparateInstanceTest tests have been "
884 << "filtered out this test will fail. Make sure that all "
885 << "GeneratorEvaluationTest are selected or de-selected together "
886 << "by the test filter.";
887 }
888
889 protected:
890 int count_;
891 static int global_count_;
892 };
893 int SeparateInstanceTest::global_count_ = 0;
894
TEST_P(SeparateInstanceTest,TestsRunInSeparateInstances)895 TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {
896 EXPECT_EQ(0, count_++);
897 global_count_++;
898 }
899 INSTANTIATE_TEST_SUITE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));
900
901 // Tests that all instantiations of a test have named appropriately. Test
902 // defined with TEST_P(TestSuiteName, TestName) and instantiated with
903 // INSTANTIATE_TEST_SUITE_P(SequenceName, TestSuiteName, generator) must be
904 // named SequenceName/TestSuiteName.TestName/i, where i is the 0-based index of
905 // the sequence element used to instantiate the test.
906 class NamingTest : public TestWithParam<int> {};
907
TEST_P(NamingTest,TestsReportCorrectNamesAndParameters)908 TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
909 const ::testing::TestInfo* const test_info =
910 ::testing::UnitTest::GetInstance()->current_test_info();
911
912 EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name());
913
914 Message index_stream;
915 index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam();
916 EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());
917
918 EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
919 }
920
921 INSTANTIATE_TEST_SUITE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
922
923 // Tests that macros in test names are expanded correctly.
924 class MacroNamingTest : public TestWithParam<int> {};
925
926 #define PREFIX_WITH_FOO(test_name) Foo##test_name
927 #define PREFIX_WITH_MACRO(test_name) Macro##test_name
928
TEST_P(PREFIX_WITH_MACRO (NamingTest),PREFIX_WITH_FOO (SomeTestName))929 TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {
930 const ::testing::TestInfo* const test_info =
931 ::testing::UnitTest::GetInstance()->current_test_info();
932
933 EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name());
934 EXPECT_STREQ("FooSomeTestName/0", test_info->name());
935 }
936
937 INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42));
938
939 // Tests the same thing for non-parametrized tests.
940 class MacroNamingTestNonParametrized : public ::testing::Test {};
941
TEST_F(PREFIX_WITH_MACRO (NamingTestNonParametrized),PREFIX_WITH_FOO (SomeTestName))942 TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized),
943 PREFIX_WITH_FOO(SomeTestName)) {
944 const ::testing::TestInfo* const test_info =
945 ::testing::UnitTest::GetInstance()->current_test_info();
946
947 EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name());
948 EXPECT_STREQ("FooSomeTestName", test_info->name());
949 }
950
TEST(MacroNameing,LookupNames)951 TEST(MacroNameing, LookupNames) {
952 std::set<std::string> know_suite_names, know_test_names;
953
954 const auto& ins = testing::UnitTest::GetInstance();
955 int ts = 0;
956 while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) {
957 know_suite_names.insert(suite->name());
958
959 int ti = 0;
960 while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) {
961 know_test_names.insert(std::string(suite->name()) + "." + info->name());
962 }
963 }
964
965 // Check that the expected form of the test suit name actually exists.
966 EXPECT_NE( //
967 know_suite_names.find("FortyTwo/MacroNamingTest"),
968 know_suite_names.end());
969 EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
970 know_suite_names.end());
971 // Check that the expected form of the test name actually exists.
972 EXPECT_NE( //
973 know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
974 know_test_names.end());
975 EXPECT_NE(
976 know_test_names.find("MacroNamingTestNonParametrized.FooSomeTestName"),
977 know_test_names.end());
978 }
979
980 // Tests that user supplied custom parameter names are working correctly.
981 // Runs the test with a builtin helper method which uses PrintToString,
982 // as well as a custom function and custom functor to ensure all possible
983 // uses work correctly.
984 class CustomFunctorNamingTest : public TestWithParam<std::string> {};
TEST_P(CustomFunctorNamingTest,CustomTestNames)985 TEST_P(CustomFunctorNamingTest, CustomTestNames) {}
986
987 struct CustomParamNameFunctor {
operator ()CustomParamNameFunctor988 std::string operator()(const ::testing::TestParamInfo<std::string>& inf) {
989 return inf.param;
990 }
991 };
992
993 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctor, CustomFunctorNamingTest,
994 Values(std::string("FunctorName")),
995 CustomParamNameFunctor());
996
997 INSTANTIATE_TEST_SUITE_P(AllAllowedCharacters, CustomFunctorNamingTest,
998 Values("abcdefghijklmnopqrstuvwxyz",
999 "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "01234567890_"),
1000 CustomParamNameFunctor());
1001
CustomParamNameFunction(const::testing::TestParamInfo<std::string> & inf)1002 inline std::string CustomParamNameFunction(
1003 const ::testing::TestParamInfo<std::string>& inf) {
1004 return inf.param;
1005 }
1006
1007 class CustomFunctionNamingTest : public TestWithParam<std::string> {};
TEST_P(CustomFunctionNamingTest,CustomTestNames)1008 TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
1009
1010 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunction, CustomFunctionNamingTest,
1011 Values(std::string("FunctionName")),
1012 CustomParamNameFunction);
1013
1014 INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctionP, CustomFunctionNamingTest,
1015 Values(std::string("FunctionNameP")),
1016 &CustomParamNameFunction);
1017
1018 // Test custom naming with a lambda
1019
1020 class CustomLambdaNamingTest : public TestWithParam<std::string> {};
TEST_P(CustomLambdaNamingTest,CustomTestNames)1021 TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
1022
1023 INSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest,
1024 Values(std::string("LambdaName")),
__anon45bb9d110602(const ::testing::TestParamInfo<std::string>& inf) 1025 [](const ::testing::TestParamInfo<std::string>& inf) {
1026 return inf.param;
1027 });
1028
TEST(CustomNamingTest,CheckNameRegistry)1029 TEST(CustomNamingTest, CheckNameRegistry) {
1030 const auto& unit_test = ::testing::UnitTest::GetInstance();
1031 std::set<std::string> test_names;
1032 for (int suite_num = 0; suite_num < unit_test->total_test_suite_count();
1033 ++suite_num) {
1034 const ::testing::TestSuite* test_suite = unit_test->GetTestSuite(suite_num);
1035 for (int test_num = 0; test_num < test_suite->total_test_count();
1036 ++test_num) {
1037 const ::testing::TestInfo* test_info = test_suite->GetTestInfo(test_num);
1038 test_names.insert(std::string(test_info->name()));
1039 }
1040 }
1041 EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName"));
1042 EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName"));
1043 EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionNameP"));
1044 EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName"));
1045 }
1046
1047 // Test a numeric name to ensure PrintToStringParamName works correctly.
1048
1049 class CustomIntegerNamingTest : public TestWithParam<int> {};
1050
TEST_P(CustomIntegerNamingTest,TestsReportCorrectNames)1051 TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
1052 const ::testing::TestInfo* const test_info =
1053 ::testing::UnitTest::GetInstance()->current_test_info();
1054 Message test_name_stream;
1055 test_name_stream << "TestsReportCorrectNames/" << GetParam();
1056 EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
1057 }
1058
1059 INSTANTIATE_TEST_SUITE_P(PrintToString, CustomIntegerNamingTest, Range(0, 5),
1060 ::testing::PrintToStringParamName());
1061
1062 // Test a custom struct with PrintToString.
1063
1064 struct CustomStruct {
CustomStructCustomStruct1065 explicit CustomStruct(int value) : x(value) {}
1066 int x;
1067 };
1068
operator <<(std::ostream & stream,const CustomStruct & val)1069 std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
1070 stream << val.x;
1071 return stream;
1072 }
1073
1074 class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
1075
TEST_P(CustomStructNamingTest,TestsReportCorrectNames)1076 TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
1077 const ::testing::TestInfo* const test_info =
1078 ::testing::UnitTest::GetInstance()->current_test_info();
1079 Message test_name_stream;
1080 test_name_stream << "TestsReportCorrectNames/" << GetParam();
1081 EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
1082 }
1083
1084 INSTANTIATE_TEST_SUITE_P(PrintToString, CustomStructNamingTest,
1085 Values(CustomStruct(0), CustomStruct(1)),
1086 ::testing::PrintToStringParamName());
1087
1088 // Test that using a stateful parameter naming function works as expected.
1089
1090 struct StatefulNamingFunctor {
StatefulNamingFunctorStatefulNamingFunctor1091 StatefulNamingFunctor() : sum(0) {}
operator ()StatefulNamingFunctor1092 std::string operator()(const ::testing::TestParamInfo<int>& info) {
1093 int value = info.param + sum;
1094 sum += info.param;
1095 return ::testing::PrintToString(value);
1096 }
1097 int sum;
1098 };
1099
1100 class StatefulNamingTest : public ::testing::TestWithParam<int> {
1101 protected:
StatefulNamingTest()1102 StatefulNamingTest() : sum_(0) {}
1103 int sum_;
1104 };
1105
TEST_P(StatefulNamingTest,TestsReportCorrectNames)1106 TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
1107 const ::testing::TestInfo* const test_info =
1108 ::testing::UnitTest::GetInstance()->current_test_info();
1109 sum_ += GetParam();
1110 Message test_name_stream;
1111 test_name_stream << "TestsReportCorrectNames/" << sum_;
1112 EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
1113 }
1114
1115 INSTANTIATE_TEST_SUITE_P(StatefulNamingFunctor, StatefulNamingTest, Range(0, 5),
1116 StatefulNamingFunctor());
1117
1118 // Class that cannot be streamed into an ostream. It needs to be copyable
1119 // (and, in case of MSVC, also assignable) in order to be a test parameter
1120 // type. Its default copy constructor and assignment operator do exactly
1121 // what we need.
1122 class Unstreamable {
1123 public:
Unstreamable(int value)1124 explicit Unstreamable(int value) : value_(value) {}
1125 // -Wunused-private-field: dummy accessor for `value_`.
dummy_value() const1126 const int& dummy_value() const { return value_; }
1127
1128 private:
1129 int value_;
1130 };
1131
1132 class CommentTest : public TestWithParam<Unstreamable> {};
1133
TEST_P(CommentTest,TestsCorrectlyReportUnstreamableParams)1134 TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
1135 const ::testing::TestInfo* const test_info =
1136 ::testing::UnitTest::GetInstance()->current_test_info();
1137
1138 EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
1139 }
1140
1141 INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
1142 Values(Unstreamable(1)));
1143
1144 // Verify that we can create a hierarchy of test fixtures, where the base
1145 // class fixture is not parameterized and the derived class is. In this case
1146 // ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We
1147 // perform simple tests on both.
1148 class NonParameterizedBaseTest : public ::testing::Test {
1149 public:
NonParameterizedBaseTest()1150 NonParameterizedBaseTest() : n_(17) {}
1151
1152 protected:
1153 int n_;
1154 };
1155
1156 class ParameterizedDerivedTest : public NonParameterizedBaseTest,
1157 public ::testing::WithParamInterface<int> {
1158 protected:
ParameterizedDerivedTest()1159 ParameterizedDerivedTest() : count_(0) {}
1160 int count_;
1161 static int global_count_;
1162 };
1163
1164 int ParameterizedDerivedTest::global_count_ = 0;
1165
TEST_F(NonParameterizedBaseTest,FixtureIsInitialized)1166 TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
1167
TEST_P(ParameterizedDerivedTest,SeesSequence)1168 TEST_P(ParameterizedDerivedTest, SeesSequence) {
1169 EXPECT_EQ(17, n_);
1170 EXPECT_EQ(0, count_++);
1171 EXPECT_EQ(GetParam(), global_count_++);
1172 }
1173
1174 class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
1175
TEST_F(ParameterizedDeathTest,GetParamDiesFromTestF)1176 TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
1177 EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
1178 }
1179
1180 INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
1181 Range(0, 5));
1182
1183 // Tests param generator working with Enums
1184 enum MyEnums {
1185 ENUM1 = 1,
1186 ENUM2 = 3,
1187 ENUM3 = 8,
1188 };
1189
1190 class MyEnumTest : public testing::TestWithParam<MyEnums> {};
1191
TEST_P(MyEnumTest,ChecksParamMoreThanZero)1192 TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
1193 INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,
1194 ::testing::Values(ENUM1, ENUM2, 0));
1195
1196 namespace works_here {
1197 // Never used not instantiated, this should work.
1198 class NotUsedTest : public testing::TestWithParam<int> {};
1199
1200 ///////
1201 // Never used not instantiated, this should work.
1202 template <typename T>
1203 class NotUsedTypeTest : public testing::Test {};
1204 TYPED_TEST_SUITE_P(NotUsedTypeTest);
1205
1206 // Used but not instantiated, this would fail. but...
1207 class NotInstantiatedTest : public testing::TestWithParam<int> {};
1208 // ... we mark is as allowed.
1209 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
1210
TEST_P(NotInstantiatedTest,Used)1211 TEST_P(NotInstantiatedTest, Used) {}
1212
1213 using OtherName = NotInstantiatedTest;
1214 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
TEST_P(OtherName,Used)1215 TEST_P(OtherName, Used) {}
1216
1217 // Used but not instantiated, this would fail. but...
1218 template <typename T>
1219 class NotInstantiatedTypeTest : public testing::Test {};
1220 TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
1221 // ... we mark is as allowed.
1222 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
1223
TYPED_TEST_P(NotInstantiatedTypeTest,Used)1224 TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
1225 REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
1226 } // namespace works_here
1227
main(int argc,char ** argv)1228 int main(int argc, char** argv) {
1229 // Used in TestGenerationTest test suite.
1230 AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
1231 // Used in GeneratorEvaluationTest test suite. Tests that the updated value
1232 // will be picked up for instantiating tests in GeneratorEvaluationTest.
1233 GeneratorEvaluationTest::set_param_value(1);
1234
1235 ::testing::InitGoogleTest(&argc, argv);
1236
1237 // Used in GeneratorEvaluationTest test suite. Tests that value updated
1238 // here will NOT be used for instantiating tests in
1239 // GeneratorEvaluationTest.
1240 GeneratorEvaluationTest::set_param_value(2);
1241
1242 return RUN_ALL_TESTS();
1243 }
1244