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 #include <gtest/internal/gtest-port.h>
43 #if GTEST_HAS_PARAM_TEST
47 #endif // GTEST_HAS_RTTI
49 #include <gtest/internal/gtest-linked_ptr.h>
50 #include <gtest/internal/gtest-internal.h>
55 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
57 // Outputs a message explaining invalid registration of different
58 // fixture class for the same test case. This may happen when
59 // TEST_P macro is used to define two tests with the same name
60 // but in different namespaces.
61 void ReportInvalidTestCaseType(const char* test_case_name,
62 const char* file, int line);
64 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
66 // Downcasts the pointer of type Base to Derived.
67 // Derived must be a subclass of Base. The parameter MUST
68 // point to a class of type Derived, not any subclass of it.
69 // When RTTI is available, the function performs a runtime
70 // check to enforce this.
71 template <class Derived, class Base>
72 Derived* CheckedDowncastToActualType(Base* base) {
74 GTEST_CHECK_(typeid(*base) == typeid(Derived));
75 Derived* derived = dynamic_cast<Derived*>(base); // NOLINT
77 Derived* derived = static_cast<Derived*>(base); // Poor man's downcast.
78 #endif // GTEST_HAS_RTTI
82 template <typename> class ParamGeneratorInterface;
83 template <typename> class ParamGenerator;
85 // Interface for iterating over elements provided by an implementation
86 // of ParamGeneratorInterface<T>.
88 class ParamIteratorInterface {
90 virtual ~ParamIteratorInterface() {}
91 // A pointer to the base generator instance.
92 // Used only for the purposes of iterator comparison
93 // to make sure that two iterators belong to the same generator.
94 virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
95 // Advances iterator to point to the next element
96 // provided by the generator. The caller is responsible
97 // for not calling Advance() on an iterator equal to
98 // BaseGenerator()->End().
99 virtual void Advance() = 0;
100 // Clones the iterator object. Used for implementing copy semantics
101 // of ParamIterator<T>.
102 virtual ParamIteratorInterface* Clone() const = 0;
103 // Dereferences the current iterator and provides (read-only) access
104 // to the pointed value. It is the caller's responsibility not to call
105 // Current() on an iterator equal to BaseGenerator()->End().
106 // Used for implementing ParamGenerator<T>::operator*().
107 virtual const T* Current() const = 0;
108 // Determines whether the given iterator and other point to the same
109 // element in the sequence generated by the generator.
110 // Used for implementing ParamGenerator<T>::operator==().
111 virtual bool Equals(const ParamIteratorInterface& other) const = 0;
114 // Class iterating over elements provided by an implementation of
115 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
116 // and implements the const forward iterator concept.
117 template <typename T>
118 class ParamIterator {
120 typedef T value_type;
121 typedef const T& reference;
122 typedef ptrdiff_t difference_type;
124 // ParamIterator assumes ownership of the impl_ pointer.
125 ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
126 ParamIterator& operator=(const ParamIterator& other) {
128 impl_.reset(other.impl_->Clone());
132 const T& operator*() const { return *impl_->Current(); }
133 const T* operator->() const { return impl_->Current(); }
134 // Prefix version of operator++.
135 ParamIterator& operator++() {
139 // Postfix version of operator++.
140 ParamIterator operator++(int /*unused*/) {
141 ParamIteratorInterface<T>* clone = impl_->Clone();
143 return ParamIterator(clone);
145 bool operator==(const ParamIterator& other) const {
146 return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
148 bool operator!=(const ParamIterator& other) const {
149 return !(*this == other);
153 friend class ParamGenerator<T>;
154 explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
155 scoped_ptr<ParamIteratorInterface<T> > impl_;
158 // ParamGeneratorInterface<T> is the binary interface to access generators
159 // defined in other translation units.
160 template <typename T>
161 class ParamGeneratorInterface {
165 virtual ~ParamGeneratorInterface() {}
167 // Generator interface definition
168 virtual ParamIteratorInterface<T>* Begin() const = 0;
169 virtual ParamIteratorInterface<T>* End() const = 0;
172 // Wraps ParamGeneratorInetrface<T> and provides general generator syntax
173 // compatible with the STL Container concept.
174 // This class implements copy initialization semantics and the contained
175 // ParamGeneratorInterface<T> instance is shared among all copies
176 // of the original object. This is possible because that instance is immutable.
178 class ParamGenerator {
180 typedef ParamIterator<T> iterator;
182 explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
183 ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
185 ParamGenerator& operator=(const ParamGenerator& other) {
190 iterator begin() const { return iterator(impl_->Begin()); }
191 iterator end() const { return iterator(impl_->End()); }
194 ::testing::internal::linked_ptr<const ParamGeneratorInterface<T> > impl_;
197 // Generates values from a range of two comparable values. Can be used to
198 // generate sequences of user-defined types that implement operator+() and
200 // This class is used in the Range() function.
201 template <typename T, typename IncrementT>
202 class RangeGenerator : public ParamGeneratorInterface<T> {
204 RangeGenerator(T begin, T end, IncrementT step)
205 : begin_(begin), end_(end),
206 step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
207 virtual ~RangeGenerator() {}
209 virtual ParamIteratorInterface<T>* Begin() const {
210 return new Iterator(this, begin_, 0, step_);
212 virtual ParamIteratorInterface<T>* End() const {
213 return new Iterator(this, end_, end_index_, step_);
217 class Iterator : public ParamIteratorInterface<T> {
219 Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
221 : base_(base), value_(value), index_(index), step_(step) {}
222 virtual ~Iterator() {}
224 virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
227 virtual void Advance() {
228 value_ = value_ + step_;
231 virtual ParamIteratorInterface<T>* Clone() const {
232 return new Iterator(*this);
234 virtual const T* Current() const { return &value_; }
235 virtual bool Equals(const ParamIteratorInterface<T>& other) const {
236 // Having the same base generator guarantees that the other
237 // iterator is of the same type and we can downcast.
238 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
239 << "The program attempted to compare iterators "
240 << "from different generators." << std::endl;
241 const int other_index =
242 CheckedDowncastToActualType<const Iterator>(&other)->index_;
243 return index_ == other_index;
247 Iterator(const Iterator& other)
248 : base_(other.base_), value_(other.value_), index_(other.index_),
249 step_(other.step_) {}
251 // No implementation - assignment is unsupported.
252 void operator=(const Iterator& other);
254 const ParamGeneratorInterface<T>* const base_;
257 const IncrementT step_;
258 }; // class RangeGenerator::Iterator
260 static int CalculateEndIndex(const T& begin,
262 const IncrementT& step) {
264 for (T i = begin; i < end; i = i + step)
269 // No implementation - assignment is unsupported.
270 void operator=(const RangeGenerator& other);
274 const IncrementT step_;
275 // The index for the end() iterator. All the elements in the generated
276 // sequence are indexed (0-based) to aid iterator comparison.
277 const int end_index_;
278 }; // class RangeGenerator
281 // Generates values from a pair of STL-style iterators. Used in the
282 // ValuesIn() function. The elements are copied from the source range
283 // since the source can be located on the stack, and the generator
284 // is likely to persist beyond that stack frame.
285 template <typename T>
286 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
288 template <typename ForwardIterator>
289 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
290 : container_(begin, end) {}
291 virtual ~ValuesInIteratorRangeGenerator() {}
293 virtual ParamIteratorInterface<T>* Begin() const {
294 return new Iterator(this, container_.begin());
296 virtual ParamIteratorInterface<T>* End() const {
297 return new Iterator(this, container_.end());
301 typedef typename ::std::vector<T> ContainerType;
303 class Iterator : public ParamIteratorInterface<T> {
305 Iterator(const ParamGeneratorInterface<T>* base,
306 typename ContainerType::const_iterator iterator)
307 : base_(base), iterator_(iterator) {}
308 virtual ~Iterator() {}
310 virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
313 virtual void Advance() {
317 virtual ParamIteratorInterface<T>* Clone() const {
318 return new Iterator(*this);
320 // We need to use cached value referenced by iterator_ because *iterator_
321 // can return a temporary object (and of type other then T), so just
322 // having "return &*iterator_;" doesn't work.
323 // value_ is updated here and not in Advance() because Advance()
324 // can advance iterator_ beyond the end of the range, and we cannot
325 // detect that fact. The client code, on the other hand, is
326 // responsible for not calling Current() on an out-of-range iterator.
327 virtual const T* Current() const {
328 if (value_.get() == NULL)
329 value_.reset(new T(*iterator_));
332 virtual bool Equals(const ParamIteratorInterface<T>& other) const {
333 // Having the same base generator guarantees that the other
334 // iterator is of the same type and we can downcast.
335 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
336 << "The program attempted to compare iterators "
337 << "from different generators." << std::endl;
339 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
343 Iterator(const Iterator& other)
344 // The explicit constructor call suppresses a false warning
345 // emitted by gcc when supplied with the -Wextra option.
346 : ParamIteratorInterface<T>(),
348 iterator_(other.iterator_) {}
350 const ParamGeneratorInterface<T>* const base_;
351 typename ContainerType::const_iterator iterator_;
352 // A cached value of *iterator_. We keep it here to allow access by
353 // pointer in the wrapping iterator's operator->().
354 // value_ needs to be mutable to be accessed in Current().
355 // Use of scoped_ptr helps manage cached value's lifetime,
356 // which is bound by the lifespan of the iterator itself.
357 mutable scoped_ptr<const T> value_;
358 }; // class ValuesInIteratorRangeGenerator::Iterator
360 // No implementation - assignment is unsupported.
361 void operator=(const ValuesInIteratorRangeGenerator& other);
363 const ContainerType container_;
364 }; // class ValuesInIteratorRangeGenerator
366 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
368 // Stores a parameter value and later creates tests parameterized with that
370 template <class TestClass>
371 class ParameterizedTestFactory : public TestFactoryBase {
373 typedef typename TestClass::ParamType ParamType;
374 explicit ParameterizedTestFactory(ParamType parameter) :
375 parameter_(parameter) {}
376 virtual Test* CreateTest() {
377 TestClass::SetParam(¶meter_);
378 return new TestClass();
382 const ParamType parameter_;
384 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
387 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
389 // TestMetaFactoryBase is a base class for meta-factories that create
390 // test factories for passing into MakeAndRegisterTestInfo function.
391 template <class ParamType>
392 class TestMetaFactoryBase {
394 virtual ~TestMetaFactoryBase() {}
396 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
399 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
401 // TestMetaFactory creates test factories for passing into
402 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
403 // ownership of test factory pointer, same factory object cannot be passed
404 // into that method twice. But ParameterizedTestCaseInfo is going to call
405 // it for each Test/Parameter value combination. Thus it needs meta factory
407 template <class TestCase>
408 class TestMetaFactory
409 : public TestMetaFactoryBase<typename TestCase::ParamType> {
411 typedef typename TestCase::ParamType ParamType;
415 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) {
416 return new ParameterizedTestFactory<TestCase>(parameter);
420 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
423 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
425 // ParameterizedTestCaseInfoBase is a generic interface
426 // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
427 // accumulates test information provided by TEST_P macro invocations
428 // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
429 // and uses that information to register all resulting test instances
430 // in RegisterTests method. The ParameterizeTestCaseRegistry class holds
431 // a collection of pointers to the ParameterizedTestCaseInfo objects
432 // and calls RegisterTests() on each of them when asked.
433 class ParameterizedTestCaseInfoBase {
435 virtual ~ParameterizedTestCaseInfoBase() {}
437 // Base part of test case name for display purposes.
438 virtual const String& GetTestCaseName() const = 0;
439 // Test case id to verify identity.
440 virtual TypeId GetTestCaseTypeId() const = 0;
441 // UnitTest class invokes this method to register tests in this
442 // test case right before running them in RUN_ALL_TESTS macro.
443 // This method should not be called more then once on any single
444 // instance of a ParameterizedTestCaseInfoBase derived class.
445 virtual void RegisterTests() = 0;
448 ParameterizedTestCaseInfoBase() {}
451 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase);
454 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
456 // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
457 // macro invocations for a particular test case and generators
458 // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
459 // test case. It registers tests with all values generated by all
460 // generators when asked.
461 template <class TestCase>
462 class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
464 // ParamType and GeneratorCreationFunc are private types but are required
465 // for declarations of public methods AddTestPattern() and
466 // AddTestCaseInstantiation().
467 typedef typename TestCase::ParamType ParamType;
468 // A function that returns an instance of appropriate generator type.
469 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
471 explicit ParameterizedTestCaseInfo(const char* name)
472 : test_case_name_(name) {}
474 // Test case base name for display purposes.
475 virtual const String& GetTestCaseName() const { return test_case_name_; }
476 // Test case id to verify identity.
477 virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); }
478 // TEST_P macro uses AddTestPattern() to record information
479 // about a single test in a LocalTestInfo structure.
480 // test_case_name is the base name of the test case (without invocation
481 // prefix). test_base_name is the name of an individual test without
482 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
483 // test case base name and DoBar is test base name.
484 void AddTestPattern(const char* test_case_name,
485 const char* test_base_name,
486 TestMetaFactoryBase<ParamType>* meta_factory) {
487 tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name,
491 // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
492 // about a generator.
493 int AddTestCaseInstantiation(const char* instantiation_name,
494 GeneratorCreationFunc* func,
495 const char* /* file */,
497 instantiations_.push_back(::std::make_pair(instantiation_name, func));
498 return 0; // Return value used only to run this method in namespace scope.
500 // UnitTest class invokes this method to register tests in this test case
501 // test cases right before running tests in RUN_ALL_TESTS macro.
502 // This method should not be called more then once on any single
503 // instance of a ParameterizedTestCaseInfoBase derived class.
504 // UnitTest has a guard to prevent from calling this method more then once.
505 virtual void RegisterTests() {
506 for (typename TestInfoContainer::iterator test_it = tests_.begin();
507 test_it != tests_.end(); ++test_it) {
508 linked_ptr<TestInfo> test_info = *test_it;
509 for (typename InstantiationContainer::iterator gen_it =
510 instantiations_.begin(); gen_it != instantiations_.end();
512 const String& instantiation_name = gen_it->first;
513 ParamGenerator<ParamType> generator((*gen_it->second)());
515 Message test_case_name_stream;
516 if ( !instantiation_name.empty() )
517 test_case_name_stream << instantiation_name.c_str() << "/";
518 test_case_name_stream << test_info->test_case_base_name.c_str();
521 for (typename ParamGenerator<ParamType>::iterator param_it =
523 param_it != generator.end(); ++param_it, ++i) {
524 Message test_name_stream;
525 test_name_stream << test_info->test_base_name.c_str() << "/" << i;
526 ::testing::internal::MakeAndRegisterTestInfo(
527 test_case_name_stream.GetString().c_str(),
528 test_name_stream.GetString().c_str(),
529 "", // test_case_comment
530 "", // comment; TODO(vladl@google.com): provide parameter value
533 TestCase::SetUpTestCase,
534 TestCase::TearDownTestCase,
535 test_info->test_meta_factory->CreateTestFactory(*param_it));
542 // LocalTestInfo structure keeps information about a single test registered
543 // with TEST_P macro.
545 TestInfo(const char* test_case_base_name,
546 const char* test_base_name,
547 TestMetaFactoryBase<ParamType>* test_meta_factory) :
548 test_case_base_name(test_case_base_name),
549 test_base_name(test_base_name),
550 test_meta_factory(test_meta_factory) {}
552 const String test_case_base_name;
553 const String test_base_name;
554 const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
556 typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer;
557 // Keeps pairs of <Instantiation name, Sequence generator creation function>
558 // received from INSTANTIATE_TEST_CASE_P macros.
559 typedef ::std::vector<std::pair<String, GeneratorCreationFunc*> >
560 InstantiationContainer;
562 const String test_case_name_;
563 TestInfoContainer tests_;
564 InstantiationContainer instantiations_;
566 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo);
567 }; // class ParameterizedTestCaseInfo
569 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
571 // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
572 // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
573 // macros use it to locate their corresponding ParameterizedTestCaseInfo
575 class ParameterizedTestCaseRegistry {
577 ParameterizedTestCaseRegistry() {}
578 ~ParameterizedTestCaseRegistry() {
579 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
580 it != test_case_infos_.end(); ++it) {
585 // Looks up or creates and returns a structure containing information about
586 // tests and instantiations of a particular test case.
587 template <class TestCase>
588 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
589 const char* test_case_name,
592 ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL;
593 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
594 it != test_case_infos_.end(); ++it) {
595 if ((*it)->GetTestCaseName() == test_case_name) {
596 if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
597 // Complain about incorrect usage of Google Test facilities
598 // and terminate the program since we cannot guaranty correct
599 // test case setup and tear-down in this case.
600 ReportInvalidTestCaseType(test_case_name, file, line);
603 // At this point we are sure that the object we found is of the same
604 // type we are looking for, so we downcast it to that type
605 // without further checks.
606 typed_test_info = CheckedDowncastToActualType<
607 ParameterizedTestCaseInfo<TestCase> >(*it);
612 if (typed_test_info == NULL) {
613 typed_test_info = new ParameterizedTestCaseInfo<TestCase>(test_case_name);
614 test_case_infos_.push_back(typed_test_info);
616 return typed_test_info;
618 void RegisterTests() {
619 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
620 it != test_case_infos_.end(); ++it) {
621 (*it)->RegisterTests();
626 typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer;
628 TestCaseInfoContainer test_case_infos_;
630 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry);
633 } // namespace internal
634 } // namespace testing
636 #endif // GTEST_HAS_PARAM_TEST
638 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_