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.
30 // Author: vladl@google.com (Vlad Losev)
32 // Type and function utilities for implementing parameterized tests.
34 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
35 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
41 // scripts/fuse_gtest.py depends on gtest's own header being #included
42 // *unconditionally*. Therefore these #includes cannot be moved
43 // inside #if GTEST_HAS_PARAM_TEST.
44 #include <gtest/internal/gtest-internal.h>
45 #include <gtest/internal/gtest-linked_ptr.h>
46 #include <gtest/internal/gtest-port.h>
48 #if GTEST_HAS_PARAM_TEST
53 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
55 // Outputs a message explaining invalid registration of different
56 // fixture class for the same test case. This may happen when
57 // TEST_P macro is used to define two tests with the same name
58 // but in different namespaces.
59 GTEST_API_
void ReportInvalidTestCaseType(const char* test_case_name
,
60 const char* file
, int line
);
62 template <typename
> class ParamGeneratorInterface
;
63 template <typename
> class ParamGenerator
;
65 // Interface for iterating over elements provided by an implementation
66 // of ParamGeneratorInterface<T>.
68 class ParamIteratorInterface
{
70 virtual ~ParamIteratorInterface() {}
71 // A pointer to the base generator instance.
72 // Used only for the purposes of iterator comparison
73 // to make sure that two iterators belong to the same generator.
74 virtual const ParamGeneratorInterface
<T
>* BaseGenerator() const = 0;
75 // Advances iterator to point to the next element
76 // provided by the generator. The caller is responsible
77 // for not calling Advance() on an iterator equal to
78 // BaseGenerator()->End().
79 virtual void Advance() = 0;
80 // Clones the iterator object. Used for implementing copy semantics
81 // of ParamIterator<T>.
82 virtual ParamIteratorInterface
* Clone() const = 0;
83 // Dereferences the current iterator and provides (read-only) access
84 // to the pointed value. It is the caller's responsibility not to call
85 // Current() on an iterator equal to BaseGenerator()->End().
86 // Used for implementing ParamGenerator<T>::operator*().
87 virtual const T
* Current() const = 0;
88 // Determines whether the given iterator and other point to the same
89 // element in the sequence generated by the generator.
90 // Used for implementing ParamGenerator<T>::operator==().
91 virtual bool Equals(const ParamIteratorInterface
& other
) const = 0;
94 // Class iterating over elements provided by an implementation of
95 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
96 // and implements the const forward iterator concept.
100 typedef T value_type
;
101 typedef const T
& reference
;
102 typedef ptrdiff_t difference_type
;
104 // ParamIterator assumes ownership of the impl_ pointer.
105 ParamIterator(const ParamIterator
& other
) : impl_(other
.impl_
->Clone()) {}
106 ParamIterator
& operator=(const ParamIterator
& other
) {
108 impl_
.reset(other
.impl_
->Clone());
112 const T
& operator*() const { return *impl_
->Current(); }
113 const T
* operator->() const { return impl_
->Current(); }
114 // Prefix version of operator++.
115 ParamIterator
& operator++() {
119 // Postfix version of operator++.
120 ParamIterator
operator++(int /*unused*/) {
121 ParamIteratorInterface
<T
>* clone
= impl_
->Clone();
123 return ParamIterator(clone
);
125 bool operator==(const ParamIterator
& other
) const {
126 return impl_
.get() == other
.impl_
.get() || impl_
->Equals(*other
.impl_
);
128 bool operator!=(const ParamIterator
& other
) const {
129 return !(*this == other
);
133 friend class ParamGenerator
<T
>;
134 explicit ParamIterator(ParamIteratorInterface
<T
>* impl
) : impl_(impl
) {}
135 scoped_ptr
<ParamIteratorInterface
<T
> > impl_
;
138 // ParamGeneratorInterface<T> is the binary interface to access generators
139 // defined in other translation units.
140 template <typename T
>
141 class ParamGeneratorInterface
{
145 virtual ~ParamGeneratorInterface() {}
147 // Generator interface definition
148 virtual ParamIteratorInterface
<T
>* Begin() const = 0;
149 virtual ParamIteratorInterface
<T
>* End() const = 0;
152 // Wraps ParamGeneratorInterface<T> and provides general generator syntax
153 // compatible with the STL Container concept.
154 // This class implements copy initialization semantics and the contained
155 // ParamGeneratorInterface<T> instance is shared among all copies
156 // of the original object. This is possible because that instance is immutable.
158 class ParamGenerator
{
160 typedef ParamIterator
<T
> iterator
;
162 explicit ParamGenerator(ParamGeneratorInterface
<T
>* impl
) : impl_(impl
) {}
163 ParamGenerator(const ParamGenerator
& other
) : impl_(other
.impl_
) {}
165 ParamGenerator
& operator=(const ParamGenerator
& other
) {
170 iterator
begin() const { return iterator(impl_
->Begin()); }
171 iterator
end() const { return iterator(impl_
->End()); }
174 ::testing::internal::linked_ptr
<const ParamGeneratorInterface
<T
> > impl_
;
177 // Generates values from a range of two comparable values. Can be used to
178 // generate sequences of user-defined types that implement operator+() and
180 // This class is used in the Range() function.
181 template <typename T
, typename IncrementT
>
182 class RangeGenerator
: public ParamGeneratorInterface
<T
> {
184 RangeGenerator(T begin
, T end
, IncrementT step
)
185 : begin_(begin
), end_(end
),
186 step_(step
), end_index_(CalculateEndIndex(begin
, end
, step
)) {}
187 virtual ~RangeGenerator() {}
189 virtual ParamIteratorInterface
<T
>* Begin() const {
190 return new Iterator(this, begin_
, 0, step_
);
192 virtual ParamIteratorInterface
<T
>* End() const {
193 return new Iterator(this, end_
, end_index_
, step_
);
197 class Iterator
: public ParamIteratorInterface
<T
> {
199 Iterator(const ParamGeneratorInterface
<T
>* base
, T value
, int index
,
201 : base_(base
), value_(value
), index_(index
), step_(step
) {}
202 virtual ~Iterator() {}
204 virtual const ParamGeneratorInterface
<T
>* BaseGenerator() const {
207 virtual void Advance() {
208 value_
= value_
+ step_
;
211 virtual ParamIteratorInterface
<T
>* Clone() const {
212 return new Iterator(*this);
214 virtual const T
* Current() const { return &value_
; }
215 virtual bool Equals(const ParamIteratorInterface
<T
>& other
) const {
216 // Having the same base generator guarantees that the other
217 // iterator is of the same type and we can downcast.
218 GTEST_CHECK_(BaseGenerator() == other
.BaseGenerator())
219 << "The program attempted to compare iterators "
220 << "from different generators." << std::endl
;
221 const int other_index
=
222 CheckedDowncastToActualType
<const Iterator
>(&other
)->index_
;
223 return index_
== other_index
;
227 Iterator(const Iterator
& other
)
228 : ParamIteratorInterface
<T
>(),
229 base_(other
.base_
), value_(other
.value_
), index_(other
.index_
),
230 step_(other
.step_
) {}
232 // No implementation - assignment is unsupported.
233 void operator=(const Iterator
& other
);
235 const ParamGeneratorInterface
<T
>* const base_
;
238 const IncrementT step_
;
239 }; // class RangeGenerator::Iterator
241 static int CalculateEndIndex(const T
& begin
,
243 const IncrementT
& step
) {
245 for (T i
= begin
; i
< end
; i
= i
+ step
)
250 // No implementation - assignment is unsupported.
251 void operator=(const RangeGenerator
& other
);
255 const IncrementT step_
;
256 // The index for the end() iterator. All the elements in the generated
257 // sequence are indexed (0-based) to aid iterator comparison.
258 const int end_index_
;
259 }; // class RangeGenerator
262 // Generates values from a pair of STL-style iterators. Used in the
263 // ValuesIn() function. The elements are copied from the source range
264 // since the source can be located on the stack, and the generator
265 // is likely to persist beyond that stack frame.
266 template <typename T
>
267 class ValuesInIteratorRangeGenerator
: public ParamGeneratorInterface
<T
> {
269 template <typename ForwardIterator
>
270 ValuesInIteratorRangeGenerator(ForwardIterator begin
, ForwardIterator end
)
271 : container_(begin
, end
) {}
272 virtual ~ValuesInIteratorRangeGenerator() {}
274 virtual ParamIteratorInterface
<T
>* Begin() const {
275 return new Iterator(this, container_
.begin());
277 virtual ParamIteratorInterface
<T
>* End() const {
278 return new Iterator(this, container_
.end());
282 typedef typename ::std::vector
<T
> ContainerType
;
284 class Iterator
: public ParamIteratorInterface
<T
> {
286 Iterator(const ParamGeneratorInterface
<T
>* base
,
287 typename
ContainerType::const_iterator iterator
)
288 : base_(base
), iterator_(iterator
) {}
289 virtual ~Iterator() {}
291 virtual const ParamGeneratorInterface
<T
>* BaseGenerator() const {
294 virtual void Advance() {
298 virtual ParamIteratorInterface
<T
>* Clone() const {
299 return new Iterator(*this);
301 // We need to use cached value referenced by iterator_ because *iterator_
302 // can return a temporary object (and of type other then T), so just
303 // having "return &*iterator_;" doesn't work.
304 // value_ is updated here and not in Advance() because Advance()
305 // can advance iterator_ beyond the end of the range, and we cannot
306 // detect that fact. The client code, on the other hand, is
307 // responsible for not calling Current() on an out-of-range iterator.
308 virtual const T
* Current() const {
309 if (value_
.get() == NULL
)
310 value_
.reset(new T(*iterator_
));
313 virtual bool Equals(const ParamIteratorInterface
<T
>& other
) const {
314 // Having the same base generator guarantees that the other
315 // iterator is of the same type and we can downcast.
316 GTEST_CHECK_(BaseGenerator() == other
.BaseGenerator())
317 << "The program attempted to compare iterators "
318 << "from different generators." << std::endl
;
320 CheckedDowncastToActualType
<const Iterator
>(&other
)->iterator_
;
324 Iterator(const Iterator
& other
)
325 // The explicit constructor call suppresses a false warning
326 // emitted by gcc when supplied with the -Wextra option.
327 : ParamIteratorInterface
<T
>(),
329 iterator_(other
.iterator_
) {}
331 const ParamGeneratorInterface
<T
>* const base_
;
332 typename
ContainerType::const_iterator iterator_
;
333 // A cached value of *iterator_. We keep it here to allow access by
334 // pointer in the wrapping iterator's operator->().
335 // value_ needs to be mutable to be accessed in Current().
336 // Use of scoped_ptr helps manage cached value's lifetime,
337 // which is bound by the lifespan of the iterator itself.
338 mutable scoped_ptr
<const T
> value_
;
339 }; // class ValuesInIteratorRangeGenerator::Iterator
341 // No implementation - assignment is unsupported.
342 void operator=(const ValuesInIteratorRangeGenerator
& other
);
344 const ContainerType container_
;
345 }; // class ValuesInIteratorRangeGenerator
347 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
349 // Stores a parameter value and later creates tests parameterized with that
351 template <class TestClass
>
352 class ParameterizedTestFactory
: public TestFactoryBase
{
354 typedef typename
TestClass::ParamType ParamType
;
355 explicit ParameterizedTestFactory(ParamType parameter
) :
356 parameter_(parameter
) {}
357 virtual Test
* CreateTest() {
358 TestClass::SetParam(¶meter_
);
359 return new TestClass();
363 const ParamType parameter_
;
365 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory
);
368 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
370 // TestMetaFactoryBase is a base class for meta-factories that create
371 // test factories for passing into MakeAndRegisterTestInfo function.
372 template <class ParamType
>
373 class TestMetaFactoryBase
{
375 virtual ~TestMetaFactoryBase() {}
377 virtual TestFactoryBase
* CreateTestFactory(ParamType parameter
) = 0;
380 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
382 // TestMetaFactory creates test factories for passing into
383 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
384 // ownership of test factory pointer, same factory object cannot be passed
385 // into that method twice. But ParameterizedTestCaseInfo is going to call
386 // it for each Test/Parameter value combination. Thus it needs meta factory
388 template <class TestCase
>
389 class TestMetaFactory
390 : public TestMetaFactoryBase
<typename
TestCase::ParamType
> {
392 typedef typename
TestCase::ParamType ParamType
;
396 virtual TestFactoryBase
* CreateTestFactory(ParamType parameter
) {
397 return new ParameterizedTestFactory
<TestCase
>(parameter
);
401 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory
);
404 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
406 // ParameterizedTestCaseInfoBase is a generic interface
407 // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
408 // accumulates test information provided by TEST_P macro invocations
409 // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
410 // and uses that information to register all resulting test instances
411 // in RegisterTests method. The ParameterizeTestCaseRegistry class holds
412 // a collection of pointers to the ParameterizedTestCaseInfo objects
413 // and calls RegisterTests() on each of them when asked.
414 class ParameterizedTestCaseInfoBase
{
416 virtual ~ParameterizedTestCaseInfoBase() {}
418 // Base part of test case name for display purposes.
419 virtual const String
& GetTestCaseName() const = 0;
420 // Test case id to verify identity.
421 virtual TypeId
GetTestCaseTypeId() const = 0;
422 // UnitTest class invokes this method to register tests in this
423 // test case right before running them in RUN_ALL_TESTS macro.
424 // This method should not be called more then once on any single
425 // instance of a ParameterizedTestCaseInfoBase derived class.
426 virtual void RegisterTests() = 0;
429 ParameterizedTestCaseInfoBase() {}
432 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase
);
435 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
437 // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
438 // macro invocations for a particular test case and generators
439 // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
440 // test case. It registers tests with all values generated by all
441 // generators when asked.
442 template <class TestCase
>
443 class ParameterizedTestCaseInfo
: public ParameterizedTestCaseInfoBase
{
445 // ParamType and GeneratorCreationFunc are private types but are required
446 // for declarations of public methods AddTestPattern() and
447 // AddTestCaseInstantiation().
448 typedef typename
TestCase::ParamType ParamType
;
449 // A function that returns an instance of appropriate generator type.
450 typedef ParamGenerator
<ParamType
>(GeneratorCreationFunc
)();
452 explicit ParameterizedTestCaseInfo(const char* name
)
453 : test_case_name_(name
) {}
455 // Test case base name for display purposes.
456 virtual const String
& GetTestCaseName() const { return test_case_name_
; }
457 // Test case id to verify identity.
458 virtual TypeId
GetTestCaseTypeId() const { return GetTypeId
<TestCase
>(); }
459 // TEST_P macro uses AddTestPattern() to record information
460 // about a single test in a LocalTestInfo structure.
461 // test_case_name is the base name of the test case (without invocation
462 // prefix). test_base_name is the name of an individual test without
463 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
464 // test case base name and DoBar is test base name.
465 void AddTestPattern(const char* test_case_name
,
466 const char* test_base_name
,
467 TestMetaFactoryBase
<ParamType
>* meta_factory
) {
468 tests_
.push_back(linked_ptr
<TestInfo
>(new TestInfo(test_case_name
,
472 // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
473 // about a generator.
474 int AddTestCaseInstantiation(const char* instantiation_name
,
475 GeneratorCreationFunc
* func
,
476 const char* /* file */,
478 instantiations_
.push_back(::std::make_pair(instantiation_name
, func
));
479 return 0; // Return value used only to run this method in namespace scope.
481 // UnitTest class invokes this method to register tests in this test case
482 // test cases right before running tests in RUN_ALL_TESTS macro.
483 // This method should not be called more then once on any single
484 // instance of a ParameterizedTestCaseInfoBase derived class.
485 // UnitTest has a guard to prevent from calling this method more then once.
486 virtual void RegisterTests() {
487 for (typename
TestInfoContainer::iterator test_it
= tests_
.begin();
488 test_it
!= tests_
.end(); ++test_it
) {
489 linked_ptr
<TestInfo
> test_info
= *test_it
;
490 for (typename
InstantiationContainer::iterator gen_it
=
491 instantiations_
.begin(); gen_it
!= instantiations_
.end();
493 const String
& instantiation_name
= gen_it
->first
;
494 ParamGenerator
<ParamType
> generator((*gen_it
->second
)());
496 Message test_case_name_stream
;
497 if ( !instantiation_name
.empty() )
498 test_case_name_stream
<< instantiation_name
.c_str() << "/";
499 test_case_name_stream
<< test_info
->test_case_base_name
.c_str();
502 for (typename ParamGenerator
<ParamType
>::iterator param_it
=
504 param_it
!= generator
.end(); ++param_it
, ++i
) {
505 Message test_name_stream
;
506 test_name_stream
<< test_info
->test_base_name
.c_str() << "/" << i
;
507 ::testing::internal::MakeAndRegisterTestInfo(
508 test_case_name_stream
.GetString().c_str(),
509 test_name_stream
.GetString().c_str(),
510 "", // test_case_comment
511 "", // comment; TODO(vladl@google.com): provide parameter value
514 TestCase::SetUpTestCase
,
515 TestCase::TearDownTestCase
,
516 test_info
->test_meta_factory
->CreateTestFactory(*param_it
));
523 // LocalTestInfo structure keeps information about a single test registered
524 // with TEST_P macro.
526 TestInfo(const char* a_test_case_base_name
,
527 const char* a_test_base_name
,
528 TestMetaFactoryBase
<ParamType
>* a_test_meta_factory
) :
529 test_case_base_name(a_test_case_base_name
),
530 test_base_name(a_test_base_name
),
531 test_meta_factory(a_test_meta_factory
) {}
533 const String test_case_base_name
;
534 const String test_base_name
;
535 const scoped_ptr
<TestMetaFactoryBase
<ParamType
> > test_meta_factory
;
537 typedef ::std::vector
<linked_ptr
<TestInfo
> > TestInfoContainer
;
538 // Keeps pairs of <Instantiation name, Sequence generator creation function>
539 // received from INSTANTIATE_TEST_CASE_P macros.
540 typedef ::std::vector
<std::pair
<String
, GeneratorCreationFunc
*> >
541 InstantiationContainer
;
543 const String test_case_name_
;
544 TestInfoContainer tests_
;
545 InstantiationContainer instantiations_
;
547 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo
);
548 }; // class ParameterizedTestCaseInfo
550 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
552 // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
553 // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
554 // macros use it to locate their corresponding ParameterizedTestCaseInfo
556 class ParameterizedTestCaseRegistry
{
558 ParameterizedTestCaseRegistry() {}
559 ~ParameterizedTestCaseRegistry() {
560 for (TestCaseInfoContainer::iterator it
= test_case_infos_
.begin();
561 it
!= test_case_infos_
.end(); ++it
) {
566 // Looks up or creates and returns a structure containing information about
567 // tests and instantiations of a particular test case.
568 template <class TestCase
>
569 ParameterizedTestCaseInfo
<TestCase
>* GetTestCasePatternHolder(
570 const char* test_case_name
,
573 ParameterizedTestCaseInfo
<TestCase
>* typed_test_info
= NULL
;
574 for (TestCaseInfoContainer::iterator it
= test_case_infos_
.begin();
575 it
!= test_case_infos_
.end(); ++it
) {
576 if ((*it
)->GetTestCaseName() == test_case_name
) {
577 if ((*it
)->GetTestCaseTypeId() != GetTypeId
<TestCase
>()) {
578 // Complain about incorrect usage of Google Test facilities
579 // and terminate the program since we cannot guaranty correct
580 // test case setup and tear-down in this case.
581 ReportInvalidTestCaseType(test_case_name
, file
, line
);
584 // At this point we are sure that the object we found is of the same
585 // type we are looking for, so we downcast it to that type
586 // without further checks.
587 typed_test_info
= CheckedDowncastToActualType
<
588 ParameterizedTestCaseInfo
<TestCase
> >(*it
);
593 if (typed_test_info
== NULL
) {
594 typed_test_info
= new ParameterizedTestCaseInfo
<TestCase
>(test_case_name
);
595 test_case_infos_
.push_back(typed_test_info
);
597 return typed_test_info
;
599 void RegisterTests() {
600 for (TestCaseInfoContainer::iterator it
= test_case_infos_
.begin();
601 it
!= test_case_infos_
.end(); ++it
) {
602 (*it
)->RegisterTests();
607 typedef ::std::vector
<ParameterizedTestCaseInfoBase
*> TestCaseInfoContainer
;
609 TestCaseInfoContainer test_case_infos_
;
611 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry
);
614 } // namespace internal
615 } // namespace testing
617 #endif // GTEST_HAS_PARAM_TEST
619 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_