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 #ifdef 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 const ParamGeneratorInterface<T>* const base_;
254 const IncrementT step_;
255 }; // class RangeGenerator::Iterator
257 static int CalculateEndIndex(const T& begin,
259 const IncrementT& step) {
261 for (T i = begin; i < end; i = i + step)
268 const IncrementT step_;
269 // The index for the end() iterator. All the elements in the generated
270 // sequence are indexed (0-based) to aid iterator comparison.
271 const int end_index_;
272 }; // class RangeGenerator
275 // Generates values from a pair of STL-style iterators. Used in the
276 // ValuesIn() function. The elements are copied from the source range
277 // since the source can be located on the stack, and the generator
278 // is likely to persist beyond that stack frame.
279 template <typename T>
280 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
282 template <typename ForwardIterator>
283 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
284 : container_(begin, end) {}
285 virtual ~ValuesInIteratorRangeGenerator() {}
287 virtual ParamIteratorInterface<T>* Begin() const {
288 return new Iterator(this, container_.begin());
290 virtual ParamIteratorInterface<T>* End() const {
291 return new Iterator(this, container_.end());
295 typedef typename ::std::vector<T> ContainerType;
297 class Iterator : public ParamIteratorInterface<T> {
299 Iterator(const ParamGeneratorInterface<T>* base,
300 typename ContainerType::const_iterator iterator)
301 : base_(base), iterator_(iterator) {}
302 virtual ~Iterator() {}
304 virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
307 virtual void Advance() {
311 virtual ParamIteratorInterface<T>* Clone() const {
312 return new Iterator(*this);
314 // We need to use cached value referenced by iterator_ because *iterator_
315 // can return a temporary object (and of type other then T), so just
316 // having "return &*iterator_;" doesn't work.
317 // value_ is updated here and not in Advance() because Advance()
318 // can advance iterator_ beyond the end of the range, and we cannot
319 // detect that fact. The client code, on the other hand, is
320 // responsible for not calling Current() on an out-of-range iterator.
321 virtual const T* Current() const {
322 if (value_.get() == NULL)
323 value_.reset(new T(*iterator_));
326 virtual bool Equals(const ParamIteratorInterface<T>& other) const {
327 // Having the same base generator guarantees that the other
328 // iterator is of the same type and we can downcast.
329 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
330 << "The program attempted to compare iterators "
331 << "from different generators." << std::endl;
333 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
337 Iterator(const Iterator& other)
338 // The explicit constructor call suppresses a false warning
339 // emitted by gcc when supplied with the -Wextra option.
340 : ParamIteratorInterface<T>(),
342 iterator_(other.iterator_) {}
344 const ParamGeneratorInterface<T>* const base_;
345 typename ContainerType::const_iterator iterator_;
346 // A cached value of *iterator_. We keep it here to allow access by
347 // pointer in the wrapping iterator's operator->().
348 // value_ needs to be mutable to be accessed in Current().
349 // Use of scoped_ptr helps manage cached value's lifetime,
350 // which is bound by the lifespan of the iterator itself.
351 mutable scoped_ptr<const T> value_;
354 const ContainerType container_;
355 }; // class ValuesInIteratorRangeGenerator
357 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
359 // Stores a parameter value and later creates tests parameterized with that
361 template <class TestClass>
362 class ParameterizedTestFactory : public TestFactoryBase {
364 typedef typename TestClass::ParamType ParamType;
365 explicit ParameterizedTestFactory(ParamType parameter) :
366 parameter_(parameter) {}
367 virtual Test* CreateTest() {
368 TestClass::SetParam(¶meter_);
369 return new TestClass();
373 const ParamType parameter_;
375 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
378 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
380 // TestMetaFactoryBase is a base class for meta-factories that create
381 // test factories for passing into MakeAndRegisterTestInfo function.
382 template <class ParamType>
383 class TestMetaFactoryBase {
385 virtual ~TestMetaFactoryBase() {}
387 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
390 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
392 // TestMetaFactory creates test factories for passing into
393 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
394 // ownership of test factory pointer, same factory object cannot be passed
395 // into that method twice. But ParameterizedTestCaseInfo is going to call
396 // it for each Test/Parameter value combination. Thus it needs meta factory
398 template <class TestCase>
399 class TestMetaFactory
400 : public TestMetaFactoryBase<typename TestCase::ParamType> {
402 typedef typename TestCase::ParamType ParamType;
406 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) {
407 return new ParameterizedTestFactory<TestCase>(parameter);
411 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
414 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
416 // ParameterizedTestCaseInfoBase is a generic interface
417 // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
418 // accumulates test information provided by TEST_P macro invocations
419 // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
420 // and uses that information to register all resulting test instances
421 // in RegisterTests method. The ParameterizeTestCaseRegistry class holds
422 // a collection of pointers to the ParameterizedTestCaseInfo objects
423 // and calls RegisterTests() on each of them when asked.
424 class ParameterizedTestCaseInfoBase {
426 virtual ~ParameterizedTestCaseInfoBase() {}
428 // Base part of test case name for display purposes.
429 virtual const String& GetTestCaseName() const = 0;
430 // Test case id to verify identity.
431 virtual TypeId GetTestCaseTypeId() const = 0;
432 // UnitTest class invokes this method to register tests in this
433 // test case right before running them in RUN_ALL_TESTS macro.
434 // This method should not be called more then once on any single
435 // instance of a ParameterizedTestCaseInfoBase derived class.
436 virtual void RegisterTests() = 0;
439 ParameterizedTestCaseInfoBase() {}
442 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase);
445 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
447 // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
448 // macro invocations for a particular test case and generators
449 // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
450 // test case. It registers tests with all values generated by all
451 // generators when asked.
452 template <class TestCase>
453 class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
455 // ParamType and GeneratorCreationFunc are private types but are required
456 // for declarations of public methods AddTestPattern() and
457 // AddTestCaseInstantiation().
458 typedef typename TestCase::ParamType ParamType;
459 // A function that returns an instance of appropriate generator type.
460 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
462 explicit ParameterizedTestCaseInfo(const char* name)
463 : test_case_name_(name) {}
465 // Test case base name for display purposes.
466 virtual const String& GetTestCaseName() const { return test_case_name_; }
467 // Test case id to verify identity.
468 virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); }
469 // TEST_P macro uses AddTestPattern() to record information
470 // about a single test in a LocalTestInfo structure.
471 // test_case_name is the base name of the test case (without invocation
472 // prefix). test_base_name is the name of an individual test without
473 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
474 // test case base name and DoBar is test base name.
475 void AddTestPattern(const char* test_case_name,
476 const char* test_base_name,
477 TestMetaFactoryBase<ParamType>* meta_factory) {
478 tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name,
482 // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
483 // about a generator.
484 int AddTestCaseInstantiation(const char* instantiation_name,
485 GeneratorCreationFunc* func,
488 instantiations_.push_back(::std::make_pair(instantiation_name, func));
489 return 0; // Return value used only to run this method in namespace scope.
491 // UnitTest class invokes this method to register tests in this test case
492 // test cases right before running tests in RUN_ALL_TESTS macro.
493 // This method should not be called more then once on any single
494 // instance of a ParameterizedTestCaseInfoBase derived class.
495 // UnitTest has a guard to prevent from calling this method more then once.
496 virtual void RegisterTests() {
497 for (typename TestInfoContainer::iterator test_it = tests_.begin();
498 test_it != tests_.end(); ++test_it) {
499 linked_ptr<TestInfo> test_info = *test_it;
500 for (typename InstantiationContainer::iterator gen_it =
501 instantiations_.begin(); gen_it != instantiations_.end();
503 const String& instantiation_name = gen_it->first;
504 ParamGenerator<ParamType> generator((*gen_it->second)());
506 Message test_case_name_stream;
507 if ( !instantiation_name.empty() )
508 test_case_name_stream << instantiation_name.c_str() << "/";
509 test_case_name_stream << test_info->test_case_base_name.c_str();
512 for (typename ParamGenerator<ParamType>::iterator param_it =
514 param_it != generator.end(); ++param_it, ++i) {
515 Message test_name_stream;
516 test_name_stream << test_info->test_base_name.c_str() << "/" << i;
517 ::testing::internal::MakeAndRegisterTestInfo(
518 test_case_name_stream.GetString().c_str(),
519 test_name_stream.GetString().c_str(),
520 "", // test_case_comment
521 "", // comment; TODO(vladl@google.com): provide parameter value
524 TestCase::SetUpTestCase,
525 TestCase::TearDownTestCase,
526 test_info->test_meta_factory->CreateTestFactory(*param_it));
533 // LocalTestInfo structure keeps information about a single test registered
534 // with TEST_P macro.
536 TestInfo(const char* test_case_base_name,
537 const char* test_base_name,
538 TestMetaFactoryBase<ParamType>* test_meta_factory) :
539 test_case_base_name(test_case_base_name),
540 test_base_name(test_base_name),
541 test_meta_factory(test_meta_factory) {}
543 const String test_case_base_name;
544 const String test_base_name;
545 const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
547 typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer;
548 // Keeps pairs of <Instantiation name, Sequence generator creation function>
549 // received from INSTANTIATE_TEST_CASE_P macros.
550 typedef ::std::vector<std::pair<String, GeneratorCreationFunc*> >
551 InstantiationContainer;
553 const String test_case_name_;
554 TestInfoContainer tests_;
555 InstantiationContainer instantiations_;
557 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo);
558 }; // class ParameterizedTestCaseInfo
560 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
562 // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
563 // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
564 // macros use it to locate their corresponding ParameterizedTestCaseInfo
566 class ParameterizedTestCaseRegistry {
568 ParameterizedTestCaseRegistry() {}
569 ~ParameterizedTestCaseRegistry() {
570 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
571 it != test_case_infos_.end(); ++it) {
576 // Looks up or creates and returns a structure containing information about
577 // tests and instantiations of a particular test case.
578 template <class TestCase>
579 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
580 const char* test_case_name,
583 ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL;
584 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
585 it != test_case_infos_.end(); ++it) {
586 if ((*it)->GetTestCaseName() == test_case_name) {
587 if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
588 // Complain about incorrect usage of Google Test facilities
589 // and terminate the program since we cannot guaranty correct
590 // test case setup and tear-down in this case.
591 ReportInvalidTestCaseType(test_case_name, file, line);
594 // At this point we are sure that the object we found is of the same
595 // type we are looking for, so we downcast it to that type
596 // without further checks.
597 typed_test_info = CheckedDowncastToActualType<
598 ParameterizedTestCaseInfo<TestCase> >(*it);
603 if (typed_test_info == NULL) {
604 typed_test_info = new ParameterizedTestCaseInfo<TestCase>(test_case_name);
605 test_case_infos_.push_back(typed_test_info);
607 return typed_test_info;
609 void RegisterTests() {
610 for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
611 it != test_case_infos_.end(); ++it) {
612 (*it)->RegisterTests();
617 typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer;
619 TestCaseInfoContainer test_case_infos_;
621 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry);
624 } // namespace internal
625 } // namespace testing
627 #endif // GTEST_HAS_PARAM_TEST
629 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_