Coverage Report

Created: 2026-01-13 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/perfetto/buildtools/googletest/googletest/include/gtest/gtest-param-test.h
Line
Count
Source
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
// Macros and functions for implementing parameterized tests
31
// in Google C++ Testing and Mocking Framework (Google Test)
32
//
33
// GOOGLETEST_CM0001 DO NOT DELETE
34
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
35
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
36
37
38
// Value-parameterized tests allow you to test your code with different
39
// parameters without writing multiple copies of the same test.
40
//
41
// Here is how you use value-parameterized tests:
42
43
#if 0
44
45
// To write value-parameterized tests, first you should define a fixture
46
// class. It is usually derived from testing::TestWithParam<T> (see below for
47
// another inheritance scheme that's sometimes useful in more complicated
48
// class hierarchies), where the type of your parameter values.
49
// TestWithParam<T> is itself derived from testing::Test. T can be any
50
// copyable type. If it's a raw pointer, you are responsible for managing the
51
// lifespan of the pointed values.
52
53
class FooTest : public ::testing::TestWithParam<const char*> {
54
  // You can implement all the usual class fixture members here.
55
};
56
57
// Then, use the TEST_P macro to define as many parameterized tests
58
// for this fixture as you want. The _P suffix is for "parameterized"
59
// or "pattern", whichever you prefer to think.
60
61
TEST_P(FooTest, DoesBlah) {
62
  // Inside a test, access the test parameter with the GetParam() method
63
  // of the TestWithParam<T> class:
64
  EXPECT_TRUE(foo.Blah(GetParam()));
65
  ...
66
}
67
68
TEST_P(FooTest, HasBlahBlah) {
69
  ...
70
}
71
72
// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
73
// case with any set of parameters you want. Google Test defines a number
74
// of functions for generating test parameters. They return what we call
75
// (surprise!) parameter generators. Here is a summary of them, which
76
// are all in the testing namespace:
77
//
78
//
79
//  Range(begin, end [, step]) - Yields values {begin, begin+step,
80
//                               begin+step+step, ...}. The values do not
81
//                               include end. step defaults to 1.
82
//  Values(v1, v2, ..., vN)    - Yields values {v1, v2, ..., vN}.
83
//  ValuesIn(container)        - Yields values from a C-style array, an STL
84
//  ValuesIn(begin,end)          container, or an iterator range [begin, end).
85
//  Bool()                     - Yields sequence {false, true}.
86
//  Combine(g1, g2, ..., gN)   - Yields all combinations (the Cartesian product
87
//                               for the math savvy) of the values generated
88
//                               by the N generators.
89
//
90
// For more details, see comments at the definitions of these functions below
91
// in this file.
92
//
93
// The following statement will instantiate tests from the FooTest test suite
94
// each with parameter values "meeny", "miny", and "moe".
95
96
INSTANTIATE_TEST_SUITE_P(InstantiationName,
97
                         FooTest,
98
                         Values("meeny", "miny", "moe"));
99
100
// To distinguish different instances of the pattern, (yes, you
101
// can instantiate it more than once) the first argument to the
102
// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
103
// actual test suite name. Remember to pick unique prefixes for different
104
// instantiations. The tests from the instantiation above will have
105
// these names:
106
//
107
//    * InstantiationName/FooTest.DoesBlah/0 for "meeny"
108
//    * InstantiationName/FooTest.DoesBlah/1 for "miny"
109
//    * InstantiationName/FooTest.DoesBlah/2 for "moe"
110
//    * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
111
//    * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
112
//    * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
113
//
114
// You can use these names in --gtest_filter.
115
//
116
// This statement will instantiate all tests from FooTest again, each
117
// with parameter values "cat" and "dog":
118
119
const char* pets[] = {"cat", "dog"};
120
INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
121
122
// The tests from the instantiation above will have these names:
123
//
124
//    * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
125
//    * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
126
//    * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
127
//    * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
128
//
129
// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
130
// in the given test suite, whether their definitions come before or
131
// AFTER the INSTANTIATE_TEST_SUITE_P statement.
132
//
133
// Please also note that generator expressions (including parameters to the
134
// generators) are evaluated in InitGoogleTest(), after main() has started.
135
// This allows the user on one hand, to adjust generator parameters in order
136
// to dynamically determine a set of tests to run and on the other hand,
137
// give the user a chance to inspect the generated tests with Google Test
138
// reflection API before RUN_ALL_TESTS() is executed.
139
//
140
// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
141
// for more examples.
142
//
143
// In the future, we plan to publish the API for defining new parameter
144
// generators. But for now this interface remains part of the internal
145
// implementation and is subject to change.
146
//
147
//
148
// A parameterized test fixture must be derived from testing::Test and from
149
// testing::WithParamInterface<T>, where T is the type of the parameter
150
// values. Inheriting from TestWithParam<T> satisfies that requirement because
151
// TestWithParam<T> inherits from both Test and WithParamInterface. In more
152
// complicated hierarchies, however, it is occasionally useful to inherit
153
// separately from Test and WithParamInterface. For example:
154
155
class BaseTest : public ::testing::Test {
156
  // You can inherit all the usual members for a non-parameterized test
157
  // fixture here.
158
};
159
160
class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
161
  // The usual test fixture members go here too.
162
};
163
164
TEST_F(BaseTest, HasFoo) {
165
  // This is an ordinary non-parameterized test.
166
}
167
168
TEST_P(DerivedTest, DoesBlah) {
169
  // GetParam works just the same here as if you inherit from TestWithParam.
170
  EXPECT_TRUE(foo.Blah(GetParam()));
171
}
172
173
#endif  // 0
174
175
#include <iterator>
176
#include <utility>
177
178
#include "gtest/internal/gtest-internal.h"
179
#include "gtest/internal/gtest-param-util.h"
180
#include "gtest/internal/gtest-port.h"
181
182
namespace testing {
183
184
// Functions producing parameter generators.
185
//
186
// Google Test uses these generators to produce parameters for value-
187
// parameterized tests. When a parameterized test suite is instantiated
188
// with a particular generator, Google Test creates and runs tests
189
// for each element in the sequence produced by the generator.
190
//
191
// In the following sample, tests from test suite FooTest are instantiated
192
// each three times with parameter values 3, 5, and 8:
193
//
194
// class FooTest : public TestWithParam<int> { ... };
195
//
196
// TEST_P(FooTest, TestThis) {
197
// }
198
// TEST_P(FooTest, TestThat) {
199
// }
200
// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
201
//
202
203
// Range() returns generators providing sequences of values in a range.
204
//
205
// Synopsis:
206
// Range(start, end)
207
//   - returns a generator producing a sequence of values {start, start+1,
208
//     start+2, ..., }.
209
// Range(start, end, step)
210
//   - returns a generator producing a sequence of values {start, start+step,
211
//     start+step+step, ..., }.
212
// Notes:
213
//   * The generated sequences never include end. For example, Range(1, 5)
214
//     returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
215
//     returns a generator producing {1, 3, 5, 7}.
216
//   * start and end must have the same type. That type may be any integral or
217
//     floating-point type or a user defined type satisfying these conditions:
218
//     * It must be assignable (have operator=() defined).
219
//     * It must have operator+() (operator+(int-compatible type) for
220
//       two-operand version).
221
//     * It must have operator<() defined.
222
//     Elements in the resulting sequences will also have that type.
223
//   * Condition start < end must be satisfied in order for resulting sequences
224
//     to contain any elements.
225
//
226
template <typename T, typename IncrementT>
227
internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
228
  return internal::ParamGenerator<T>(
229
      new internal::RangeGenerator<T, IncrementT>(start, end, step));
230
}
231
232
template <typename T>
233
internal::ParamGenerator<T> Range(T start, T end) {
234
  return Range(start, end, 1);
235
}
236
237
// ValuesIn() function allows generation of tests with parameters coming from
238
// a container.
239
//
240
// Synopsis:
241
// ValuesIn(const T (&array)[N])
242
//   - returns a generator producing sequences with elements from
243
//     a C-style array.
244
// ValuesIn(const Container& container)
245
//   - returns a generator producing sequences with elements from
246
//     an STL-style container.
247
// ValuesIn(Iterator begin, Iterator end)
248
//   - returns a generator producing sequences with elements from
249
//     a range [begin, end) defined by a pair of STL-style iterators. These
250
//     iterators can also be plain C pointers.
251
//
252
// Please note that ValuesIn copies the values from the containers
253
// passed in and keeps them to generate tests in RUN_ALL_TESTS().
254
//
255
// Examples:
256
//
257
// This instantiates tests from test suite StringTest
258
// each with C-string values of "foo", "bar", and "baz":
259
//
260
// const char* strings[] = {"foo", "bar", "baz"};
261
// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
262
//
263
// This instantiates tests from test suite StlStringTest
264
// each with STL strings with values "a" and "b":
265
//
266
// ::std::vector< ::std::string> GetParameterStrings() {
267
//   ::std::vector< ::std::string> v;
268
//   v.push_back("a");
269
//   v.push_back("b");
270
//   return v;
271
// }
272
//
273
// INSTANTIATE_TEST_SUITE_P(CharSequence,
274
//                          StlStringTest,
275
//                          ValuesIn(GetParameterStrings()));
276
//
277
//
278
// This will also instantiate tests from CharTest
279
// each with parameter values 'a' and 'b':
280
//
281
// ::std::list<char> GetParameterChars() {
282
//   ::std::list<char> list;
283
//   list.push_back('a');
284
//   list.push_back('b');
285
//   return list;
286
// }
287
// ::std::list<char> l = GetParameterChars();
288
// INSTANTIATE_TEST_SUITE_P(CharSequence2,
289
//                          CharTest,
290
//                          ValuesIn(l.begin(), l.end()));
291
//
292
template <typename ForwardIterator>
293
internal::ParamGenerator<
294
    typename std::iterator_traits<ForwardIterator>::value_type>
295
0
ValuesIn(ForwardIterator begin, ForwardIterator end) {
296
0
  typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
297
0
  return internal::ParamGenerator<ParamType>(
298
0
      new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
299
0
}
300
301
template <typename T, size_t N>
302
internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
303
  return ValuesIn(array, array + N);
304
}
305
306
template <class Container>
307
internal::ParamGenerator<typename Container::value_type> ValuesIn(
308
0
    const Container& container) {
309
0
  return ValuesIn(container.begin(), container.end());
310
0
}
311
312
// Values() allows generating tests from explicitly specified list of
313
// parameters.
314
//
315
// Synopsis:
316
// Values(T v1, T v2, ..., T vN)
317
//   - returns a generator producing sequences with elements v1, v2, ..., vN.
318
//
319
// For example, this instantiates tests from test suite BarTest each
320
// with values "one", "two", and "three":
321
//
322
// INSTANTIATE_TEST_SUITE_P(NumSequence,
323
//                          BarTest,
324
//                          Values("one", "two", "three"));
325
//
326
// This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
327
// The exact type of values will depend on the type of parameter in BazTest.
328
//
329
// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
330
//
331
//
332
template <typename... T>
333
0
internal::ValueArray<T...> Values(T... v) {
334
0
  return internal::ValueArray<T...>(std::move(v)...);
335
0
}
336
337
// Bool() allows generating tests with parameters in a set of (false, true).
338
//
339
// Synopsis:
340
// Bool()
341
//   - returns a generator producing sequences with elements {false, true}.
342
//
343
// It is useful when testing code that depends on Boolean flags. Combinations
344
// of multiple flags can be tested when several Bool()'s are combined using
345
// Combine() function.
346
//
347
// In the following example all tests in the test suite FlagDependentTest
348
// will be instantiated twice with parameters false and true.
349
//
350
// class FlagDependentTest : public testing::TestWithParam<bool> {
351
//   virtual void SetUp() {
352
//     external_flag = GetParam();
353
//   }
354
// }
355
// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
356
//
357
0
inline internal::ParamGenerator<bool> Bool() {
358
0
  return Values(false, true);
359
0
}
360
361
// Combine() allows the user to combine two or more sequences to produce
362
// values of a Cartesian product of those sequences' elements.
363
//
364
// Synopsis:
365
// Combine(gen1, gen2, ..., genN)
366
//   - returns a generator producing sequences with elements coming from
367
//     the Cartesian product of elements from the sequences generated by
368
//     gen1, gen2, ..., genN. The sequence elements will have a type of
369
//     std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
370
//     of elements from sequences produces by gen1, gen2, ..., genN.
371
//
372
// Example:
373
//
374
// This will instantiate tests in test suite AnimalTest each one with
375
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
376
// tuple("dog", BLACK), and tuple("dog", WHITE):
377
//
378
// enum Color { BLACK, GRAY, WHITE };
379
// class AnimalTest
380
//     : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
381
//
382
// TEST_P(AnimalTest, AnimalLooksNice) {...}
383
//
384
// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
385
//                          Combine(Values("cat", "dog"),
386
//                                  Values(BLACK, WHITE)));
387
//
388
// This will instantiate tests in FlagDependentTest with all variations of two
389
// Boolean flags:
390
//
391
// class FlagDependentTest
392
//     : public testing::TestWithParam<std::tuple<bool, bool> > {
393
//   virtual void SetUp() {
394
//     // Assigns external_flag_1 and external_flag_2 values from the tuple.
395
//     std::tie(external_flag_1, external_flag_2) = GetParam();
396
//   }
397
// };
398
//
399
// TEST_P(FlagDependentTest, TestFeature1) {
400
//   // Test your code using external_flag_1 and external_flag_2 here.
401
// }
402
// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
403
//                          Combine(Bool(), Bool()));
404
//
405
template <typename... Generator>
406
internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
407
  return internal::CartesianProductHolder<Generator...>(g...);
408
}
409
410
#define TEST_P(test_suite_name, test_name)                                     \
411
  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                     \
412
      : public test_suite_name {                                               \
413
   public:                                                                     \
414
    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {}                    \
415
    void TestBody() override;                                                  \
416
                                                                               \
417
   private:                                                                    \
418
    static int AddToRegistry() {                                               \
419
      ::testing::UnitTest::GetInstance()                                       \
420
          ->parameterized_test_registry()                                      \
421
          .GetTestSuitePatternHolder<test_suite_name>(                         \
422
              GTEST_STRINGIFY_(test_suite_name),                               \
423
              ::testing::internal::CodeLocation(__FILE__, __LINE__))           \
424
          ->AddTestPattern(                                                    \
425
              GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name),  \
426
              new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
427
                  test_suite_name, test_name)>(),                              \
428
              ::testing::internal::CodeLocation(__FILE__, __LINE__));          \
429
      return 0;                                                                \
430
    }                                                                          \
431
    static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_;               \
432
    GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,    \
433
                                                           test_name));        \
434
  };                                                                           \
435
  int GTEST_TEST_CLASS_NAME_(test_suite_name,                                  \
436
                             test_name)::gtest_registering_dummy_ =            \
437
      GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry();     \
438
  void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
439
440
// The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
441
// generator and an optional function or functor that generates custom test name
442
// suffixes based on the test parameters. Such a function or functor should
443
// accept one argument of type testing::TestParamInfo<class ParamType>, and
444
// return std::string.
445
//
446
// testing::PrintToStringParamName is a builtin test suffix generator that
447
// returns the value of testing::PrintToString(GetParam()).
448
//
449
// Note: test names must be non-empty, unique, and may only contain ASCII
450
// alphanumeric characters or underscore. Because PrintToString adds quotes
451
// to std::string and C strings, it won't work for these types.
452
453
#define GTEST_EXPAND_(arg) arg
454
#define GTEST_GET_FIRST_(first, ...) first
455
#define GTEST_GET_SECOND_(first, second, ...) second
456
457
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...)                \
458
  static ::testing::internal::ParamGenerator<test_suite_name::ParamType>      \
459
      gtest_##prefix##test_suite_name##_EvalGenerator_() {                    \
460
    return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_));        \
461
  }                                                                           \
462
  static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_(   \
463
      const ::testing::TestParamInfo<test_suite_name::ParamType>& info) {     \
464
    if (::testing::internal::AlwaysFalse()) {                                 \
465
      ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_(      \
466
          __VA_ARGS__,                                                        \
467
          ::testing::internal::DefaultParamName<test_suite_name::ParamType>,  \
468
          DUMMY_PARAM_)));                                                    \
469
      auto t = std::make_tuple(__VA_ARGS__);                                  \
470
      static_assert(std::tuple_size<decltype(t)>::value <= 2,                 \
471
                    "Too Many Args!");                                        \
472
    }                                                                         \
473
    return ((GTEST_EXPAND_(GTEST_GET_SECOND_(                                 \
474
        __VA_ARGS__,                                                          \
475
        ::testing::internal::DefaultParamName<test_suite_name::ParamType>,    \
476
        DUMMY_PARAM_))))(info);                                               \
477
  }                                                                           \
478
  static int gtest_##prefix##test_suite_name##_dummy_                         \
479
      GTEST_ATTRIBUTE_UNUSED_ =                                               \
480
          ::testing::UnitTest::GetInstance()                                  \
481
              ->parameterized_test_registry()                                 \
482
              .GetTestSuitePatternHolder<test_suite_name>(                    \
483
                  GTEST_STRINGIFY_(test_suite_name),                          \
484
                  ::testing::internal::CodeLocation(__FILE__, __LINE__))      \
485
              ->AddTestSuiteInstantiation(                                    \
486
                  GTEST_STRINGIFY_(prefix),                                   \
487
                  &gtest_##prefix##test_suite_name##_EvalGenerator_,          \
488
                  &gtest_##prefix##test_suite_name##_EvalGenerateName_,       \
489
                  __FILE__, __LINE__)
490
491
492
// Allow Marking a Parameterized test class as not needing to be instantiated.
493
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T)                   \
494
  namespace gtest_do_not_use_outside_namespace_scope {}                   \
495
  static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
496
      GTEST_STRINGIFY_(T))
497
498
// Legacy API is deprecated but still available
499
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
500
#define INSTANTIATE_TEST_CASE_P                                            \
501
  static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
502
                "");                                                       \
503
  INSTANTIATE_TEST_SUITE_P
504
#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
505
506
}  // namespace testing
507
508
#endif  // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_