Unverified Commit 120863ba authored by Romain Deterre's avatar Romain Deterre Committed by GitHub
Browse files

Update Google Test to v1.10.0 (#840)

This commit updates the version of Google Test from 1.8 to 1.10.
parent b2f89386
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. <b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
# The Problem # # The Problem
Template and macro libraries often need to define many classes, Template and macro libraries often need to define many classes, functions, or
functions, or macros that vary only (or almost only) in the number of macros that vary only (or almost only) in the number of arguments they take.
arguments they take. It's a lot of repetitive, mechanical, and It's a lot of repetitive, mechanical, and error-prone work.
error-prone work.
Variadic templates and variadic macros can alleviate the problem. Variadic templates and variadic macros can alleviate the problem. However, while
However, while both are being considered by the C++ committee, neither both are being considered by the C++ committee, neither is in the standard yet
is in the standard yet or widely supported by compilers. Thus they or widely supported by compilers. Thus they are often not a good choice,
are often not a good choice, especially when your code needs to be especially when your code needs to be portable. And their capabilities are still
portable. And their capabilities are still limited. limited.
As a result, authors of such libraries often have to write scripts to As a result, authors of such libraries often have to write scripts to generate
generate their implementation. However, our experience is that it's their implementation. However, our experience is that it's tedious to write such
tedious to write such scripts, which tend to reflect the structure of scripts, which tend to reflect the structure of the generated code poorly and
the generated code poorly and are often hard to read and edit. For are often hard to read and edit. For example, a small change needed in the
example, a small change needed in the generated code may require some generated code may require some non-intuitive, non-trivial changes in the
non-intuitive, non-trivial changes in the script. This is especially script. This is especially painful when experimenting with the code.
painful when experimenting with the code.
# Our Solution # # Our Solution
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
Programming, or Practical Utility for Meta Programming, whichever you Programming, or Practical Utility for Meta Programming, whichever you prefer) is
prefer) is a simple meta-programming tool for C++. The idea is that a a simple meta-programming tool for C++. The idea is that a programmer writes a
programmer writes a `foo.pump` file which contains C++ code plus meta `foo.pump` file which contains C++ code plus meta code that manipulates the C++
code that manipulates the C++ code. The meta code can handle code. The meta code can handle iterations over a range, nested iterations, local
iterations over a range, nested iterations, local meta variable meta variable definitions, simple arithmetic, and conditional expressions. You
definitions, simple arithmetic, and conditional expressions. You can can view it as a small Domain-Specific Language. The meta language is designed
view it as a small Domain-Specific Language. The meta language is to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and
designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, concise, making Pump code intuitive and easy to maintain.
for example) and concise, making Pump code intuitive and easy to
maintain. ## Highlights
## Highlights ## * The implementation is in a single Python script and thus ultra portable: no
build or installation is needed and it works cross platforms.
* The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. * Pump tries to be smart with respect to
* Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. [Google's style guide](https://github.com/google/styleguide): it breaks long
* The format is human-readable and more concise than XML. lines (easy to have when they are generated) at acceptable places to fit
* The format works relatively well with Emacs' C++ mode. within 80 columns and indent the continuation lines correctly.
* The format is human-readable and more concise than XML.
## Examples ## * The format works relatively well with Emacs' C++ mode.
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): ## Examples
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are
meta brackets, and `$$` starts a meta comment that ends with the line):
``` ```
$var n = 3 $$ Defines a meta variable n. $var n = 3 $$ Defines a meta variable n.
...@@ -71,7 +70,7 @@ $if i == 0 [[ ...@@ -71,7 +70,7 @@ $if i == 0 [[
will be translated by the Pump compiler to: will be translated by the Pump compiler to:
``` ```cpp
// Foo0 does blah for 0-ary predicates. // Foo0 does blah for 0-ary predicates.
template <size_t N> template <size_t N>
class Foo0 { class Foo0 {
...@@ -105,9 +104,10 @@ Func($for i + [[a$i]]); ...@@ -105,9 +104,10 @@ Func($for i + [[a$i]]);
$$ The text between i and [[ is the separator between iterations. $$ The text between i and [[ is the separator between iterations.
``` ```
will generate one of the following lines (without the comments), depending on the value of `n`: will generate one of the following lines (without the comments), depending on
the value of `n`:
``` ```cpp
Func(); // If n is 0. Func(); // If n is 0.
Func(a1); // If n is 1. Func(a1); // If n is 1.
Func(a1 + a2); // If n is 2. Func(a1 + a2); // If n is 2.
...@@ -115,32 +115,38 @@ Func(a1 + a2 + a3); // If n is 3. ...@@ -115,32 +115,38 @@ Func(a1 + a2 + a3); // If n is 3.
// And so on... // And so on...
``` ```
## Constructs ## ## Constructs
We support the following meta programming constructs: We support the following meta programming constructs:
| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | | `$var id = exp` | Defines a named constant value. `$id` is |
|:----------------|:-----------------------------------------------------------------------------------------------| : : valid util the end of the current meta :
| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | : : lexical block. :
| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | | :------------------------------- | :--------------------------------------- |
| `$($)` | Generates a single `$` character. | | `$range id exp..exp` | Sets the range of an iteration variable, |
| `$id` | Value of the named constant or iteration variable. | : : which can be reused in multiple loops :
| `$(exp)` | Value of the expression. | : : later. :
| `$if exp [[ code ]] else_branch` | Conditional. | | `$for id sep [[ code ]]` | Iteration. The range of `id` must have |
| `[[ code ]]` | Meta lexical block. | : : been defined earlier. `$id` is valid in :
| `cpp_code` | Raw C++ code. | : : `code`. :
| `$$ comment` | Meta comment. | | `$($)` | Generates a single `$` character. |
| `$id` | Value of the named constant or iteration |
**Note:** To give the user some freedom in formatting the Pump source : : variable. :
code, Pump ignores a new-line character if it's right after `$for foo` | `$(exp)` | Value of the expression. |
or next to `[[` or `]]`. Without this rule you'll often be forced to write | `$if exp [[ code ]] else_branch` | Conditional. |
very long lines to get the desired output. Therefore sometimes you may | `[[ code ]]` | Meta lexical block. |
need to insert an extra new-line in such places for a new-line to show | `cpp_code` | Raw C++ code. |
up in your output. | `$$ comment` | Meta comment. |
## Grammar ## **Note:** To give the user some freedom in formatting the Pump source code, Pump
ignores a new-line character if it's right after `$for foo` or next to `[[` or
``` `]]`. Without this rule you'll often be forced to write very long lines to get
the desired output. Therefore sometimes you may need to insert an extra new-line
in such places for a new-line to show up in your output.
## Grammar
```ebnf
code ::= atomic_code* code ::= atomic_code*
atomic_code ::= $var id = exp atomic_code ::= $var id = exp
| $var id = [[ code ]] | $var id = [[ code ]]
...@@ -159,19 +165,26 @@ else_branch ::= $else [[ code ]] ...@@ -159,19 +165,26 @@ else_branch ::= $else [[ code ]]
exp ::= simple_expression_in_Python_syntax exp ::= simple_expression_in_Python_syntax
``` ```
## Code ## ## Code
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py).
very unpolished and lacks automated tests, although it has been It is still very unpolished and lacks automated tests, although it has been
successfully used many times. If you find a chance to use it in your successfully used many times. If you find a chance to use it in your project,
project, please let us know what you think! We also welcome help on please let us know what you think! We also welcome help on improving Pump.
improving Pump.
## Real Examples ## ## Real Examples
You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. You can find real-world applications of Pump in
[Google Test](https://github.com/google/googletest/tree/master/googletest) and
[Google Mock](https://github.com/google/googletest/tree/master/googlemock). The
source file `foo.h.pump` generates `foo.h`.
## Tips ## ## Tips
* If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. * If a meta variable is followed by a letter or digit, you can separate them
* To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper`
generate `Foo1Helper` when `j` is 1.
* To avoid extra-long Pump source lines, you can break a line anywhere you
want by inserting `[[]]` followed by a new line. Since any new-line
character next to `[[` or `]]` is ignored, the generated code won't contain
this new line.
# Googletest Samples {#samples}
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
* Sample #1 shows the basic steps of using googletest to test C++ functions.
* Sample #2 shows a more complex unit test for a class with multiple member
functions.
* Sample #3 uses a test fixture.
* Sample #4 teaches you how to use googletest and `googletest.h` together to
get the best of both libraries.
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
derived fixtures.
* Sample #6 demonstrates type-parameterized tests.
* Sample #7 teaches the basics of value-parameterized tests.
* Sample #8 shows using `Combine()` in value-parameterized tests.
* Sample #9 shows use of the listener API to modify Google Test's console
output and the use of its reflection API to inspect test results.
* Sample #10 shows use of the listener API to implement a primitive memory
leak checker.
...@@ -26,14 +26,14 @@ ...@@ -26,14 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: wan@google.com (Zhanyong Wan) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file defines the public API for death tests. It is // This header file defines the public API for death tests. It is
// #included by gtest.h so a user doesn't need to include this // #included by gtest.h so a user doesn't need to include this
// directly. // directly.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
...@@ -99,10 +99,11 @@ GTEST_API_ bool InDeathTestChild(); ...@@ -99,10 +99,11 @@ GTEST_API_ bool InDeathTestChild();
// //
// On the regular expressions used in death tests: // On the regular expressions used in death tests:
// //
// GOOGLETEST_CM0005 DO NOT DELETE
// On POSIX-compliant systems (*nix), we use the <regex.h> library, // On POSIX-compliant systems (*nix), we use the <regex.h> library,
// which uses the POSIX extended regex syntax. // which uses the POSIX extended regex syntax.
// //
// On other platforms (e.g. Windows), we only support a simple regex // On other platforms (e.g. Windows or Mac), we only support a simple regex
// syntax implemented as part of Google Test. This limited // syntax implemented as part of Google Test. This limited
// implementation should be enough most of the time when writing // implementation should be enough most of the time when writing
// death tests; though it lacks many features you can find in PCRE // death tests; though it lacks many features you can find in PCRE
...@@ -160,7 +161,6 @@ GTEST_API_ bool InDeathTestChild(); ...@@ -160,7 +161,6 @@ GTEST_API_ bool InDeathTestChild();
// is rarely a problem as people usually don't put the test binary // is rarely a problem as people usually don't put the test binary
// directory in PATH. // directory in PATH.
// //
// TODO(wan@google.com): make thread-safe death tests search the PATH.
// Asserts that a given statement causes the program to exit, with an // Asserts that a given statement causes the program to exit, with an
// integer exit status that satisfies predicate, and emitting error output // integer exit status that satisfies predicate, and emitting error output
...@@ -169,7 +169,7 @@ GTEST_API_ bool InDeathTestChild(); ...@@ -169,7 +169,7 @@ GTEST_API_ bool InDeathTestChild();
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
// Like ASSERT_EXIT, but continues on to successive tests in the // Like ASSERT_EXIT, but continues on to successive tests in the
// test case, if any: // test suite, if any:
# define EXPECT_EXIT(statement, predicate, regex) \ # define EXPECT_EXIT(statement, predicate, regex) \
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
...@@ -180,7 +180,7 @@ GTEST_API_ bool InDeathTestChild(); ...@@ -180,7 +180,7 @@ GTEST_API_ bool InDeathTestChild();
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
// Like ASSERT_DEATH, but continues on to successive tests in the // Like ASSERT_DEATH, but continues on to successive tests in the
// test case, if any: // test suite, if any:
# define EXPECT_DEATH(statement, regex) \ # define EXPECT_DEATH(statement, regex) \
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
...@@ -198,9 +198,10 @@ class GTEST_API_ ExitedWithCode { ...@@ -198,9 +198,10 @@ class GTEST_API_ ExitedWithCode {
const int exit_code_; const int exit_code_;
}; };
# if !GTEST_OS_WINDOWS # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Tests that an exit code describes an exit due to termination by a // Tests that an exit code describes an exit due to termination by a
// given signal. // given signal.
// GOOGLETEST_CM0006 DO NOT DELETE
class GTEST_API_ KilledBySignal { class GTEST_API_ KilledBySignal {
public: public:
explicit KilledBySignal(int signum); explicit KilledBySignal(int signum);
...@@ -226,7 +227,7 @@ class GTEST_API_ KilledBySignal { ...@@ -226,7 +227,7 @@ class GTEST_API_ KilledBySignal {
// return 12; // return 12;
// } // }
// //
// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
// int sideeffect = 0; // int sideeffect = 0;
// // Only asserts in dbg. // // Only asserts in dbg.
// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
...@@ -272,6 +273,54 @@ class GTEST_API_ KilledBySignal { ...@@ -272,6 +273,54 @@ class GTEST_API_ KilledBySignal {
# endif // NDEBUG for EXPECT_DEBUG_DEATH # endif // NDEBUG for EXPECT_DEBUG_DEATH
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
// This macro is used for implementing macros such as
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
// death tests are not supported. Those macros must compile on such systems
// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
// on systems that support death tests. This allows one to write such a macro on
// a system that does not support death tests and be sure that it will compile
// on a death-test supporting system. It is exposed publicly so that systems
// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
// ASSERT_DEATH_IF_SUPPORTED.
//
// Parameters:
// statement - A statement that a macro such as EXPECT_DEATH would test
// for program termination. This macro has to make sure this
// statement is compiled but not executed, to ensure that
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
// parameter if and only if EXPECT_DEATH compiles with it.
// regex - A regex that a macro such as EXPECT_DEATH would use to test
// the output of statement. This parameter has to be
// compiled but not evaluated by this macro, to ensure that
// this macro only accepts expressions that a macro such as
// EXPECT_DEATH would accept.
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
// compile inside functions where ASSERT_DEATH doesn't
// compile.
//
// The branch that has an always false condition is used to ensure that
// statement and regex are compiled (and thus syntactically correct) but
// never executed. The unreachable code macro protects the terminator
// statement from generating an 'unreachable code' warning in case
// statement unconditionally returns or throws. The Message constructor at
// the end allows the syntax of streaming additional messages into the
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_LOG_(WARNING) \
<< "Death tests are not supported on this platform.\n" \
<< "Statement '" #statement "' cannot be verified."; \
} else if (::testing::internal::AlwaysFalse()) { \
::testing::internal::RE::PartialMatch(".*", (regex)); \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
terminator; \
} else \
::testing::Message()
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
// death tests are supported; otherwise they just issue a warning. This is // death tests are supported; otherwise they just issue a warning. This is
...@@ -284,9 +333,9 @@ class GTEST_API_ KilledBySignal { ...@@ -284,9 +333,9 @@ class GTEST_API_ KilledBySignal {
ASSERT_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
#else #else
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
#endif #endif
} // namespace testing } // namespace testing
......
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument.
// IWYU pragma: private, include "testing/base/public/gunit.h"
// IWYU pragma: friend third_party/googletest/googlemock/.*
// IWYU pragma: friend third_party/googletest/googletest/.*
#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include "gtest/gtest-printers.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
// MSVC warning C5046 is new as of VS2017 version 15.8.
#if defined(_MSC_VER) && _MSC_VER >= 1915
#define GTEST_MAYBE_5046_ 5046
#else
#define GTEST_MAYBE_5046_
#endif
GTEST_DISABLE_MSC_WARNINGS_PUSH_(
4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
clients of class B */
/* Symbol involving type with internal linkage not defined */)
namespace testing {
// To implement a matcher Foo for type T, define:
// 1. a class FooMatcherImpl that implements the
// MatcherInterface<T> interface, and
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherImpl*.
//
// The two-level delegation design makes it possible to allow a user
// to write "v" instead of "Eq(v)" where a Matcher is expected, which
// is impossible if we pass matchers by pointers. It also eases
// ownership management as Matcher objects can now be copied like
// plain values.
// MatchResultListener is an abstract class. Its << operator can be
// used by a matcher to explain why a value matches or doesn't match.
//
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
// listener does not own the ostream, and does not dereference it
// in the constructor or destructor.
explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
virtual ~MatchResultListener() = 0; // Makes this class abstract.
// Streams x to the underlying ostream; does nothing if the ostream
// is NULL.
template <typename T>
MatchResultListener& operator<<(const T& x) {
if (stream_ != nullptr) *stream_ << x;
return *this;
}
// Returns the underlying ostream.
::std::ostream* stream() { return stream_; }
// Returns true if and only if the listener is interested in an explanation
// of the match result. A matcher's MatchAndExplain() method can use
// this information to avoid generating the explanation when no one
// intends to hear it.
bool IsInterested() const { return stream_ != nullptr; }
private:
::std::ostream* const stream_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
};
inline MatchResultListener::~MatchResultListener() {
}
// An instance of a subclass of this knows how to describe itself as a
// matcher.
class MatcherDescriberInterface {
public:
virtual ~MatcherDescriberInterface() {}
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
// matcher should have. The subject of the verb phrase is the value
// being matched. For example, the DescribeTo() method of the Gt(7)
// matcher prints "is greater than 7".
virtual void DescribeTo(::std::ostream* os) const = 0;
// Describes the negation of this matcher to an ostream. For
// example, if the description of this matcher is "is greater than
// 7", the negated description could be "is not greater than 7".
// You are not required to override this when implementing
// MatcherInterface, but it is highly advised so that your matcher
// can produce good error messages.
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "not (";
DescribeTo(os);
*os << ")";
}
};
// The implementation of a matcher.
template <typename T>
class MatcherInterface : public MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener' if necessary (see the next paragraph), in
// the form of a non-restrictive relative clause ("which ...",
// "whose ...", etc) that describes x. For example, the
// MatchAndExplain() method of the Pointee(...) matcher should
// generate an explanation like "which points to ...".
//
// Implementations of MatchAndExplain() should add an explanation of
// the match result *if and only if* they can provide additional
// information that's not already present (or not obvious) in the
// print-out of x and the matcher's description. Whether the match
// succeeds is not a factor in deciding whether an explanation is
// needed, as sometimes the caller needs to print a failure message
// when the match succeeds (e.g. when the matcher is used inside
// Not()).
//
// For example, a "has at least 10 elements" matcher should explain
// what the actual element count is, regardless of the match result,
// as it is useful information to the reader; on the other hand, an
// "is empty" matcher probably only needs to explain what the actual
// size is when the match fails, as it's redundant to say that the
// size is 0 when the value is already known to be empty.
//
// You should override this method when defining a new matcher.
//
// It's the responsibility of the caller (Google Test) to guarantee
// that 'listener' is not NULL. This helps to simplify a matcher's
// implementation when it doesn't care about the performance, as it
// can talk to 'listener' without checking its validity first.
// However, in order to implement dummy listeners efficiently,
// listener->stream() may be NULL.
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
// Inherits these methods from MatcherDescriberInterface:
// virtual void DescribeTo(::std::ostream* os) const = 0;
// virtual void DescribeNegationTo(::std::ostream* os) const;
};
namespace internal {
// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
template <typename T>
class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
public:
explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
: impl_(impl) {}
~MatcherInterfaceAdapter() override { delete impl_; }
void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
void DescribeNegationTo(::std::ostream* os) const override {
impl_->DescribeNegationTo(os);
}
bool MatchAndExplain(const T& x,
MatchResultListener* listener) const override {
return impl_->MatchAndExplain(x, listener);
}
private:
const MatcherInterface<T>* const impl_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
};
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a == b; }
};
struct AnyNe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a != b; }
};
struct AnyLt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a < b; }
};
struct AnyGt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a > b; }
};
struct AnyLe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a <= b; }
};
struct AnyGe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a >= b; }
};
// A match result listener that ignores the explanation.
class DummyMatchResultListener : public MatchResultListener {
public:
DummyMatchResultListener() : MatchResultListener(nullptr) {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
};
// A match result listener that forwards the explanation to a given
// ostream. The difference between this and MatchResultListener is
// that the former is concrete.
class StreamMatchResultListener : public MatchResultListener {
public:
explicit StreamMatchResultListener(::std::ostream* os)
: MatchResultListener(os) {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
};
// An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
class MatcherBase {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
return impl_->MatchAndExplain(x, listener);
}
// Returns true if and only if this matcher matches x.
bool Matches(const T& x) const {
DummyMatchResultListener dummy;
return MatchAndExplain(x, &dummy);
}
// Describes this matcher to an ostream.
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
// Describes the negation of this matcher to an ostream.
void DescribeNegationTo(::std::ostream* os) const {
impl_->DescribeNegationTo(os);
}
// Explains why x matches, or doesn't match, the matcher.
void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
StreamMatchResultListener listener(os);
MatchAndExplain(x, &listener);
}
// Returns the describer for this matcher object; retains ownership
// of the describer, which is only guaranteed to be alive when
// this matcher object is alive.
const MatcherDescriberInterface* GetDescriber() const {
return impl_.get();
}
protected:
MatcherBase() {}
// Constructs a matcher from its implementation.
explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
template <typename U>
explicit MatcherBase(
const MatcherInterface<U>* impl,
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
nullptr)
: impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
MatcherBase(const MatcherBase&) = default;
MatcherBase& operator=(const MatcherBase&) = default;
MatcherBase(MatcherBase&&) = default;
MatcherBase& operator=(MatcherBase&&) = default;
virtual ~MatcherBase() {}
private:
std::shared_ptr<const MatcherInterface<const T&>> impl_;
};
} // namespace internal
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
// object that can check whether a value of type T matches. The
// implementation of Matcher<T> is just a std::shared_ptr to const
// MatcherInterface<T>. Don't inherit from Matcher!
template <typename T>
class Matcher : public internal::MatcherBase<T> {
public:
// Constructs a null matcher. Needed for storing Matcher objects in STL
// containers. A default-constructed matcher is not yet initialized. You
// cannot use it until a valid value has been assigned to it.
explicit Matcher() {} // NOLINT
// Constructs a matcher from its implementation.
explicit Matcher(const MatcherInterface<const T&>* impl)
: internal::MatcherBase<T>(impl) {}
template <typename U>
explicit Matcher(
const MatcherInterface<U>* impl,
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
nullptr)
: internal::MatcherBase<T>(impl) {}
// Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT
};
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
// matcher is expected.
template <>
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
template <>
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<std::string>(impl) {}
explicit Matcher(const MatcherInterface<std::string>* impl)
: internal::MatcherBase<std::string>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
#if GTEST_HAS_ABSL
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
class GTEST_API_ Matcher<const absl::string_view&>
: public internal::MatcherBase<const absl::string_view&> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
: internal::MatcherBase<const absl::string_view&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly.
Matcher(absl::string_view s); // NOLINT
};
template <>
class GTEST_API_ Matcher<absl::string_view>
: public internal::MatcherBase<absl::string_view> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
: internal::MatcherBase<absl::string_view>(impl) {}
explicit Matcher(const MatcherInterface<absl::string_view>* impl)
: internal::MatcherBase<absl::string_view>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly.
Matcher(absl::string_view s); // NOLINT
};
#endif // GTEST_HAS_ABSL
// Prints a matcher in a human-readable format.
template <typename T>
std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
matcher.DescribeTo(&os);
return os;
}
// The PolymorphicMatcher class template makes it easy to implement a
// polymorphic matcher (i.e. a matcher that can match values of more
// than one type, e.g. Eq(n) and NotNull()).
//
// To define a polymorphic matcher, a user should provide an Impl
// class that has a DescribeTo() method and a DescribeNegationTo()
// method, and define a member function (or member function template)
//
// bool MatchAndExplain(const Value& value,
// MatchResultListener* listener) const;
//
// See the definition of NotNull() for a complete example.
template <class Impl>
class PolymorphicMatcher {
public:
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
// Returns a mutable reference to the underlying matcher
// implementation object.
Impl& mutable_impl() { return impl_; }
// Returns an immutable reference to the underlying matcher
// implementation object.
const Impl& impl() const { return impl_; }
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
}
private:
template <typename T>
class MonomorphicImpl : public MatcherInterface<T> {
public:
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); }
virtual void DescribeNegationTo(::std::ostream* os) const {
impl_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
return impl_.MatchAndExplain(x, listener);
}
private:
const Impl impl_;
};
Impl impl_;
};
// Creates a matcher from its implementation.
// DEPRECATED: Especially in the generic code, prefer:
// Matcher<T>(new MyMatcherImpl<const T&>(...));
//
// MakeMatcher may create a Matcher that accepts its argument by value, which
// leads to unnecessary copies & lack of support for non-copyable types.
template <typename T>
inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
return Matcher<T>(impl);
}
// Creates a polymorphic matcher from its implementation. This is
// easier to use than the PolymorphicMatcher<Impl> constructor as it
// doesn't require you to explicitly write the template argument, e.g.
//
// MakePolymorphicMatcher(foo);
// vs
// PolymorphicMatcher<TypeOfFoo>(foo);
template <class Impl>
inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
return PolymorphicMatcher<Impl>(impl);
}
namespace internal {
// Implements a matcher that compares a given value with a
// pre-supplied value using one of the ==, <=, <, etc, operators. The
// two values being compared don't have to have the same type.
//
// The matcher defined here is polymorphic (for example, Eq(5) can be
// used to match an int, a short, a double, etc). Therefore we use
// a template type conversion operator in the implementation.
//
// The following template definition assumes that the Rhs parameter is
// a "bare" type (i.e. neither 'const T' nor 'T&').
template <typename D, typename Rhs, typename Op>
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
template <typename Lhs>
operator Matcher<Lhs>() const {
return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
}
private:
template <typename T>
static const T& Unwrap(const T& v) { return v; }
template <typename T>
static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
template <typename Lhs, typename = Rhs>
class Impl : public MatcherInterface<Lhs> {
public:
explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
bool MatchAndExplain(Lhs lhs,
MatchResultListener* /* listener */) const override {
return Op()(lhs, Unwrap(rhs_));
}
void DescribeTo(::std::ostream* os) const override {
*os << D::Desc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << D::NegatedDesc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
private:
Rhs rhs_;
};
Rhs rhs_;
};
template <typename Rhs>
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
public:
explicit EqMatcher(const Rhs& rhs)
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
public:
explicit NeMatcher(const Rhs& rhs)
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
public:
explicit LtMatcher(const Rhs& rhs)
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
public:
explicit GtMatcher(const Rhs& rhs)
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
public:
explicit LeMatcher(const Rhs& rhs)
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
public:
explicit GeMatcher(const Rhs& rhs)
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
class MatchesRegexMatcher {
public:
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
#if GTEST_HAS_ABSL
bool MatchAndExplain(const absl::string_view& s,
MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
#endif // GTEST_HAS_ABSL
// Accepts pointer types, particularly:
// const char*
// char*
// const wchar_t*
// wchar_t*
template <typename CharType>
bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
return s != nullptr && MatchAndExplain(std::string(s), listener);
}
// Matches anything that can convert to std::string.
//
// This is a template, not just a plain function with const std::string&,
// because absl::string_view has some interfering non-explicit constructors.
template <class MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
const std::string& s2(s);
return full_match_ ? RE::FullMatch(s2, *regex_)
: RE::PartialMatch(s2, *regex_);
}
void DescribeTo(::std::ostream* os) const {
*os << (full_match_ ? "matches" : "contains") << " regular expression ";
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't " << (full_match_ ? "match" : "contain")
<< " regular expression ";
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
}
private:
const std::shared_ptr<const RE> regex_;
const bool full_match_;
};
} // namespace internal
// Matches a string that fully matches regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const std::string& regex) {
return MatchesRegex(new internal::RE(regex));
}
// Matches a string that contains regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const std::string& regex) {
return ContainsRegex(new internal::RE(regex));
}
// Creates a polymorphic matcher that matches anything equal to x.
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
// wouldn't compile.
template <typename T>
inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
// Constructs a Matcher<T> from a 'value' of type T. The constructed
// matcher matches any value that's equal to 'value'.
template <typename T>
Matcher<T>::Matcher(T value) { *this = Eq(value); }
// Creates a monomorphic matcher that matches anything with type Lhs
// and equal to rhs. A user may need to use this instead of Eq(...)
// in order to resolve an overloading ambiguity.
//
// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
// or Matcher<T>(x), but more readable than the latter.
//
// We could define similar monomorphic matchers for other comparison
// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
// it yet as those are used much less than Eq() in practice. A user
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
// for example.
template <typename Lhs, typename Rhs>
inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
// Creates a polymorphic matcher that matches anything >= x.
template <typename Rhs>
inline internal::GeMatcher<Rhs> Ge(Rhs x) {
return internal::GeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything > x.
template <typename Rhs>
inline internal::GtMatcher<Rhs> Gt(Rhs x) {
return internal::GtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything <= x.
template <typename Rhs>
inline internal::LeMatcher<Rhs> Le(Rhs x) {
return internal::LeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything < x.
template <typename Rhs>
inline internal::LtMatcher<Rhs> Lt(Rhs x) {
return internal::LtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything != x.
template <typename Rhs>
inline internal::NeMatcher<Rhs> Ne(Rhs x) {
return internal::NeMatcher<Rhs>(x);
}
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
...@@ -26,10 +26,9 @@ ...@@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: wan@google.com (Zhanyong Wan) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file defines the Message class. // This header file defines the Message class.
// //
...@@ -43,13 +42,19 @@ ...@@ -43,13 +42,19 @@
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
// program! // program!
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#include <limits> #include <limits>
#include <memory>
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
// Ensures that there is at least one operator<< in the global namespace. // Ensures that there is at least one operator<< in the global namespace.
// See Message& operator<<(...) below for why. // See Message& operator<<(...) below for why.
void operator<<(const testing::internal::Secret&, int); void operator<<(const testing::internal::Secret&, int);
...@@ -102,14 +107,6 @@ class GTEST_API_ Message { ...@@ -102,14 +107,6 @@ class GTEST_API_ Message {
*ss_ << str; *ss_ << str;
} }
#if GTEST_OS_SYMBIAN
// Streams a value (either a pointer or not) to this object.
template <typename T>
inline Message& operator <<(const T& value) {
StreamHelper(typename internal::is_pointer<T>::type(), value);
return *this;
}
#else
// Streams a non-pointer value to this object. // Streams a non-pointer value to this object.
template <typename T> template <typename T>
inline Message& operator <<(const T& val) { inline Message& operator <<(const T& val) {
...@@ -147,14 +144,13 @@ class GTEST_API_ Message { ...@@ -147,14 +144,13 @@ class GTEST_API_ Message {
// as "(null)". // as "(null)".
template <typename T> template <typename T>
inline Message& operator <<(T* const& pointer) { // NOLINT inline Message& operator <<(T* const& pointer) { // NOLINT
if (pointer == NULL) { if (pointer == nullptr) {
*ss_ << "(null)"; *ss_ << "(null)";
} else { } else {
*ss_ << pointer; *ss_ << pointer;
} }
return *this; return *this;
} }
#endif // GTEST_OS_SYMBIAN
// Since the basic IO manipulators are overloaded for both narrow // Since the basic IO manipulators are overloaded for both narrow
// and wide streams, we have to provide this specialized definition // and wide streams, we have to provide this specialized definition
...@@ -183,12 +179,6 @@ class GTEST_API_ Message { ...@@ -183,12 +179,6 @@ class GTEST_API_ Message {
Message& operator <<(const ::std::wstring& wstr); Message& operator <<(const ::std::wstring& wstr);
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_GLOBAL_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& operator <<(const ::wstring& wstr);
#endif // GTEST_HAS_GLOBAL_WSTRING
// Gets the text streamed to this object so far as an std::string. // Gets the text streamed to this object so far as an std::string.
// Each '\0' character in the buffer is replaced with "\\0". // Each '\0' character in the buffer is replaced with "\\0".
// //
...@@ -196,32 +186,8 @@ class GTEST_API_ Message { ...@@ -196,32 +186,8 @@ class GTEST_API_ Message {
std::string GetString() const; std::string GetString() const;
private: private:
#if GTEST_OS_SYMBIAN
// These are needed as the Nokia Symbian Compiler cannot decide between
// const T& and const T* in a function template. The Nokia compiler _can_
// decide between class template specializations for T and T*, so a
// tr1::type_traits-like is_pointer works, and we can overload on that.
template <typename T>
inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) {
if (pointer == NULL) {
*ss_ << "(null)";
} else {
*ss_ << pointer;
}
}
template <typename T>
inline void StreamHelper(internal::false_type /*is_pointer*/,
const T& value) {
// See the comments in Message& operator <<(const T&) above for why
// we need this using statement.
using ::operator <<;
*ss_ << value;
}
#endif // GTEST_OS_SYMBIAN
// We'll hold the text streamed to this object here. // We'll hold the text streamed to this object here.
const internal::scoped_ptr< ::std::stringstream> ss_; const std::unique_ptr< ::std::stringstream> ss_;
// We declare (but don't implement) this to prevent the compiler // We declare (but don't implement) this to prevent the compiler
// from implementing the assignment operator. // from implementing the assignment operator.
...@@ -247,4 +213,6 @@ std::string StreamableToString(const T& streamable) { ...@@ -247,4 +213,6 @@ std::string StreamableToString(const T& streamable) {
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
$$ -*- mode: c++; -*-
$var n = 50 $$ Maximum length of Values arguments we want to support.
$var maxtuple = 10 $$ Maximum number of Combine arguments we want to support.
// Copyright 2008, Google Inc. // Copyright 2008, Google Inc.
// All rights reserved. // All rights reserved.
// //
...@@ -30,13 +27,12 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. ...@@ -30,13 +27,12 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support.
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Authors: vladl@google.com (Vlad Losev)
//
// Macros and functions for implementing parameterized tests // Macros and functions for implementing parameterized tests
// in Google C++ Testing Framework (Google Test) // in Google C++ Testing and Mocking Framework (Google Test)
// //
// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
// //
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
...@@ -75,10 +71,10 @@ TEST_P(FooTest, HasBlahBlah) { ...@@ -75,10 +71,10 @@ TEST_P(FooTest, HasBlahBlah) {
... ...
} }
// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
// case with any set of parameters you want. Google Test defines a number // case with any set of parameters you want. Google Test defines a number
// of functions for generating test parameters. They return what we call // of functions for generating test parameters. They return what we call
// (surprise!) parameter generators. Here is a summary of them, which // (surprise!) parameter generators. Here is a summary of them, which
// are all in the testing namespace: // are all in the testing namespace:
// //
// //
...@@ -96,17 +92,17 @@ TEST_P(FooTest, HasBlahBlah) { ...@@ -96,17 +92,17 @@ TEST_P(FooTest, HasBlahBlah) {
// For more details, see comments at the definitions of these functions below // For more details, see comments at the definitions of these functions below
// in this file. // in this file.
// //
// The following statement will instantiate tests from the FooTest test case // The following statement will instantiate tests from the FooTest test suite
// each with parameter values "meeny", "miny", and "moe". // each with parameter values "meeny", "miny", and "moe".
INSTANTIATE_TEST_CASE_P(InstantiationName, INSTANTIATE_TEST_SUITE_P(InstantiationName,
FooTest, FooTest,
Values("meeny", "miny", "moe")); Values("meeny", "miny", "moe"));
// To distinguish different instances of the pattern, (yes, you // To distinguish different instances of the pattern, (yes, you
// can instantiate it more then once) the first argument to the // can instantiate it more than once) the first argument to the
// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
// actual test case name. Remember to pick unique prefixes for different // actual test suite name. Remember to pick unique prefixes for different
// instantiations. The tests from the instantiation above will have // instantiations. The tests from the instantiation above will have
// these names: // these names:
// //
...@@ -123,7 +119,7 @@ INSTANTIATE_TEST_CASE_P(InstantiationName, ...@@ -123,7 +119,7 @@ INSTANTIATE_TEST_CASE_P(InstantiationName,
// with parameter values "cat" and "dog": // with parameter values "cat" and "dog":
const char* pets[] = {"cat", "dog"}; const char* pets[] = {"cat", "dog"};
INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
// The tests from the instantiation above will have these names: // The tests from the instantiation above will have these names:
// //
...@@ -132,9 +128,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); ...@@ -132,9 +128,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
// //
// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
// in the given test case, whether their definitions come before or // in the given test suite, whether their definitions come before or
// AFTER the INSTANTIATE_TEST_CASE_P statement. // AFTER the INSTANTIATE_TEST_SUITE_P statement.
// //
// Please also note that generator expressions (including parameters to the // Please also note that generator expressions (including parameters to the
// generators) are evaluated in InitGoogleTest(), after main() has started. // generators) are evaluated in InitGoogleTest(), after main() has started.
...@@ -178,31 +174,23 @@ TEST_P(DerivedTest, DoesBlah) { ...@@ -178,31 +174,23 @@ TEST_P(DerivedTest, DoesBlah) {
#endif // 0 #endif // 0
#include "gtest/internal/gtest-port.h" #include <iterator>
#include <utility>
#if !GTEST_OS_SYMBIAN
# include <utility>
#endif
// scripts/fuse_gtest.py depends on gtest's own header being #included
// *unconditionally*. Therefore these #includes cannot be moved
// inside #if GTEST_HAS_PARAM_TEST.
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util.h"
#include "gtest/internal/gtest-param-util-generated.h" #include "gtest/internal/gtest-port.h"
#if GTEST_HAS_PARAM_TEST
namespace testing { namespace testing {
// Functions producing parameter generators. // Functions producing parameter generators.
// //
// Google Test uses these generators to produce parameters for value- // Google Test uses these generators to produce parameters for value-
// parameterized tests. When a parameterized test case is instantiated // parameterized tests. When a parameterized test suite is instantiated
// with a particular generator, Google Test creates and runs tests // with a particular generator, Google Test creates and runs tests
// for each element in the sequence produced by the generator. // for each element in the sequence produced by the generator.
// //
// In the following sample, tests from test case FooTest are instantiated // In the following sample, tests from test suite FooTest are instantiated
// each three times with parameter values 3, 5, and 8: // each three times with parameter values 3, 5, and 8:
// //
// class FooTest : public TestWithParam<int> { ... }; // class FooTest : public TestWithParam<int> { ... };
...@@ -211,7 +199,7 @@ namespace testing { ...@@ -211,7 +199,7 @@ namespace testing {
// } // }
// TEST_P(FooTest, TestThat) { // TEST_P(FooTest, TestThat) {
// } // }
// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
// //
// Range() returns generators providing sequences of values in a range. // Range() returns generators providing sequences of values in a range.
...@@ -268,13 +256,13 @@ internal::ParamGenerator<T> Range(T start, T end) { ...@@ -268,13 +256,13 @@ internal::ParamGenerator<T> Range(T start, T end) {
// //
// Examples: // Examples:
// //
// This instantiates tests from test case StringTest // This instantiates tests from test suite StringTest
// each with C-string values of "foo", "bar", and "baz": // each with C-string values of "foo", "bar", and "baz":
// //
// const char* strings[] = {"foo", "bar", "baz"}; // const char* strings[] = {"foo", "bar", "baz"};
// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
// //
// This instantiates tests from test case StlStringTest // This instantiates tests from test suite StlStringTest
// each with STL strings with values "a" and "b": // each with STL strings with values "a" and "b":
// //
// ::std::vector< ::std::string> GetParameterStrings() { // ::std::vector< ::std::string> GetParameterStrings() {
...@@ -284,9 +272,9 @@ internal::ParamGenerator<T> Range(T start, T end) { ...@@ -284,9 +272,9 @@ internal::ParamGenerator<T> Range(T start, T end) {
// return v; // return v;
// } // }
// //
// INSTANTIATE_TEST_CASE_P(CharSequence, // INSTANTIATE_TEST_SUITE_P(CharSequence,
// StlStringTest, // StlStringTest,
// ValuesIn(GetParameterStrings())); // ValuesIn(GetParameterStrings()));
// //
// //
// This will also instantiate tests from CharTest // This will also instantiate tests from CharTest
...@@ -299,16 +287,15 @@ internal::ParamGenerator<T> Range(T start, T end) { ...@@ -299,16 +287,15 @@ internal::ParamGenerator<T> Range(T start, T end) {
// return list; // return list;
// } // }
// ::std::list<char> l = GetParameterChars(); // ::std::list<char> l = GetParameterChars();
// INSTANTIATE_TEST_CASE_P(CharSequence2, // INSTANTIATE_TEST_SUITE_P(CharSequence2,
// CharTest, // CharTest,
// ValuesIn(l.begin(), l.end())); // ValuesIn(l.begin(), l.end()));
// //
template <typename ForwardIterator> template <typename ForwardIterator>
internal::ParamGenerator< internal::ParamGenerator<
typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type> typename std::iterator_traits<ForwardIterator>::value_type>
ValuesIn(ForwardIterator begin, ForwardIterator end) { ValuesIn(ForwardIterator begin, ForwardIterator end) {
typedef typename ::testing::internal::IteratorTraits<ForwardIterator> typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
::value_type ParamType;
return internal::ParamGenerator<ParamType>( return internal::ParamGenerator<ParamType>(
new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end)); new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
} }
...@@ -331,29 +318,24 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn( ...@@ -331,29 +318,24 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
// Values(T v1, T v2, ..., T vN) // Values(T v1, T v2, ..., T vN)
// - returns a generator producing sequences with elements v1, v2, ..., vN. // - returns a generator producing sequences with elements v1, v2, ..., vN.
// //
// For example, this instantiates tests from test case BarTest each // For example, this instantiates tests from test suite BarTest each
// with values "one", "two", and "three": // with values "one", "two", and "three":
// //
// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); // INSTANTIATE_TEST_SUITE_P(NumSequence,
// BarTest,
// Values("one", "two", "three"));
// //
// This instantiates tests from test case BazTest each with values 1, 2, 3.5. // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
// The exact type of values will depend on the type of parameter in BazTest. // The exact type of values will depend on the type of parameter in BazTest.
// //
// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
// //
// Currently, Values() supports from 1 to $n parameters.
// //
$range i 1..n template <typename... T>
$for i [[ internal::ValueArray<T...> Values(T... v) {
$range j 1..i return internal::ValueArray<T...>(std::move(v)...);
template <$for j, [[typename T$j]]>
internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) {
return internal::ValueArray$i<$for j, [[T$j]]>($for j, [[v$j]]);
} }
]]
// Bool() allows generating tests with parameters in a set of (false, true). // Bool() allows generating tests with parameters in a set of (false, true).
// //
// Synopsis: // Synopsis:
...@@ -364,7 +346,7 @@ internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) { ...@@ -364,7 +346,7 @@ internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) {
// of multiple flags can be tested when several Bool()'s are combined using // of multiple flags can be tested when several Bool()'s are combined using
// Combine() function. // Combine() function.
// //
// In the following example all tests in the test case FlagDependentTest // In the following example all tests in the test suite FlagDependentTest
// will be instantiated twice with parameters false and true. // will be instantiated twice with parameters false and true.
// //
// class FlagDependentTest : public testing::TestWithParam<bool> { // class FlagDependentTest : public testing::TestWithParam<bool> {
...@@ -372,13 +354,12 @@ internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) { ...@@ -372,13 +354,12 @@ internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) {
// external_flag = GetParam(); // external_flag = GetParam();
// } // }
// } // }
// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
// //
inline internal::ParamGenerator<bool> Bool() { inline internal::ParamGenerator<bool> Bool() {
return Values(false, true); return Values(false, true);
} }
# if GTEST_HAS_COMBINE
// Combine() allows the user to combine two or more sequences to produce // Combine() allows the user to combine two or more sequences to produce
// values of a Cartesian product of those sequences' elements. // values of a Cartesian product of those sequences' elements.
// //
...@@ -387,95 +368,83 @@ inline internal::ParamGenerator<bool> Bool() { ...@@ -387,95 +368,83 @@ inline internal::ParamGenerator<bool> Bool() {
// - returns a generator producing sequences with elements coming from // - returns a generator producing sequences with elements coming from
// the Cartesian product of elements from the sequences generated by // the Cartesian product of elements from the sequences generated by
// gen1, gen2, ..., genN. The sequence elements will have a type of // gen1, gen2, ..., genN. The sequence elements will have a type of
// tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
// of elements from sequences produces by gen1, gen2, ..., genN. // of elements from sequences produces by gen1, gen2, ..., genN.
// //
// Combine can have up to $maxtuple arguments. This number is currently limited // Combine can have up to 10 arguments.
// by the maximum number of elements in the tuple implementation used by Google
// Test.
// //
// Example: // Example:
// //
// This will instantiate tests in test case AnimalTest each one with // This will instantiate tests in test suite AnimalTest each one with
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
// tuple("dog", BLACK), and tuple("dog", WHITE): // tuple("dog", BLACK), and tuple("dog", WHITE):
// //
// enum Color { BLACK, GRAY, WHITE }; // enum Color { BLACK, GRAY, WHITE };
// class AnimalTest // class AnimalTest
// : public testing::TestWithParam<tuple<const char*, Color> > {...}; // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
// //
// TEST_P(AnimalTest, AnimalLooksNice) {...} // TEST_P(AnimalTest, AnimalLooksNice) {...}
// //
// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
// Combine(Values("cat", "dog"), // Combine(Values("cat", "dog"),
// Values(BLACK, WHITE))); // Values(BLACK, WHITE)));
// //
// This will instantiate tests in FlagDependentTest with all variations of two // This will instantiate tests in FlagDependentTest with all variations of two
// Boolean flags: // Boolean flags:
// //
// class FlagDependentTest // class FlagDependentTest
// : public testing::TestWithParam<tuple<bool, bool> > { // : public testing::TestWithParam<std::tuple<bool, bool> > {
// virtual void SetUp() { // virtual void SetUp() {
// // Assigns external_flag_1 and external_flag_2 values from the tuple. // // Assigns external_flag_1 and external_flag_2 values from the tuple.
// tie(external_flag_1, external_flag_2) = GetParam(); // std::tie(external_flag_1, external_flag_2) = GetParam();
// } // }
// }; // };
// //
// TEST_P(FlagDependentTest, TestFeature1) { // TEST_P(FlagDependentTest, TestFeature1) {
// // Test your code using external_flag_1 and external_flag_2 here. // // Test your code using external_flag_1 and external_flag_2 here.
// } // }
// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
// Combine(Bool(), Bool())); // Combine(Bool(), Bool()));
// //
$range i 2..maxtuple template <typename... Generator>
$for i [[ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
$range j 1..i return internal::CartesianProductHolder<Generator...>(g...);
template <$for j, [[typename Generator$j]]>
internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine(
$for j, [[const Generator$j& g$j]]) {
return internal::CartesianProductHolder$i<$for j, [[Generator$j]]>(
$for j, [[g$j]]);
} }
]] #define TEST_P(test_suite_name, test_name) \
# endif // GTEST_HAS_COMBINE class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public test_suite_name { \
public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
# define TEST_P(test_case_name, test_name) \ virtual void TestBody(); \
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ \
: public test_case_name { \ private: \
public: \ static int AddToRegistry() { \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ ::testing::UnitTest::GetInstance() \
virtual void TestBody(); \ ->parameterized_test_registry() \
private: \ .GetTestSuitePatternHolder<test_suite_name>( \
static int AddToRegistry() { \ #test_suite_name, \
::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
GetTestCasePatternHolder<test_case_name>(\ ->AddTestPattern( \
#test_case_name, \ GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
::testing::internal::CodeLocation(\ new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
__FILE__, __LINE__))->AddTestPattern(\ test_suite_name, test_name)>()); \
#test_case_name, \ return 0; \
#test_name, \ } \
new ::testing::internal::TestMetaFactory< \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_TEST_CLASS_NAME_(\ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_case_name, test_name)>()); \ test_name)); \
return 0; \ }; \
} \ int GTEST_TEST_CLASS_NAME_(test_suite_name, \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ test_name)::gtest_registering_dummy_ = \
GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
}; \
int GTEST_TEST_CLASS_NAME_(test_case_name, \ // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
test_name)::gtest_registering_dummy_ = \ // generator and an optional function or functor that generates custom test name
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ // suffixes based on the test parameters. Such a function or functor should
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() // accept one argument of type testing::TestParamInfo<class ParamType>, and
// return std::string.
// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user
// to specify a function or functor that generates custom test name suffixes
// based on the test parameters. The function should accept one argument of
// type testing::TestParamInfo<class ParamType>, and return std::string.
// //
// testing::PrintToStringParamName is a builtin test suffix generator that // testing::PrintToStringParamName is a builtin test suffix generator that
// returns the value of testing::PrintToString(GetParam()). // returns the value of testing::PrintToString(GetParam()).
...@@ -484,27 +453,51 @@ internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine( ...@@ -484,27 +453,51 @@ internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine(
// alphanumeric characters or underscore. Because PrintToString adds quotes // alphanumeric characters or underscore. Because PrintToString adds quotes
// to std::string and C strings, it won't work for these types. // to std::string and C strings, it won't work for these types.
# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ #define GTEST_EXPAND_(arg) arg
::testing::internal::ParamGenerator<test_case_name::ParamType> \ #define GTEST_GET_FIRST_(first, ...) first
gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ #define GTEST_GET_SECOND_(first, second, ...) second
::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_case_name::ParamType>& info) { \ #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
return ::testing::internal::GetParamNameGen<test_case_name::ParamType> \ static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
(__VA_ARGS__)(info); \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \
} \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ } \
::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
GetTestCasePatternHolder<test_case_name>(\ const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
#test_case_name, \ if (::testing::internal::AlwaysFalse()) { \
::testing::internal::CodeLocation(\ ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__FILE__, __LINE__))->AddTestCaseInstantiation(\ __VA_ARGS__, \
#prefix, \ ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
&gtest_##prefix##test_case_name##_EvalGenerator_, \ DUMMY_PARAM_))); \
&gtest_##prefix##test_case_name##_EvalGenerateName_, \ auto t = std::make_tuple(__VA_ARGS__); \
__FILE__, __LINE__) static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \
} \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \
} \
static int gtest_##prefix##test_suite_name##_dummy_ \
GTEST_ATTRIBUTE_UNUSED_ = \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
#test_suite_name, \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \
#prefix, &gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__)
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TEST_CASE_P \
static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
""); \
INSTANTIATE_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
} // namespace testing } // namespace testing
#endif // GTEST_HAS_PARAM_TEST
#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
...@@ -26,10 +26,9 @@ ...@@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
// Google Test - The Google C++ Testing and Mocking Framework
// //
// This file implements a universal value printer that can print a // This file implements a universal value printer that can print a
// value of any type T: // value of any type T:
...@@ -46,6 +45,10 @@ ...@@ -46,6 +45,10 @@
// 2. operator<<(ostream&, const T&) defined in either foo or the // 2. operator<<(ostream&, const T&) defined in either foo or the
// global namespace. // global namespace.
// //
// However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
// operator<<() is ignored for container types.
//
// If none of the above is defined, it will print the debug string of // If none of the above is defined, it will print the debug string of
// the value if it is a protocol buffer, or print the raw bytes in the // the value if it is a protocol buffer, or print the raw bytes in the
// value otherwise. // value otherwise.
...@@ -92,20 +95,27 @@ ...@@ -92,20 +95,27 @@
// being defined as many user-defined container types don't have // being defined as many user-defined container types don't have
// value_type. // value_type.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <functional>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <tuple>
#include <type_traits>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_HAS_STD_TUPLE_ #if GTEST_HAS_ABSL
# include <tuple> #include "absl/strings/string_view.h"
#endif #include "absl/types/optional.h"
#include "absl/types/variant.h"
#endif // GTEST_HAS_ABSL
namespace testing { namespace testing {
...@@ -125,7 +135,11 @@ enum TypeKind { ...@@ -125,7 +135,11 @@ enum TypeKind {
kProtobuf, // a protobuf type kProtobuf, // a protobuf type
kConvertibleToInteger, // a type implicitly convertible to BiggestInt kConvertibleToInteger, // a type implicitly convertible to BiggestInt
// (e.g. a named or unnamed enum type) // (e.g. a named or unnamed enum type)
kOtherType // anything else #if GTEST_HAS_ABSL
kConvertibleToStringView, // a type implicitly convertible to
// absl::string_view
#endif
kOtherType // anything else
}; };
// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
...@@ -137,8 +151,10 @@ class TypeWithoutFormatter { ...@@ -137,8 +151,10 @@ class TypeWithoutFormatter {
public: public:
// This default version is called when kTypeKind is kOtherType. // This default version is called when kTypeKind is kOtherType.
static void PrintValue(const T& value, ::std::ostream* os) { static void PrintValue(const T& value, ::std::ostream* os) {
PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value), PrintBytesInObjectTo(
sizeof(value), os); static_cast<const unsigned char*>(
reinterpret_cast<const void*>(std::addressof(value))),
sizeof(value), os);
} }
}; };
...@@ -151,10 +167,10 @@ template <typename T> ...@@ -151,10 +167,10 @@ template <typename T>
class TypeWithoutFormatter<T, kProtobuf> { class TypeWithoutFormatter<T, kProtobuf> {
public: public:
static void PrintValue(const T& value, ::std::ostream* os) { static void PrintValue(const T& value, ::std::ostream* os) {
const ::testing::internal::string short_str = value.ShortDebugString(); std::string pretty_str = value.ShortDebugString();
const ::testing::internal::string pretty_str = if (pretty_str.length() > kProtobufOneLinerMaxLength) {
short_str.length() <= kProtobufOneLinerMaxLength ? pretty_str = "\n" + value.DebugString();
short_str : ("\n" + value.DebugString()); }
*os << ("<" + pretty_str + ">"); *os << ("<" + pretty_str + ">");
} }
}; };
...@@ -175,6 +191,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> { ...@@ -175,6 +191,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
} }
}; };
#if GTEST_HAS_ABSL
template <typename T>
class TypeWithoutFormatter<T, kConvertibleToStringView> {
public:
// Since T has neither operator<< nor PrintTo() but can be implicitly
// converted to absl::string_view, we print it as a absl::string_view.
//
// Note: the implementation is further below, as it depends on
// internal::PrintTo symbol which is defined later in the file.
static void PrintValue(const T& value, ::std::ostream* os);
};
#endif
// Prints the given value to the given ostream. If the value is a // Prints the given value to the given ostream. If the value is a
// protocol message, its debug string is printed; if it's an enum or // protocol message, its debug string is printed; if it's an enum or
// of a type implicitly convertible to BiggestInt, it's printed as an // of a type implicitly convertible to BiggestInt, it's printed as an
...@@ -202,10 +231,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> { ...@@ -202,10 +231,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
template <typename Char, typename CharTraits, typename T> template <typename Char, typename CharTraits, typename T>
::std::basic_ostream<Char, CharTraits>& operator<<( ::std::basic_ostream<Char, CharTraits>& operator<<(
::std::basic_ostream<Char, CharTraits>& os, const T& x) { ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
TypeWithoutFormatter<T, TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
(internal::IsAProtocolMessage<T>::value ? kProtobuf : ? kProtobuf
internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ? : std::is_convertible<
kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); const T&, internal::BiggestInt>::value
? kConvertibleToInteger
:
#if GTEST_HAS_ABSL
std::is_convertible<
const T&, absl::string_view>::value
? kConvertibleToStringView
:
#endif
kOtherType)>::PrintValue(x, &os);
return os; return os;
} }
...@@ -320,16 +358,6 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); ...@@ -320,16 +358,6 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
#if GTEST_HAS_GLOBAL_STRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
#endif
#if GTEST_HAS_GLOBAL_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
#endif
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
...@@ -364,11 +392,18 @@ class UniversalPrinter; ...@@ -364,11 +392,18 @@ class UniversalPrinter;
template <typename T> template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os); void UniversalPrint(const T& value, ::std::ostream* os);
enum DefaultPrinterType {
kPrintContainer,
kPrintPointer,
kPrintFunctionPointer,
kPrintOther,
};
template <DefaultPrinterType type> struct WrapPrinterType {};
// Used to print an STL-style container when the user doesn't define // Used to print an STL-style container when the user doesn't define
// a PrintTo() for it. // a PrintTo() for it.
template <typename C> template <typename C>
void DefaultPrintTo(IsContainer /* dummy */, void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
false_type /* is not a pointer */,
const C& container, ::std::ostream* os) { const C& container, ::std::ostream* os) {
const size_t kMaxCount = 32; // The maximum number of elements to print. const size_t kMaxCount = 32; // The maximum number of elements to print.
*os << '{'; *os << '{';
...@@ -401,40 +436,34 @@ void DefaultPrintTo(IsContainer /* dummy */, ...@@ -401,40 +436,34 @@ void DefaultPrintTo(IsContainer /* dummy */,
// implementation-defined. Therefore they will be printed as raw // implementation-defined. Therefore they will be printed as raw
// bytes.) // bytes.)
template <typename T> template <typename T>
void DefaultPrintTo(IsNotContainer /* dummy */, void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
true_type /* is a pointer */,
T* p, ::std::ostream* os) { T* p, ::std::ostream* os) {
if (p == NULL) { if (p == nullptr) {
*os << "NULL"; *os << "NULL";
} else { } else {
// C++ doesn't allow casting from a function pointer to any object // T is not a function type. We just call << to print p,
// pointer. // relying on ADL to pick up user-defined << for their pointer
// // types, if any.
// IsTrue() silences warnings: "Condition is always true", *os << p;
// "unreachable code". }
if (IsTrue(ImplicitlyConvertible<T*, const void*>::value)) { }
// T is not a function type. We just call << to print p, template <typename T>
// relying on ADL to pick up user-defined << for their pointer void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
// types, if any. T* p, ::std::ostream* os) {
*os << p; if (p == nullptr) {
} else { *os << "NULL";
// T is a function type, so '*os << p' doesn't do what we want } else {
// (it just prints p as bool). We want to print p as a const // T is a function type, so '*os << p' doesn't do what we want
// void*. However, we cannot cast it to const void* directly, // (it just prints p as bool). We want to print p as a const
// even using reinterpret_cast, as earlier versions of gcc // void*.
// (e.g. 3.4.5) cannot compile the cast when p is a function *os << reinterpret_cast<const void*>(p);
// pointer. Casting to UInt64 first solves the problem.
*os << reinterpret_cast<const void*>(
reinterpret_cast<internal::UInt64>(p));
}
} }
} }
// Used to print a non-container, non-pointer value when the user // Used to print a non-container, non-pointer value when the user
// doesn't define PrintTo() for it. // doesn't define PrintTo() for it.
template <typename T> template <typename T>
void DefaultPrintTo(IsNotContainer /* dummy */, void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
false_type /* is not a pointer */,
const T& value, ::std::ostream* os) { const T& value, ::std::ostream* os) {
::testing_internal::DefaultPrintNonContainerTo(value, os); ::testing_internal::DefaultPrintNonContainerTo(value, os);
} }
...@@ -452,11 +481,8 @@ void DefaultPrintTo(IsNotContainer /* dummy */, ...@@ -452,11 +481,8 @@ void DefaultPrintTo(IsNotContainer /* dummy */,
// wants). // wants).
template <typename T> template <typename T>
void PrintTo(const T& value, ::std::ostream* os) { void PrintTo(const T& value, ::std::ostream* os) {
// DefaultPrintTo() is overloaded. The type of its first two // DefaultPrintTo() is overloaded. The type of its first argument
// arguments determine which version will be picked. If T is an // determines which version will be picked.
// STL-style container, the version for container will be called; if
// T is a pointer, the pointer version will be called; otherwise the
// generic version will be called.
// //
// Note that we check for container types here, prior to we check // Note that we check for container types here, prior to we check
// for protocol message types in our operator<<. The rationale is: // for protocol message types in our operator<<. The rationale is:
...@@ -468,13 +494,23 @@ void PrintTo(const T& value, ::std::ostream* os) { ...@@ -468,13 +494,23 @@ void PrintTo(const T& value, ::std::ostream* os) {
// elements; therefore we check for container types here to ensure // elements; therefore we check for container types here to ensure
// that our format is used. // that our format is used.
// //
// The second argument of DefaultPrintTo() is needed to bypass a bug // Note that MSVC and clang-cl do allow an implicit conversion from
// in Symbian's C++ compiler that prevents it from picking the right // pointer-to-function to pointer-to-object, but clang-cl warns on it.
// overload between: // So don't use ImplicitlyConvertible if it can be helped since it will
// // cause this warning, and use a separate overload of DefaultPrintTo for
// PrintTo(const T& x, ...); // function pointers so that the `*os << p` in the object pointer overload
// PrintTo(T* x, ...); // doesn't cause that warning either.
DefaultPrintTo(IsContainerTest<T>(0), is_pointer<T>(), value, os); DefaultPrintTo(
WrapPrinterType <
(sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
!IsRecursiveContainer<T>::value
? kPrintContainer
: !std::is_pointer<T>::value
? kPrintOther
: std::is_function<typename std::remove_pointer<T>::type>::value
? kPrintFunctionPointer
: kPrintPointer > (),
value, os);
} }
// The following list of PrintTo() overloads tells // The following list of PrintTo() overloads tells
...@@ -553,27 +589,13 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { ...@@ -553,27 +589,13 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
} }
} }
// Overloads for ::string and ::std::string. // Overloads for ::std::string.
#if GTEST_HAS_GLOBAL_STRING
GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os);
inline void PrintTo(const ::string& s, ::std::ostream* os) {
PrintStringTo(s, os);
}
#endif // GTEST_HAS_GLOBAL_STRING
GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
inline void PrintTo(const ::std::string& s, ::std::ostream* os) { inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os); PrintStringTo(s, os);
} }
// Overloads for ::wstring and ::std::wstring. // Overloads for ::std::wstring.
#if GTEST_HAS_GLOBAL_WSTRING
GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
...@@ -581,95 +603,45 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { ...@@ -581,95 +603,45 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ #if GTEST_HAS_ABSL
// Helper function for printing a tuple. T must be instantiated with // Overload for absl::string_view.
// a tuple type. inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
template <typename T> PrintTo(::std::string(sp), os);
void PrintTupleTo(const T& t, ::std::ostream* os);
#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_TR1_TUPLE
// Overload for ::std::tr1::tuple. Needed for printing function arguments,
// which are packed as tuples.
// Overloaded PrintTo() for tuples of various arities. We support
// tuples of up-to 10 fields. The following implementation works
// regardless of whether tr1::tuple is implemented using the
// non-standard variadic template feature or not.
inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
} }
#endif // GTEST_HAS_ABSL
template <typename T1> inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2>
void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5, template <typename T>
typename T6, typename T7, typename T8> void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t, UniversalPrinter<T&>::Print(ref.get(), os);
::std::ostream* os) {
PrintTupleTo(t, os);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8, typename T9>
void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
::std::ostream* os) {
PrintTupleTo(t, os);
} }
template <typename T1, typename T2, typename T3, typename T4, typename T5, // Helper function for printing a tuple. T must be instantiated with
typename T6, typename T7, typename T8, typename T9, typename T10> // a tuple type.
void PrintTo( template <typename T>
const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t, void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
::std::ostream* os) { ::std::ostream*) {}
PrintTupleTo(t, os);
template <typename T, size_t I>
void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
::std::ostream* os) {
PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (I > 1) {
GTEST_INTENTIONAL_CONST_COND_POP_()
*os << ", ";
}
UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
std::get<I - 1>(t), os);
} }
#endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
template <typename... Types> template <typename... Types>
void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) { void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
PrintTupleTo(t, os); *os << "(";
PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
*os << ")";
} }
#endif // GTEST_HAS_STD_TUPLE_
// Overload for std::pair. // Overload for std::pair.
template <typename T1, typename T2> template <typename T1, typename T2>
...@@ -710,6 +682,48 @@ class UniversalPrinter { ...@@ -710,6 +682,48 @@ class UniversalPrinter {
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
}; };
#if GTEST_HAS_ABSL
// Printer for absl::optional
template <typename T>
class UniversalPrinter<::absl::optional<T>> {
public:
static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
} else {
UniversalPrint(*value, os);
}
*os << ')';
}
};
// Printer for absl::variant
template <typename... T>
class UniversalPrinter<::absl::variant<T...>> {
public:
static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
*os << '(';
absl::visit(Visitor{os}, value);
*os << ')';
}
private:
struct Visitor {
template <typename U>
void operator()(const U& u) const {
*os << "'" << GetTypeName<U>() << "' with value ";
UniversalPrint(u, os);
}
::std::ostream* os;
};
};
#endif // GTEST_HAS_ABSL
// UniversalPrintArray(begin, len, os) prints an array of 'len' // UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'. // elements, starting at address 'begin'.
template <typename T> template <typename T>
...@@ -723,7 +737,6 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { ...@@ -723,7 +737,6 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
// If the array has more than kThreshold elements, we'll have to // If the array has more than kThreshold elements, we'll have to
// omit some details by printing only the first and the last // omit some details by printing only the first and the last
// kChunkSize elements. // kChunkSize elements.
// TODO(wan@google.com): let the user control the threshold using a flag.
if (len <= kThreshold) { if (len <= kThreshold) {
PrintRawArrayTo(begin, len, os); PrintRawArrayTo(begin, len, os);
} else { } else {
...@@ -802,10 +815,10 @@ template <> ...@@ -802,10 +815,10 @@ template <>
class UniversalTersePrinter<const char*> { class UniversalTersePrinter<const char*> {
public: public:
static void Print(const char* str, ::std::ostream* os) { static void Print(const char* str, ::std::ostream* os) {
if (str == NULL) { if (str == nullptr) {
*os << "NULL"; *os << "NULL";
} else { } else {
UniversalPrint(string(str), os); UniversalPrint(std::string(str), os);
} }
} }
}; };
...@@ -822,7 +835,7 @@ template <> ...@@ -822,7 +835,7 @@ template <>
class UniversalTersePrinter<const wchar_t*> { class UniversalTersePrinter<const wchar_t*> {
public: public:
static void Print(const wchar_t* str, ::std::ostream* os) { static void Print(const wchar_t* str, ::std::ostream* os) {
if (str == NULL) { if (str == nullptr) {
*os << "NULL"; *os << "NULL";
} else { } else {
UniversalPrint(::std::wstring(str), os); UniversalPrint(::std::wstring(str), os);
...@@ -856,110 +869,22 @@ void UniversalPrint(const T& value, ::std::ostream* os) { ...@@ -856,110 +869,22 @@ void UniversalPrint(const T& value, ::std::ostream* os) {
UniversalPrinter<T1>::Print(value, os); UniversalPrinter<T1>::Print(value, os);
} }
typedef ::std::vector<string> Strings; typedef ::std::vector< ::std::string> Strings;
// TuplePolicy<TupleT> must provide:
// - tuple_size
// size of tuple TupleT.
// - get<size_t I>(const TupleT& t)
// static function extracting element I of tuple TupleT.
// - tuple_element<size_t I>::type
// type of element I of tuple TupleT.
template <typename TupleT>
struct TuplePolicy;
#if GTEST_HAS_TR1_TUPLE
template <typename TupleT>
struct TuplePolicy {
typedef TupleT Tuple;
static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
template <size_t I>
struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {};
template <size_t I>
static typename AddReference<
const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get(
const Tuple& tuple) {
return ::std::tr1::get<I>(tuple);
}
};
template <typename TupleT>
const size_t TuplePolicy<TupleT>::tuple_size;
#endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
template <typename... Types>
struct TuplePolicy< ::std::tuple<Types...> > {
typedef ::std::tuple<Types...> Tuple;
static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
template <size_t I>
struct tuple_element : ::std::tuple_element<I, Tuple> {};
template <size_t I>
static const typename ::std::tuple_element<I, Tuple>::type& get(
const Tuple& tuple) {
return ::std::get<I>(tuple);
}
};
template <typename... Types>
const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
#endif // GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
// This helper template allows PrintTo() for tuples and
// UniversalTersePrintTupleFieldsToStrings() to be defined by
// induction on the number of tuple fields. The idea is that
// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
// fields in tuple t, and can be defined in terms of
// TuplePrefixPrinter<N - 1>.
//
// The inductive case.
template <size_t N>
struct TuplePrefixPrinter {
// Prints the first N fields of a tuple.
template <typename Tuple>
static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (N > 1) {
GTEST_INTENTIONAL_CONST_COND_POP_()
*os << ", ";
}
UniversalPrinter<
typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
}
// Tersely prints the first N fields of a tuple to a string vector, // Tersely prints the first N fields of a tuple to a string vector,
// one element for each field. // one element for each field.
template <typename Tuple>
static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
::std::stringstream ss;
UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
strings->push_back(ss.str());
}
};
// Base case.
template <>
struct TuplePrefixPrinter<0> {
template <typename Tuple>
static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
template <typename Tuple>
static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
};
// Helper function for printing a tuple.
// Tuple must be either std::tr1::tuple or std::tuple type.
template <typename Tuple> template <typename Tuple>
void PrintTupleTo(const Tuple& t, ::std::ostream* os) { void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
*os << "("; Strings*) {}
TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os); template <typename Tuple, size_t I>
*os << ")"; void TersePrintPrefixToStrings(const Tuple& t,
std::integral_constant<size_t, I>,
Strings* strings) {
TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
strings);
::std::stringstream ss;
UniversalTersePrint(std::get<I - 1>(t), &ss);
strings->push_back(ss.str());
} }
// Prints the fields of a tuple tersely to a string vector, one // Prints the fields of a tuple tersely to a string vector, one
...@@ -968,14 +893,24 @@ void PrintTupleTo(const Tuple& t, ::std::ostream* os) { ...@@ -968,14 +893,24 @@ void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
template <typename Tuple> template <typename Tuple>
Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
Strings result; Strings result;
TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>:: TersePrintPrefixToStrings(
TersePrintPrefixToStrings(value, &result); value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
&result);
return result; return result;
} }
#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
} // namespace internal } // namespace internal
#if GTEST_HAS_ABSL
namespace internal2 {
template <typename T>
void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
const T& value, ::std::ostream* os) {
internal::PrintTo(absl::string_view(value), os);
}
} // namespace internal2
#endif
template <typename T> template <typename T>
::std::string PrintToString(const T& value) { ::std::string PrintToString(const T& value) {
::std::stringstream ss; ::std::stringstream ss;
......
...@@ -26,17 +26,21 @@ ...@@ -26,17 +26,21 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// //
// Utilities for testing Google Test itself and code that uses Google Test // Utilities for testing Google Test itself and code that uses Google Test
// (e.g. frameworks built on top of Google Test). // (e.g. frameworks built on top of Google Test).
// GOOGLETEST_CM0004 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#include "gtest/gtest.h" #include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing { namespace testing {
// This helper class can be used to mock out Google Test failure reporting // This helper class can be used to mock out Google Test failure reporting
...@@ -68,14 +72,15 @@ class GTEST_API_ ScopedFakeTestPartResultReporter ...@@ -68,14 +72,15 @@ class GTEST_API_ ScopedFakeTestPartResultReporter
TestPartResultArray* result); TestPartResultArray* result);
// The d'tor restores the previous test part result reporter. // The d'tor restores the previous test part result reporter.
virtual ~ScopedFakeTestPartResultReporter(); ~ScopedFakeTestPartResultReporter() override;
// Appends the TestPartResult object to the TestPartResultArray // Appends the TestPartResult object to the TestPartResultArray
// received in the constructor. // received in the constructor.
// //
// This method is from the TestPartResultReporterInterface // This method is from the TestPartResultReporterInterface
// interface. // interface.
virtual void ReportTestPartResult(const TestPartResult& result); void ReportTestPartResult(const TestPartResult& result) override;
private: private:
void Init(); void Init();
...@@ -97,13 +102,12 @@ class GTEST_API_ SingleFailureChecker { ...@@ -97,13 +102,12 @@ class GTEST_API_ SingleFailureChecker {
public: public:
// The constructor remembers the arguments. // The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results, SingleFailureChecker(const TestPartResultArray* results,
TestPartResult::Type type, TestPartResult::Type type, const std::string& substr);
const string& substr);
~SingleFailureChecker(); ~SingleFailureChecker();
private: private:
const TestPartResultArray* const results_; const TestPartResultArray* const results_;
const TestPartResult::Type type_; const TestPartResult::Type type_;
const string substr_; const std::string substr_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
}; };
...@@ -112,6 +116,8 @@ class GTEST_API_ SingleFailureChecker { ...@@ -112,6 +116,8 @@ class GTEST_API_ SingleFailureChecker {
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// A set of macros for testing Google Test assertions or code that's expected // A set of macros for testing Google Test assertions or code that's expected
// to generate Google Test fatal failures. It verifies that the given // to generate Google Test fatal failures. It verifies that the given
// statement will cause exactly one fatal Google Test failure with 'substr' // statement will cause exactly one fatal Google Test failure with 'substr'
......
...@@ -27,8 +27,7 @@ ...@@ -27,8 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: mheule@google.com (Markus Heule) // GOOGLETEST_CM0001 DO NOT DELETE
//
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
...@@ -38,6 +37,9 @@ ...@@ -38,6 +37,9 @@
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing { namespace testing {
// A copyable object representing the result of a test part (i.e. an // A copyable object representing the result of a test part (i.e. an
...@@ -51,22 +53,20 @@ class GTEST_API_ TestPartResult { ...@@ -51,22 +53,20 @@ class GTEST_API_ TestPartResult {
enum Type { enum Type {
kSuccess, // Succeeded. kSuccess, // Succeeded.
kNonFatalFailure, // Failed but the test can continue. kNonFatalFailure, // Failed but the test can continue.
kFatalFailure // Failed and the test should be terminated. kFatalFailure, // Failed and the test should be terminated.
kSkip // Skipped.
}; };
// C'tor. TestPartResult does NOT have a default constructor. // C'tor. TestPartResult does NOT have a default constructor.
// Always use this constructor (with parameters) to create a // Always use this constructor (with parameters) to create a
// TestPartResult object. // TestPartResult object.
TestPartResult(Type a_type, TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
const char* a_file_name,
int a_line_number,
const char* a_message) const char* a_message)
: type_(a_type), : type_(a_type),
file_name_(a_file_name == NULL ? "" : a_file_name), file_name_(a_file_name == nullptr ? "" : a_file_name),
line_number_(a_line_number), line_number_(a_line_number),
summary_(ExtractSummary(a_message)), summary_(ExtractSummary(a_message)),
message_(a_message) { message_(a_message) {}
}
// Gets the outcome of the test part. // Gets the outcome of the test part.
Type type() const { return type_; } Type type() const { return type_; }
...@@ -74,7 +74,7 @@ class GTEST_API_ TestPartResult { ...@@ -74,7 +74,7 @@ class GTEST_API_ TestPartResult {
// Gets the name of the source file where the test part took place, or // Gets the name of the source file where the test part took place, or
// NULL if it's unknown. // NULL if it's unknown.
const char* file_name() const { const char* file_name() const {
return file_name_.empty() ? NULL : file_name_.c_str(); return file_name_.empty() ? nullptr : file_name_.c_str();
} }
// Gets the line in the source file where the test part took place, // Gets the line in the source file where the test part took place,
...@@ -87,18 +87,21 @@ class GTEST_API_ TestPartResult { ...@@ -87,18 +87,21 @@ class GTEST_API_ TestPartResult {
// Gets the message associated with the test part. // Gets the message associated with the test part.
const char* message() const { return message_.c_str(); } const char* message() const { return message_.c_str(); }
// Returns true iff the test part passed. // Returns true if and only if the test part was skipped.
bool passed() const { return type_ == kSuccess; } bool skipped() const { return type_ == kSkip; }
// Returns true iff the test part failed. // Returns true if and only if the test part passed.
bool failed() const { return type_ != kSuccess; } bool passed() const { return type_ == kSuccess; }
// Returns true iff the test part non-fatally failed. // Returns true if and only if the test part non-fatally failed.
bool nonfatally_failed() const { return type_ == kNonFatalFailure; } bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
// Returns true iff the test part fatally failed. // Returns true if and only if the test part fatally failed.
bool fatally_failed() const { return type_ == kFatalFailure; } bool fatally_failed() const { return type_ == kFatalFailure; }
// Returns true if and only if the test part failed.
bool failed() const { return fatally_failed() || nonfatally_failed(); }
private: private:
Type type_; Type type_;
...@@ -143,7 +146,7 @@ class GTEST_API_ TestPartResultArray { ...@@ -143,7 +146,7 @@ class GTEST_API_ TestPartResultArray {
}; };
// This interface knows how to report a test part result. // This interface knows how to report a test part result.
class TestPartResultReporterInterface { class GTEST_API_ TestPartResultReporterInterface {
public: public:
virtual ~TestPartResultReporterInterface() {} virtual ~TestPartResultReporterInterface() {}
...@@ -162,8 +165,8 @@ class GTEST_API_ HasNewFatalFailureHelper ...@@ -162,8 +165,8 @@ class GTEST_API_ HasNewFatalFailureHelper
: public TestPartResultReporterInterface { : public TestPartResultReporterInterface {
public: public:
HasNewFatalFailureHelper(); HasNewFatalFailureHelper();
virtual ~HasNewFatalFailureHelper(); ~HasNewFatalFailureHelper() override;
virtual void ReportTestPartResult(const TestPartResult& result); void ReportTestPartResult(const TestPartResult& result) override;
bool has_new_fatal_failure() const { return has_new_fatal_failure_; } bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
private: private:
bool has_new_fatal_failure_; bool has_new_fatal_failure_;
...@@ -176,4 +179,6 @@ class GTEST_API_ HasNewFatalFailureHelper ...@@ -176,4 +179,6 @@ class GTEST_API_ HasNewFatalFailureHelper
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
...@@ -26,8 +26,9 @@ ...@@ -26,8 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
...@@ -51,22 +52,22 @@ class FooTest : public testing::Test { ...@@ -51,22 +52,22 @@ class FooTest : public testing::Test {
T value_; T value_;
}; };
// Next, associate a list of types with the test case, which will be // Next, associate a list of types with the test suite, which will be
// repeated for each type in the list. The typedef is necessary for // repeated for each type in the list. The typedef is necessary for
// the macro to parse correctly. // the macro to parse correctly.
typedef testing::Types<char, int, unsigned int> MyTypes; typedef testing::Types<char, int, unsigned int> MyTypes;
TYPED_TEST_CASE(FooTest, MyTypes); TYPED_TEST_SUITE(FooTest, MyTypes);
// If the type list contains only one type, you can write that type // If the type list contains only one type, you can write that type
// directly without Types<...>: // directly without Types<...>:
// TYPED_TEST_CASE(FooTest, int); // TYPED_TEST_SUITE(FooTest, int);
// Then, use TYPED_TEST() instead of TEST_F() to define as many typed // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
// tests for this test case as you want. // tests for this test suite as you want.
TYPED_TEST(FooTest, DoesBlah) { TYPED_TEST(FooTest, DoesBlah) {
// Inside a test, refer to TypeParam to get the type parameter. // Inside a test, refer to the special name TypeParam to get the type
// Since we are inside a derived class template, C++ requires use to // parameter. Since we are inside a derived class template, C++ requires
// visit the members of FooTest via 'this'. // us to visit the members of FooTest via 'this'.
TypeParam n = this->value_; TypeParam n = this->value_;
// To visit static members of the fixture, add the TestFixture:: // To visit static members of the fixture, add the TestFixture::
...@@ -82,6 +83,24 @@ TYPED_TEST(FooTest, DoesBlah) { ...@@ -82,6 +83,24 @@ TYPED_TEST(FooTest, DoesBlah) {
TYPED_TEST(FooTest, HasPropertyA) { ... } TYPED_TEST(FooTest, HasPropertyA) { ... }
// TYPED_TEST_SUITE takes an optional third argument which allows to specify a
// class that generates custom test name suffixes based on the type. This should
// be a class which has a static template function GetName(int index) returning
// a string for each type. The provided integer index equals the index of the
// type in the provided type list. In many cases the index can be ignored.
//
// For example:
// class MyTypeNames {
// public:
// template <typename T>
// static std::string GetName(int) {
// if (std::is_same<T, char>()) return "char";
// if (std::is_same<T, int>()) return "int";
// if (std::is_same<T, unsigned int>()) return "unsignedInt";
// }
// };
// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
#endif // 0 #endif // 0
// Type-parameterized tests are abstract test patterns parameterized // Type-parameterized tests are abstract test patterns parameterized
...@@ -107,13 +126,13 @@ class FooTest : public testing::Test { ...@@ -107,13 +126,13 @@ class FooTest : public testing::Test {
... ...
}; };
// Next, declare that you will define a type-parameterized test case // Next, declare that you will define a type-parameterized test suite
// (the _P suffix is for "parameterized" or "pattern", whichever you // (the _P suffix is for "parameterized" or "pattern", whichever you
// prefer): // prefer):
TYPED_TEST_CASE_P(FooTest); TYPED_TEST_SUITE_P(FooTest);
// Then, use TYPED_TEST_P() to define as many type-parameterized tests // Then, use TYPED_TEST_P() to define as many type-parameterized tests
// for this type-parameterized test case as you want. // for this type-parameterized test suite as you want.
TYPED_TEST_P(FooTest, DoesBlah) { TYPED_TEST_P(FooTest, DoesBlah) {
// Inside a test, refer to TypeParam to get the type parameter. // Inside a test, refer to TypeParam to get the type parameter.
TypeParam n = 0; TypeParam n = 0;
...@@ -124,10 +143,10 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... } ...@@ -124,10 +143,10 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... }
// Now the tricky part: you need to register all test patterns before // Now the tricky part: you need to register all test patterns before
// you can instantiate them. The first argument of the macro is the // you can instantiate them. The first argument of the macro is the
// test case name; the rest are the names of the tests in this test // test suite name; the rest are the names of the tests in this test
// case. // case.
REGISTER_TYPED_TEST_CASE_P(FooTest, REGISTER_TYPED_TEST_SUITE_P(FooTest,
DoesBlah, HasPropertyA); DoesBlah, HasPropertyA);
// Finally, you are free to instantiate the pattern with the types you // Finally, you are free to instantiate the pattern with the types you
// want. If you put the above code in a header file, you can #include // want. If you put the above code in a header file, you can #include
...@@ -135,14 +154,19 @@ REGISTER_TYPED_TEST_CASE_P(FooTest, ...@@ -135,14 +154,19 @@ REGISTER_TYPED_TEST_CASE_P(FooTest,
// //
// To distinguish different instances of the pattern, the first // To distinguish different instances of the pattern, the first
// argument to the INSTANTIATE_* macro is a prefix that will be added // argument to the INSTANTIATE_* macro is a prefix that will be added
// to the actual test case name. Remember to pick unique prefixes for // to the actual test suite name. Remember to pick unique prefixes for
// different instances. // different instances.
typedef testing::Types<char, int, unsigned int> MyTypes; typedef testing::Types<char, int, unsigned int> MyTypes;
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
// If the type list contains only one type, you can write that type // If the type list contains only one type, you can write that type
// directly without Types<...>: // directly without Types<...>:
// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
//
// Similar to the optional argument of TYPED_TEST_SUITE above,
// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
// generate custom names.
// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
#endif // 0 #endif // 0
...@@ -156,35 +180,53 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ...@@ -156,35 +180,53 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// Expands to the name of the typedef for the type parameters of the // Expands to the name of the typedef for the type parameters of the
// given test case. // given test suite.
# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
// The 'Types' template argument below must have spaces around it // Expands to the name of the typedef for the NameGenerator, responsible for
// since some compilers may choke on '>>' when passing a template // creating the suffixes of the name.
// instance (e.g. Types<int>) #define GTEST_NAME_GENERATOR_(TestSuiteName) \
# define TYPED_TEST_CASE(CaseName, Types) \ gtest_type_params_##TestSuiteName##_NameGenerator
typedef ::testing::internal::TypeList< Types >::type \
GTEST_TYPE_PARAMS_(CaseName) #define TYPED_TEST_SUITE(CaseName, Types, ...) \
typedef ::testing::internal::TypeList<Types>::type GTEST_TYPE_PARAMS_( \
# define TYPED_TEST(CaseName, TestName) \ CaseName); \
template <typename gtest_TypeParam_> \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ GTEST_NAME_GENERATOR_(CaseName)
: public CaseName<gtest_TypeParam_> { \
private: \ # define TYPED_TEST(CaseName, TestName) \
typedef CaseName<gtest_TypeParam_> TestFixture; \ template <typename gtest_TypeParam_> \
typedef gtest_TypeParam_ TypeParam; \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
virtual void TestBody(); \ : public CaseName<gtest_TypeParam_> { \
}; \ private: \
bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ typedef CaseName<gtest_TypeParam_> TestFixture; \
::testing::internal::TypeParameterizedTest< \ typedef gtest_TypeParam_ TypeParam; \
CaseName, \ virtual void TestBody(); \
::testing::internal::TemplateSel< \ }; \
GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ static bool gtest_##CaseName##_##TestName##_registered_ \
GTEST_TYPE_PARAMS_(CaseName)>::Register(\ GTEST_ATTRIBUTE_UNUSED_ = \
"", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ ::testing::internal::TypeParameterizedTest< \
#CaseName, #TestName, 0); \ CaseName, \
template <typename gtest_TypeParam_> \ ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody() TestName)>, \
GTEST_TYPE_PARAMS_( \
CaseName)>::Register("", \
::testing::internal::CodeLocation( \
__FILE__, __LINE__), \
#CaseName, #TestName, 0, \
::testing::internal::GenerateNames< \
GTEST_NAME_GENERATOR_(CaseName), \
GTEST_TYPE_PARAMS_(CaseName)>()); \
template <typename gtest_TypeParam_> \
void GTEST_TEST_CLASS_NAME_(CaseName, \
TestName)<gtest_TypeParam_>::TestBody()
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define TYPED_TEST_CASE \
static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
TYPED_TEST_SUITE
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#endif // GTEST_HAS_TYPED_TEST #endif // GTEST_HAS_TYPED_TEST
...@@ -195,68 +237,93 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ...@@ -195,68 +237,93 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// Expands to the namespace name that the type-parameterized tests for // Expands to the namespace name that the type-parameterized tests for
// the given type-parameterized test case are defined in. The exact // the given type-parameterized test suite are defined in. The exact
// name of the namespace is subject to change without notice. // name of the namespace is subject to change without notice.
# define GTEST_CASE_NAMESPACE_(TestCaseName) \ #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
gtest_case_##TestCaseName##_
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// Expands to the name of the variable used to remember the names of // Expands to the name of the variable used to remember the names of
// the defined tests in the given test case. // the defined tests in the given test suite.
# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
gtest_typed_test_case_p_state_##TestCaseName##_ gtest_typed_test_suite_p_state_##TestSuiteName##_
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
// //
// Expands to the name of the variable used to remember the names of // Expands to the name of the variable used to remember the names of
// the registered tests in the given test case. // the registered tests in the given test suite.
# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
gtest_registered_test_names_##TestCaseName##_ gtest_registered_test_names_##TestSuiteName##_
// The variables defined in the type-parameterized test macros are // The variables defined in the type-parameterized test macros are
// static as typically these macros are used in a .h file that can be // static as typically these macros are used in a .h file that can be
// #included in multiple translation units linked together. // #included in multiple translation units linked together.
# define TYPED_TEST_CASE_P(CaseName) \ #define TYPED_TEST_SUITE_P(SuiteName) \
static ::testing::internal::TypedTestCasePState \ static ::testing::internal::TypedTestSuitePState \
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
# define TYPED_TEST_P(CaseName, TestName) \ // Legacy API is deprecated but still available
namespace GTEST_CASE_NAMESPACE_(CaseName) { \ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
template <typename gtest_TypeParam_> \ #define TYPED_TEST_CASE_P \
class TestName : public CaseName<gtest_TypeParam_> { \ static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
private: \ TYPED_TEST_SUITE_P
typedef CaseName<gtest_TypeParam_> TestFixture; \ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
typedef gtest_TypeParam_ TypeParam; \
virtual void TestBody(); \ #define TYPED_TEST_P(SuiteName, TestName) \
}; \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ template <typename gtest_TypeParam_> \
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ class TestName : public SuiteName<gtest_TypeParam_> { \
__FILE__, __LINE__, #CaseName, #TestName); \ private: \
} \ typedef SuiteName<gtest_TypeParam_> TestFixture; \
template <typename gtest_TypeParam_> \ typedef gtest_TypeParam_ TypeParam; \
void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody() virtual void TestBody(); \
}; \
# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
namespace GTEST_CASE_NAMESPACE_(CaseName) { \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ __FILE__, __LINE__, #SuiteName, #TestName); \
} \ } \
static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ template <typename gtest_TypeParam_> \
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
} \
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
__FILE__, __LINE__, #__VA_ARGS__) __FILE__, __LINE__, #__VA_ARGS__)
// The 'Types' template argument below must have spaces around it // Legacy API is deprecated but still available
// since some compilers may choke on '>>' when passing a template #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// instance (e.g. Types<int>) #define REGISTER_TYPED_TEST_CASE_P \
# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ ""); \
::testing::internal::TypeParameterizedTestCase<CaseName, \ REGISTER_TYPED_TEST_SUITE_P
GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
::testing::internal::TypeList< Types >::type>::Register(\
#Prefix, \ #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
::testing::internal::CodeLocation(__FILE__, __LINE__), \ static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
&GTEST_TYPED_TEST_CASE_P_STATE_(CaseName), \ ::testing::internal::TypeParameterizedTestSuite< \
#CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
::testing::internal::TypeList<Types>::type>:: \
Register(#Prefix, \
::testing::internal::CodeLocation(__FILE__, __LINE__), \
&GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \
GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
::testing::internal::GenerateNames< \
::testing::internal::NameGeneratorSelector< \
__VA_ARGS__>::type, \
::testing::internal::TypeList<Types>::type>())
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TYPED_TEST_CASE_P \
static_assert( \
::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
INSTANTIATE_TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_HAS_TYPED_TEST_P
......
...@@ -26,10 +26,9 @@ ...@@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: wan@google.com (Zhanyong Wan) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file defines the public API for Google Test. It should be // This header file defines the public API for Google Test. It should be
// included by any test program that uses Google Test. // included by any test program that uses Google Test.
...@@ -48,16 +47,22 @@ ...@@ -48,16 +47,22 @@
// registration from Barthelemy Dagenais' (barthelemy@prologique.com) // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework. // easyUnit framework.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
#include <limits> #include <limits>
#include <memory>
#include <ostream> #include <ostream>
#include <type_traits>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#include "gtest/gtest-death-test.h" #include "gtest/gtest-death-test.h"
#include "gtest/gtest-matchers.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest-param-test.h" #include "gtest/gtest-param-test.h"
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
...@@ -65,23 +70,20 @@ ...@@ -65,23 +70,20 @@
#include "gtest/gtest-test-part.h" #include "gtest/gtest-test-part.h"
#include "gtest/gtest-typed-test.h" #include "gtest/gtest-typed-test.h"
// Depending on the platform, different string classes are available. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
// On Linux, in addition to ::std::string, Google also makes use of /* class A needs to have dll-interface to be used by clients of class B */)
// class ::string, which has the same interface as ::std::string, but
// has a different implementation.
//
// You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
// ::string is available AND is a distinct type to ::std::string, or
// define it to 0 to indicate otherwise.
//
// If ::std::string and ::string are the same class on your platform
// due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
//
// If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
// heuristically.
namespace testing { namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4805)
# pragma warning(disable:4100)
#endif
// Declares the flags. // Declares the flags.
// This flag temporary enables the disabled tests. // This flag temporary enables the disabled tests.
...@@ -103,6 +105,10 @@ GTEST_DECLARE_string_(color); ...@@ -103,6 +105,10 @@ GTEST_DECLARE_string_(color);
// the tests to run. If the filter is not given all tests are executed. // the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter); GTEST_DECLARE_string_(filter);
// This flag controls whether Google Test installs a signal handler that dumps
// debugging information when fatal signals are raised.
GTEST_DECLARE_bool_(install_failure_signal_handler);
// This flag causes the Google Test to list tests. None of the tests listed // This flag causes the Google Test to list tests. None of the tests listed
// are actually run if the flag is provided. // are actually run if the flag is provided.
GTEST_DECLARE_bool_(list_tests); GTEST_DECLARE_bool_(list_tests);
...@@ -115,6 +121,9 @@ GTEST_DECLARE_string_(output); ...@@ -115,6 +121,9 @@ GTEST_DECLARE_string_(output);
// test. // test.
GTEST_DECLARE_bool_(print_time); GTEST_DECLARE_bool_(print_time);
// This flags control whether Google Test prints UTF8 characters as text.
GTEST_DECLARE_bool_(print_utf8);
// This flag specifies the random number seed. // This flag specifies the random number seed.
GTEST_DECLARE_int32_(random_seed); GTEST_DECLARE_int32_(random_seed);
...@@ -135,7 +144,7 @@ GTEST_DECLARE_int32_(stack_trace_depth); ...@@ -135,7 +144,7 @@ GTEST_DECLARE_int32_(stack_trace_depth);
// When this flag is specified, a failed assertion will throw an // When this flag is specified, a failed assertion will throw an
// exception if exceptions are enabled, or exit the program with a // exception if exceptions are enabled, or exit the program with a
// non-zero code otherwise. // non-zero code otherwise. For use with an external test framework.
GTEST_DECLARE_bool_(throw_on_failure); GTEST_DECLARE_bool_(throw_on_failure);
// When this flag is set with a "host:port" string, on supported // When this flag is set with a "host:port" string, on supported
...@@ -143,6 +152,10 @@ GTEST_DECLARE_bool_(throw_on_failure); ...@@ -143,6 +152,10 @@ GTEST_DECLARE_bool_(throw_on_failure);
// the specified host machine. // the specified host machine.
GTEST_DECLARE_string_(stream_result_to); GTEST_DECLARE_string_(stream_result_to);
#if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DECLARE_string_(flagfile);
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// The upper limit for valid stack trace depths. // The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100; const int kMaxStackTraceDepth = 100;
...@@ -160,6 +173,7 @@ class TestEventListenersAccessor; ...@@ -160,6 +173,7 @@ class TestEventListenersAccessor;
class TestEventRepeater; class TestEventRepeater;
class UnitTestRecordPropertyTestHelper; class UnitTestRecordPropertyTestHelper;
class WindowsDeathTest; class WindowsDeathTest;
class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl(); class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message); const std::string& message);
...@@ -170,7 +184,12 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type, ...@@ -170,7 +184,12 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
// If we don't forward declare them the compiler might confuse the classes // If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope. // in friendship clauses with same named classes on the scope.
class Test; class Test;
class TestCase; class TestSuite;
// Old API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
using TestCase = TestSuite;
#endif
class TestInfo; class TestInfo;
class UnitTest; class UnitTest;
...@@ -259,7 +278,9 @@ class GTEST_API_ AssertionResult { ...@@ -259,7 +278,9 @@ class GTEST_API_ AssertionResult {
// Used in EXPECT_TRUE/FALSE(assertion_result). // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult& other); AssertionResult(const AssertionResult& other);
#if defined(_MSC_VER) && _MSC_VER < 1910
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
#endif
// Used in the EXPECT_TRUE/FALSE(bool_expression). // Used in the EXPECT_TRUE/FALSE(bool_expression).
// //
...@@ -271,12 +292,15 @@ class GTEST_API_ AssertionResult { ...@@ -271,12 +292,15 @@ class GTEST_API_ AssertionResult {
template <typename T> template <typename T>
explicit AssertionResult( explicit AssertionResult(
const T& success, const T& success,
typename internal::EnableIf< typename std::enable_if<
!internal::ImplicitlyConvertible<T, AssertionResult>::value>::type* !std::is_convertible<T, AssertionResult>::value>::type*
/*enabler*/ = NULL) /*enabler*/
= nullptr)
: success_(success) {} : success_(success) {}
#if defined(_MSC_VER) && _MSC_VER < 1910
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif
// Assignment operator. // Assignment operator.
AssertionResult& operator=(AssertionResult other) { AssertionResult& operator=(AssertionResult other) {
...@@ -284,7 +308,7 @@ class GTEST_API_ AssertionResult { ...@@ -284,7 +308,7 @@ class GTEST_API_ AssertionResult {
return *this; return *this;
} }
// Returns true iff the assertion succeeded. // Returns true if and only if the assertion succeeded.
operator bool() const { return success_; } // NOLINT operator bool() const { return success_; } // NOLINT
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
...@@ -295,9 +319,8 @@ class GTEST_API_ AssertionResult { ...@@ -295,9 +319,8 @@ class GTEST_API_ AssertionResult {
// assertion's expectation). When nothing has been streamed into the // assertion's expectation). When nothing has been streamed into the
// object, returns an empty string. // object, returns an empty string.
const char* message() const { const char* message() const {
return message_.get() != NULL ? message_->c_str() : ""; return message_.get() != nullptr ? message_->c_str() : "";
} }
// TODO(vladl@google.com): Remove this after making sure no clients use it.
// Deprecated; please use message() instead. // Deprecated; please use message() instead.
const char* failure_message() const { return message(); } const char* failure_message() const { return message(); }
...@@ -318,8 +341,7 @@ class GTEST_API_ AssertionResult { ...@@ -318,8 +341,7 @@ class GTEST_API_ AssertionResult {
private: private:
// Appends the contents of message to message_. // Appends the contents of message to message_.
void AppendMessage(const Message& a_message) { void AppendMessage(const Message& a_message) {
if (message_.get() == NULL) if (message_.get() == nullptr) message_.reset(new ::std::string);
message_.reset(new ::std::string);
message_->append(a_message.GetString().c_str()); message_->append(a_message.GetString().c_str());
} }
...@@ -332,7 +354,7 @@ class GTEST_API_ AssertionResult { ...@@ -332,7 +354,7 @@ class GTEST_API_ AssertionResult {
// construct is not satisfied with the predicate's outcome. // construct is not satisfied with the predicate's outcome.
// Referenced via a pointer to avoid taking too much stack frame space // Referenced via a pointer to avoid taking too much stack frame space
// with test assertions. // with test assertions.
internal::scoped_ptr< ::std::string> message_; std::unique_ptr< ::std::string> message_;
}; };
// Makes a successful assertion result. // Makes a successful assertion result.
...@@ -345,17 +367,26 @@ GTEST_API_ AssertionResult AssertionFailure(); ...@@ -345,17 +367,26 @@ GTEST_API_ AssertionResult AssertionFailure();
// Deprecated; use AssertionFailure() << msg. // Deprecated; use AssertionFailure() << msg.
GTEST_API_ AssertionResult AssertionFailure(const Message& msg); GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
} // namespace testing
// Includes the auto-generated header that implements a family of generic
// predicate assertion macros. This include comes late because it relies on
// APIs declared above.
#include "gtest/gtest_pred_impl.h"
namespace testing {
// The abstract class that all tests inherit from. // The abstract class that all tests inherit from.
// //
// In Google Test, a unit test program contains one or many TestCases, and // In Google Test, a unit test program contains one or many TestSuites, and
// each TestCase contains one or many Tests. // each TestSuite contains one or many Tests.
// //
// When you define a test using the TEST macro, you don't need to // When you define a test using the TEST macro, you don't need to
// explicitly derive from Test - the TEST macro automatically does // explicitly derive from Test - the TEST macro automatically does
// this for you. // this for you.
// //
// The only time you derive from Test is when defining a test fixture // The only time you derive from Test is when defining a test fixture
// to be used a TEST_F. For example: // to be used in a TEST_F. For example:
// //
// class FooTest : public testing::Test { // class FooTest : public testing::Test {
// protected: // protected:
...@@ -372,49 +403,57 @@ class GTEST_API_ Test { ...@@ -372,49 +403,57 @@ class GTEST_API_ Test {
public: public:
friend class TestInfo; friend class TestInfo;
// Defines types for pointers to functions that set up and tear down
// a test case.
typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
// The d'tor is virtual as we intend to inherit from Test. // The d'tor is virtual as we intend to inherit from Test.
virtual ~Test(); virtual ~Test();
// Sets up the stuff shared by all tests in this test case. // Sets up the stuff shared by all tests in this test case.
// //
// Google Test will call Foo::SetUpTestCase() before running the first // Google Test will call Foo::SetUpTestSuite() before running the first
// test in test case Foo. Hence a sub-class can define its own // test in test case Foo. Hence a sub-class can define its own
// SetUpTestCase() method to shadow the one defined in the super // SetUpTestSuite() method to shadow the one defined in the super
// class. // class.
static void SetUpTestCase() {} // Failures that happen during SetUpTestSuite are logged but otherwise
// ignored.
static void SetUpTestSuite() {}
// Tears down the stuff shared by all tests in this test case. // Tears down the stuff shared by all tests in this test suite.
// //
// Google Test will call Foo::TearDownTestCase() after running the last // Google Test will call Foo::TearDownTestSuite() after running the last
// test in test case Foo. Hence a sub-class can define its own // test in test case Foo. Hence a sub-class can define its own
// TearDownTestCase() method to shadow the one defined in the super // TearDownTestSuite() method to shadow the one defined in the super
// class. // class.
// Failures that happen during TearDownTestSuite are logged but otherwise
// ignored.
static void TearDownTestSuite() {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
static void TearDownTestCase() {} static void TearDownTestCase() {}
static void SetUpTestCase() {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Returns true iff the current test has a fatal failure. // Returns true if and only if the current test has a fatal failure.
static bool HasFatalFailure(); static bool HasFatalFailure();
// Returns true iff the current test has a non-fatal failure. // Returns true if and only if the current test has a non-fatal failure.
static bool HasNonfatalFailure(); static bool HasNonfatalFailure();
// Returns true iff the current test has a (either fatal or // Returns true if and only if the current test was skipped.
static bool IsSkipped();
// Returns true if and only if the current test has a (either fatal or
// non-fatal) failure. // non-fatal) failure.
static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
// Logs a property for the current test, test case, or for the entire // Logs a property for the current test, test suite, or for the entire
// invocation of the test program when used outside of the context of a // invocation of the test program when used outside of the context of a
// test case. Only the last value for a given key is remembered. These // test suite. Only the last value for a given key is remembered. These
// are public static so they can be called from utility functions that are // are public static so they can be called from utility functions that are
// not members of the test fixture. Calls to RecordProperty made during // not members of the test fixture. Calls to RecordProperty made during
// lifespan of the test (from the moment its constructor starts to the // lifespan of the test (from the moment its constructor starts to the
// moment its destructor finishes) will be output in XML as attributes of // moment its destructor finishes) will be output in XML as attributes of
// the <testcase> element. Properties recorded from fixture's // the <testcase> element. Properties recorded from fixture's
// SetUpTestCase or TearDownTestCase are logged as attributes of the // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
// corresponding <testsuite> element. Calls to RecordProperty made in the // corresponding <testsuite> element. Calls to RecordProperty made in the
// global context (before or after invocation of RUN_ALL_TESTS and from // global context (before or after invocation of RUN_ALL_TESTS and from
// SetUp/TearDown method of Environment objects registered with Google // SetUp/TearDown method of Environment objects registered with Google
...@@ -433,8 +472,8 @@ class GTEST_API_ Test { ...@@ -433,8 +472,8 @@ class GTEST_API_ Test {
virtual void TearDown(); virtual void TearDown();
private: private:
// Returns true iff the current test has the same fixture class as // Returns true if and only if the current test has the same fixture class
// the first test in the current test case. // as the first test in the current test suite.
static bool HasSameFixtureClass(); static bool HasSameFixtureClass();
// Runs the test after the test fixture has been set up. // Runs the test after the test fixture has been set up.
...@@ -452,7 +491,7 @@ class GTEST_API_ Test { ...@@ -452,7 +491,7 @@ class GTEST_API_ Test {
// internal method to avoid clashing with names used in user TESTs. // internal method to avoid clashing with names used in user TESTs.
void DeleteSelf_() { delete this; } void DeleteSelf_() { delete this; }
const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
// Often a user misspells SetUp() as Setup() and spends a long time // Often a user misspells SetUp() as Setup() and spends a long time
// wondering why it is never called by Google Test. The declaration of // wondering why it is never called by Google Test. The declaration of
...@@ -471,7 +510,7 @@ class GTEST_API_ Test { ...@@ -471,7 +510,7 @@ class GTEST_API_ Test {
// If you see an error about overriding the following function or // If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup(). // about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {}; struct Setup_should_be_spelled_SetUp {};
virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
// We disallow copying Tests. // We disallow copying Tests.
GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
...@@ -535,24 +574,30 @@ class GTEST_API_ TestResult { ...@@ -535,24 +574,30 @@ class GTEST_API_ TestResult {
// Returns the number of the test properties. // Returns the number of the test properties.
int test_property_count() const; int test_property_count() const;
// Returns true iff the test passed (i.e. no test part failed). // Returns true if and only if the test passed (i.e. no test part failed).
bool Passed() const { return !Failed(); } bool Passed() const { return !Skipped() && !Failed(); }
// Returns true if and only if the test was skipped.
bool Skipped() const;
// Returns true iff the test failed. // Returns true if and only if the test failed.
bool Failed() const; bool Failed() const;
// Returns true iff the test fatally failed. // Returns true if and only if the test fatally failed.
bool HasFatalFailure() const; bool HasFatalFailure() const;
// Returns true iff the test has a non-fatal failure. // Returns true if and only if the test has a non-fatal failure.
bool HasNonfatalFailure() const; bool HasNonfatalFailure() const;
// Returns the elapsed time, in milliseconds. // Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; } TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns the i-th test part result among all the results. i can range // Gets the time of the test case start, in ms from the start of the
// from 0 to test_property_count() - 1. If i is not in that range, aborts // UNIX epoch.
// the program. TimeInMillis start_timestamp() const { return start_timestamp_; }
// Returns the i-th test part result among all the results. i can range from 0
// to total_part_count() - 1. If i is not in that range, aborts the program.
const TestPartResult& GetTestPartResult(int i) const; const TestPartResult& GetTestPartResult(int i) const;
// Returns the i-th test property. i can range from 0 to // Returns the i-th test property. i can range from 0 to
...@@ -562,13 +607,14 @@ class GTEST_API_ TestResult { ...@@ -562,13 +607,14 @@ class GTEST_API_ TestResult {
private: private:
friend class TestInfo; friend class TestInfo;
friend class TestCase; friend class TestSuite;
friend class UnitTest; friend class UnitTest;
friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::ExecDeathTest; friend class internal::ExecDeathTest;
friend class internal::TestResultAccessor; friend class internal::TestResultAccessor;
friend class internal::UnitTestImpl; friend class internal::UnitTestImpl;
friend class internal::WindowsDeathTest; friend class internal::WindowsDeathTest;
friend class internal::FuchsiaDeathTest;
// Gets the vector of TestPartResults. // Gets the vector of TestPartResults.
const std::vector<TestPartResult>& test_part_results() const { const std::vector<TestPartResult>& test_part_results() const {
...@@ -580,6 +626,9 @@ class GTEST_API_ TestResult { ...@@ -580,6 +626,9 @@ class GTEST_API_ TestResult {
return test_properties_; return test_properties_;
} }
// Sets the start time.
void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
// Sets the elapsed time. // Sets the elapsed time.
void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
...@@ -593,8 +642,8 @@ class GTEST_API_ TestResult { ...@@ -593,8 +642,8 @@ class GTEST_API_ TestResult {
const TestProperty& test_property); const TestProperty& test_property);
// Adds a failure if the key is a reserved attribute of Google Test // Adds a failure if the key is a reserved attribute of Google Test
// testcase tags. Returns true if the property is valid. // testsuite tags. Returns true if the property is valid.
// TODO(russr): Validate attribute names are legal and human readable. // FIXME: Validate attribute names are legal and human readable.
static bool ValidateTestProperty(const std::string& xml_element, static bool ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property); const TestProperty& test_property);
...@@ -623,6 +672,8 @@ class GTEST_API_ TestResult { ...@@ -623,6 +672,8 @@ class GTEST_API_ TestResult {
std::vector<TestProperty> test_properties_; std::vector<TestProperty> test_properties_;
// Running count of death tests. // Running count of death tests.
int death_test_count_; int death_test_count_;
// The start time, in milliseconds since UNIX Epoch.
TimeInMillis start_timestamp_;
// The elapsed time, in milliseconds. // The elapsed time, in milliseconds.
TimeInMillis elapsed_time_; TimeInMillis elapsed_time_;
...@@ -632,7 +683,7 @@ class GTEST_API_ TestResult { ...@@ -632,7 +683,7 @@ class GTEST_API_ TestResult {
// A TestInfo object stores the following information about a test: // A TestInfo object stores the following information about a test:
// //
// Test case name // Test suite name
// Test name // Test name
// Whether the test should be run // Whether the test should be run
// A function pointer that creates the test object when invoked // A function pointer that creates the test object when invoked
...@@ -647,8 +698,13 @@ class GTEST_API_ TestInfo { ...@@ -647,8 +698,13 @@ class GTEST_API_ TestInfo {
// don't inherit from TestInfo. // don't inherit from TestInfo.
~TestInfo(); ~TestInfo();
// Returns the test case name. // Returns the test suite name.
const char* test_case_name() const { return test_case_name_.c_str(); } const char* test_suite_name() const { return test_suite_name_.c_str(); }
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const char* test_case_name() const { return test_suite_name(); }
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Returns the test name. // Returns the test name.
const char* name() const { return name_.c_str(); } const char* name() const { return name_.c_str(); }
...@@ -656,17 +712,15 @@ class GTEST_API_ TestInfo { ...@@ -656,17 +712,15 @@ class GTEST_API_ TestInfo {
// Returns the name of the parameter type, or NULL if this is not a typed // Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test. // or a type-parameterized test.
const char* type_param() const { const char* type_param() const {
if (type_param_.get() != NULL) if (type_param_.get() != nullptr) return type_param_->c_str();
return type_param_->c_str(); return nullptr;
return NULL;
} }
// Returns the text representation of the value parameter, or NULL if this // Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test. // is not a value-parameterized test.
const char* value_param() const { const char* value_param() const {
if (value_param_.get() != NULL) if (value_param_.get() != nullptr) return value_param_->c_str();
return value_param_->c_str(); return nullptr;
return NULL;
} }
// Returns the file name where this test is defined. // Returns the file name where this test is defined.
...@@ -675,12 +729,15 @@ class GTEST_API_ TestInfo { ...@@ -675,12 +729,15 @@ class GTEST_API_ TestInfo {
// Returns the line where this test is defined. // Returns the line where this test is defined.
int line() const { return location_.line; } int line() const { return location_.line; }
// Return true if this test should not be run because it's in another shard.
bool is_in_another_shard() const { return is_in_another_shard_; }
// Returns true if this test should run, that is if the test is not // Returns true if this test should run, that is if the test is not
// disabled (or it is disabled but the also_run_disabled_tests flag has // disabled (or it is disabled but the also_run_disabled_tests flag has
// been specified) and its full name matches the user-specified filter. // been specified) and its full name matches the user-specified filter.
// //
// Google Test allows the user to filter the tests by their full names. // Google Test allows the user to filter the tests by their full names.
// The full name of a test Bar in test case Foo is defined as // The full name of a test Bar in test suite Foo is defined as
// "Foo.Bar". Only the tests that match the filter will run. // "Foo.Bar". Only the tests that match the filter will run.
// //
// A filter is a colon-separated list of glob (not regex) patterns, // A filter is a colon-separated list of glob (not regex) patterns,
...@@ -693,12 +750,11 @@ class GTEST_API_ TestInfo { ...@@ -693,12 +750,11 @@ class GTEST_API_ TestInfo {
// contains the character 'A' or starts with "Foo.". // contains the character 'A' or starts with "Foo.".
bool should_run() const { return should_run_; } bool should_run() const { return should_run_; }
// Returns true iff this test will appear in the XML report. // Returns true if and only if this test will appear in the XML report.
bool is_reportable() const { bool is_reportable() const {
// For now, the XML report includes all tests matching the filter. // The XML report includes tests matching the filter, excluding those
// In the future, we may trim tests that are excluded because of // run in other shards.
// sharding. return matches_filter_ && !is_in_another_shard_;
return matches_filter_;
} }
// Returns the result of the test. // Returns the result of the test.
...@@ -709,24 +765,19 @@ class GTEST_API_ TestInfo { ...@@ -709,24 +765,19 @@ class GTEST_API_ TestInfo {
friend class internal::DefaultDeathTestFactory; friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
friend class Test; friend class Test;
friend class TestCase; friend class TestSuite;
friend class internal::UnitTestImpl; friend class internal::UnitTestImpl;
friend class internal::StreamingListenerTest; friend class internal::StreamingListenerTest;
friend TestInfo* internal::MakeAndRegisterTestInfo( friend TestInfo* internal::MakeAndRegisterTestInfo(
const char* test_case_name, const char* test_suite_name, const char* name, const char* type_param,
const char* name, const char* value_param, internal::CodeLocation code_location,
const char* type_param, internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
const char* value_param, internal::TearDownTestSuiteFunc tear_down_tc,
internal::CodeLocation code_location,
internal::TypeId fixture_class_id,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc,
internal::TestFactoryBase* factory); internal::TestFactoryBase* factory);
// Constructs a TestInfo object. The newly constructed instance assumes // Constructs a TestInfo object. The newly constructed instance assumes
// ownership of the factory object. // ownership of the factory object.
TestInfo(const std::string& test_case_name, TestInfo(const std::string& test_suite_name, const std::string& name,
const std::string& name,
const char* a_type_param, // NULL if not a type-parameterized test const char* a_type_param, // NULL if not a type-parameterized test
const char* a_value_param, // NULL if not a value-parameterized test const char* a_value_param, // NULL if not a value-parameterized test
internal::CodeLocation a_code_location, internal::CodeLocation a_code_location,
...@@ -748,20 +799,21 @@ class GTEST_API_ TestInfo { ...@@ -748,20 +799,21 @@ class GTEST_API_ TestInfo {
} }
// These fields are immutable properties of the test. // These fields are immutable properties of the test.
const std::string test_case_name_; // Test case name const std::string test_suite_name_; // test suite name
const std::string name_; // Test name const std::string name_; // Test name
// Name of the parameter type, or NULL if this is not a typed or a // Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test. // type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_; const std::unique_ptr<const ::std::string> type_param_;
// Text representation of the value parameter, or NULL if this is not a // Text representation of the value parameter, or NULL if this is not a
// value-parameterized test. // value-parameterized test.
const internal::scoped_ptr<const ::std::string> value_param_; const std::unique_ptr<const ::std::string> value_param_;
internal::CodeLocation location_; internal::CodeLocation location_;
const internal::TypeId fixture_class_id_; // ID of the test fixture class const internal::TypeId fixture_class_id_; // ID of the test fixture class
bool should_run_; // True iff this test should run bool should_run_; // True if and only if this test should run
bool is_disabled_; // True iff this test is disabled bool is_disabled_; // True if and only if this test is disabled
bool matches_filter_; // True if this test matches the bool matches_filter_; // True if this test matches the
// user-specified filter. // user-specified filter.
bool is_in_another_shard_; // Will be run in another shard.
internal::TestFactoryBase* const factory_; // The factory that creates internal::TestFactoryBase* const factory_; // The factory that creates
// the test object // the test object
...@@ -772,90 +824,96 @@ class GTEST_API_ TestInfo { ...@@ -772,90 +824,96 @@ class GTEST_API_ TestInfo {
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
}; };
// A test case, which consists of a vector of TestInfos. // A test suite, which consists of a vector of TestInfos.
// //
// TestCase is not copyable. // TestSuite is not copyable.
class GTEST_API_ TestCase { class GTEST_API_ TestSuite {
public: public:
// Creates a TestCase with the given name. // Creates a TestSuite with the given name.
// //
// TestCase does NOT have a default constructor. Always use this // TestSuite does NOT have a default constructor. Always use this
// constructor to create a TestCase object. // constructor to create a TestSuite object.
// //
// Arguments: // Arguments:
// //
// name: name of the test case // name: name of the test suite
// a_type_param: the name of the test's type parameter, or NULL if // a_type_param: the name of the test's type parameter, or NULL if
// this is not a type-parameterized test. // this is not a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test case // set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test case // tear_down_tc: pointer to the function that tears down the test suite
TestCase(const char* name, const char* a_type_param, TestSuite(const char* name, const char* a_type_param,
Test::SetUpTestCaseFunc set_up_tc, internal::SetUpTestSuiteFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc); internal::TearDownTestSuiteFunc tear_down_tc);
// Destructor of TestCase. // Destructor of TestSuite.
virtual ~TestCase(); virtual ~TestSuite();
// Gets the name of the TestCase. // Gets the name of the TestSuite.
const char* name() const { return name_.c_str(); } const char* name() const { return name_.c_str(); }
// Returns the name of the parameter type, or NULL if this is not a // Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test case. // type-parameterized test suite.
const char* type_param() const { const char* type_param() const {
if (type_param_.get() != NULL) if (type_param_.get() != nullptr) return type_param_->c_str();
return type_param_->c_str(); return nullptr;
return NULL;
} }
// Returns true if any test in this test case should run. // Returns true if any test in this test suite should run.
bool should_run() const { return should_run_; } bool should_run() const { return should_run_; }
// Gets the number of successful tests in this test case. // Gets the number of successful tests in this test suite.
int successful_test_count() const; int successful_test_count() const;
// Gets the number of failed tests in this test case. // Gets the number of skipped tests in this test suite.
int skipped_test_count() const;
// Gets the number of failed tests in this test suite.
int failed_test_count() const; int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report. // Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const; int reportable_disabled_test_count() const;
// Gets the number of disabled tests in this test case. // Gets the number of disabled tests in this test suite.
int disabled_test_count() const; int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report. // Gets the number of tests to be printed in the XML report.
int reportable_test_count() const; int reportable_test_count() const;
// Get the number of tests in this test case that should run. // Get the number of tests in this test suite that should run.
int test_to_run_count() const; int test_to_run_count() const;
// Gets the number of all tests in this test case. // Gets the number of all tests in this test suite.
int total_test_count() const; int total_test_count() const;
// Returns true iff the test case passed. // Returns true if and only if the test suite passed.
bool Passed() const { return !Failed(); } bool Passed() const { return !Failed(); }
// Returns true iff the test case failed. // Returns true if and only if the test suite failed.
bool Failed() const { return failed_test_count() > 0; } bool Failed() const { return failed_test_count() > 0; }
// Returns the elapsed time, in milliseconds. // Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; } TimeInMillis elapsed_time() const { return elapsed_time_; }
// Gets the time of the test suite start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
// Returns the i-th test among all the tests. i can range from 0 to // Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL. // total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* GetTestInfo(int i) const; const TestInfo* GetTestInfo(int i) const;
// Returns the TestResult that holds test properties recorded during // Returns the TestResult that holds test properties recorded during
// execution of SetUpTestCase and TearDownTestCase. // execution of SetUpTestSuite and TearDownTestSuite.
const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
private: private:
friend class Test; friend class Test;
friend class internal::UnitTestImpl; friend class internal::UnitTestImpl;
// Gets the (mutable) vector of TestInfos in this TestCase. // Gets the (mutable) vector of TestInfos in this TestSuite.
std::vector<TestInfo*>& test_info_list() { return test_info_list_; } std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
// Gets the (immutable) vector of TestInfos in this TestCase. // Gets the (immutable) vector of TestInfos in this TestSuite.
const std::vector<TestInfo*>& test_info_list() const { const std::vector<TestInfo*>& test_info_list() const {
return test_info_list_; return test_info_list_;
} }
...@@ -867,51 +925,64 @@ class GTEST_API_ TestCase { ...@@ -867,51 +925,64 @@ class GTEST_API_ TestCase {
// Sets the should_run member. // Sets the should_run member.
void set_should_run(bool should) { should_run_ = should; } void set_should_run(bool should) { should_run_ = should; }
// Adds a TestInfo to this test case. Will delete the TestInfo upon // Adds a TestInfo to this test suite. Will delete the TestInfo upon
// destruction of the TestCase object. // destruction of the TestSuite object.
void AddTestInfo(TestInfo * test_info); void AddTestInfo(TestInfo * test_info);
// Clears the results of all tests in this test case. // Clears the results of all tests in this test suite.
void ClearResult(); void ClearResult();
// Clears the results of all tests in the given test case. // Clears the results of all tests in the given test suite.
static void ClearTestCaseResult(TestCase* test_case) { static void ClearTestSuiteResult(TestSuite* test_suite) {
test_case->ClearResult(); test_suite->ClearResult();
} }
// Runs every test in this TestCase. // Runs every test in this TestSuite.
void Run(); void Run();
// Runs SetUpTestCase() for this TestCase. This wrapper is needed // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
// for catching exceptions thrown from SetUpTestCase(). // for catching exceptions thrown from SetUpTestSuite().
void RunSetUpTestCase() { (*set_up_tc_)(); } void RunSetUpTestSuite() {
if (set_up_tc_ != nullptr) {
(*set_up_tc_)();
}
}
// Runs TearDownTestCase() for this TestCase. This wrapper is // Runs TearDownTestSuite() for this TestSuite. This wrapper is
// needed for catching exceptions thrown from TearDownTestCase(). // needed for catching exceptions thrown from TearDownTestSuite().
void RunTearDownTestCase() { (*tear_down_tc_)(); } void RunTearDownTestSuite() {
if (tear_down_tc_ != nullptr) {
(*tear_down_tc_)();
}
}
// Returns true iff test passed. // Returns true if and only if test passed.
static bool TestPassed(const TestInfo* test_info) { static bool TestPassed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Passed(); return test_info->should_run() && test_info->result()->Passed();
} }
// Returns true iff test failed. // Returns true if and only if test skipped.
static bool TestSkipped(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Skipped();
}
// Returns true if and only if test failed.
static bool TestFailed(const TestInfo* test_info) { static bool TestFailed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Failed(); return test_info->should_run() && test_info->result()->Failed();
} }
// Returns true iff the test is disabled and will be reported in the XML // Returns true if and only if the test is disabled and will be reported in
// report. // the XML report.
static bool TestReportableDisabled(const TestInfo* test_info) { static bool TestReportableDisabled(const TestInfo* test_info) {
return test_info->is_reportable() && test_info->is_disabled_; return test_info->is_reportable() && test_info->is_disabled_;
} }
// Returns true iff test is disabled. // Returns true if and only if test is disabled.
static bool TestDisabled(const TestInfo* test_info) { static bool TestDisabled(const TestInfo* test_info) {
return test_info->is_disabled_; return test_info->is_disabled_;
} }
// Returns true iff this test will appear in the XML report. // Returns true if and only if this test will appear in the XML report.
static bool TestReportable(const TestInfo* test_info) { static bool TestReportable(const TestInfo* test_info) {
return test_info->is_reportable(); return test_info->is_reportable();
} }
...@@ -921,17 +992,17 @@ class GTEST_API_ TestCase { ...@@ -921,17 +992,17 @@ class GTEST_API_ TestCase {
return test_info->should_run(); return test_info->should_run();
} }
// Shuffles the tests in this test case. // Shuffles the tests in this test suite.
void ShuffleTests(internal::Random* random); void ShuffleTests(internal::Random* random);
// Restores the test order to before the first shuffle. // Restores the test order to before the first shuffle.
void UnshuffleTests(); void UnshuffleTests();
// Name of the test case. // Name of the test suite.
std::string name_; std::string name_;
// Name of the parameter type, or NULL if this is not a typed or a // Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test. // type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_; const std::unique_ptr<const ::std::string> type_param_;
// The vector of TestInfos in their original order. It owns the // The vector of TestInfos in their original order. It owns the
// elements in the vector. // elements in the vector.
std::vector<TestInfo*> test_info_list_; std::vector<TestInfo*> test_info_list_;
...@@ -939,20 +1010,22 @@ class GTEST_API_ TestCase { ...@@ -939,20 +1010,22 @@ class GTEST_API_ TestCase {
// shuffling and restoring the test order. The i-th element in this // shuffling and restoring the test order. The i-th element in this
// vector is the index of the i-th test in the shuffled test list. // vector is the index of the i-th test in the shuffled test list.
std::vector<int> test_indices_; std::vector<int> test_indices_;
// Pointer to the function that sets up the test case. // Pointer to the function that sets up the test suite.
Test::SetUpTestCaseFunc set_up_tc_; internal::SetUpTestSuiteFunc set_up_tc_;
// Pointer to the function that tears down the test case. // Pointer to the function that tears down the test suite.
Test::TearDownTestCaseFunc tear_down_tc_; internal::TearDownTestSuiteFunc tear_down_tc_;
// True iff any test in this test case should run. // True if and only if any test in this test suite should run.
bool should_run_; bool should_run_;
// The start time, in milliseconds since UNIX Epoch.
TimeInMillis start_timestamp_;
// Elapsed time, in milliseconds. // Elapsed time, in milliseconds.
TimeInMillis elapsed_time_; TimeInMillis elapsed_time_;
// Holds test properties recorded during execution of SetUpTestCase and // Holds test properties recorded during execution of SetUpTestSuite and
// TearDownTestCase. // TearDownTestSuite.
TestResult ad_hoc_test_result_; TestResult ad_hoc_test_result_;
// We disallow copying TestCases. // We disallow copying TestSuites.
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
}; };
// An Environment object is capable of setting up and tearing down an // An Environment object is capable of setting up and tearing down an
...@@ -983,9 +1056,21 @@ class Environment { ...@@ -983,9 +1056,21 @@ class Environment {
// If you see an error about overriding the following function or // If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup(). // about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {}; struct Setup_should_be_spelled_SetUp {};
virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
}; };
#if GTEST_HAS_EXCEPTIONS
// Exception which can be thrown from TestEventListener::OnTestPartResult.
class GTEST_API_ AssertionException
: public internal::GoogleTestFailureException {
public:
explicit AssertionException(const TestPartResult& result)
: GoogleTestFailureException(result) {}
};
#endif // GTEST_HAS_EXCEPTIONS
// The interface for tracing execution of tests. The methods are organized in // The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired. // the order the corresponding events are fired.
class TestEventListener { class TestEventListener {
...@@ -1007,20 +1092,32 @@ class TestEventListener { ...@@ -1007,20 +1092,32 @@ class TestEventListener {
// Fired after environment set-up for each iteration of tests ends. // Fired after environment set-up for each iteration of tests ends.
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
// Fired before the test case starts. // Fired before the test suite starts.
virtual void OnTestCaseStart(const TestCase& test_case) = 0; virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Fired before the test starts. // Fired before the test starts.
virtual void OnTestStart(const TestInfo& test_info) = 0; virtual void OnTestStart(const TestInfo& test_info) = 0;
// Fired after a failed assertion or a SUCCEED() invocation. // Fired after a failed assertion or a SUCCEED() invocation.
// If you want to throw an exception from this function to skip to the next
// TEST, it must be AssertionException defined above, or inherited from it.
virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
// Fired after the test ends. // Fired after the test ends.
virtual void OnTestEnd(const TestInfo& test_info) = 0; virtual void OnTestEnd(const TestInfo& test_info) = 0;
// Fired after the test case ends. // Fired after the test suite ends.
virtual void OnTestCaseEnd(const TestCase& test_case) = 0; virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Fired before environment tear-down for each iteration of tests starts. // Fired before environment tear-down for each iteration of tests starts.
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
...@@ -1043,21 +1140,30 @@ class TestEventListener { ...@@ -1043,21 +1140,30 @@ class TestEventListener {
// above. // above.
class EmptyTestEventListener : public TestEventListener { class EmptyTestEventListener : public TestEventListener {
public: public:
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, void OnTestIterationStart(const UnitTest& /*unit_test*/,
int /*iteration*/) {} int /*iteration*/) override {}
virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
virtual void OnTestStart(const TestInfo& /*test_info*/) {} // Legacy API is deprecated but still available
virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnTestEnd(const TestInfo& /*test_info*/) {} void OnTestCaseStart(const TestCase& /*test_case*/) override {}
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} void OnTestStart(const TestInfo& /*test_info*/) override {}
virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
int /*iteration*/) {} void OnTestEnd(const TestInfo& /*test_info*/) override {}
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int /*iteration*/) override {}
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
}; };
// TestEventListeners lets users add listeners to track events in Google Test. // TestEventListeners lets users add listeners to track events in Google Test.
...@@ -1097,7 +1203,7 @@ class GTEST_API_ TestEventListeners { ...@@ -1097,7 +1203,7 @@ class GTEST_API_ TestEventListeners {
} }
private: private:
friend class TestCase; friend class TestSuite;
friend class TestInfo; friend class TestInfo;
friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::NoExecDeathTest; friend class internal::NoExecDeathTest;
...@@ -1138,7 +1244,7 @@ class GTEST_API_ TestEventListeners { ...@@ -1138,7 +1244,7 @@ class GTEST_API_ TestEventListeners {
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
}; };
// A UnitTest consists of a vector of TestCases. // A UnitTest consists of a vector of TestSuites.
// //
// This is a singleton class. The only instance of UnitTest is // This is a singleton class. The only instance of UnitTest is
// created when UnitTest::GetInstance() is first called. This // created when UnitTest::GetInstance() is first called. This
...@@ -1167,10 +1273,14 @@ class GTEST_API_ UnitTest { ...@@ -1167,10 +1273,14 @@ class GTEST_API_ UnitTest {
// was executed. The UnitTest object owns the string. // was executed. The UnitTest object owns the string.
const char* original_working_dir() const; const char* original_working_dir() const;
// Returns the TestCase object for the test that's currently running, // Returns the TestSuite object for the test that's currently running,
// or NULL if no test is running. // or NULL if no test is running.
const TestCase* current_test_case() const const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
GTEST_LOCK_EXCLUDED_(mutex_);
// Legacy API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
#endif
// Returns the TestInfo object for the test that's currently running, // Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running. // or NULL if no test is running.
...@@ -1180,31 +1290,40 @@ class GTEST_API_ UnitTest { ...@@ -1180,31 +1290,40 @@ class GTEST_API_ UnitTest {
// Returns the random seed used at the start of the current test run. // Returns the random seed used at the start of the current test run.
int random_seed() const; int random_seed() const;
#if GTEST_HAS_PARAM_TEST // Returns the ParameterizedTestSuiteRegistry object used to keep track of
// Returns the ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them. // value-parameterized tests and instantiate and register them.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::ParameterizedTestCaseRegistry& parameterized_test_registry() internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
#endif // GTEST_HAS_PARAM_TEST
// Gets the number of successful test cases. // Gets the number of successful test suites.
int successful_test_case_count() const; int successful_test_suite_count() const;
// Gets the number of failed test cases. // Gets the number of failed test suites.
int failed_test_case_count() const; int failed_test_suite_count() const;
// Gets the number of all test cases. // Gets the number of all test suites.
int total_test_case_count() const; int total_test_suite_count() const;
// Gets the number of all test cases that contain at least one test // Gets the number of all test suites that contain at least one test
// that should run. // that should run.
int test_suite_to_run_count() const;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
int successful_test_case_count() const;
int failed_test_case_count() const;
int total_test_case_count() const;
int test_case_to_run_count() const; int test_case_to_run_count() const;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Gets the number of successful tests. // Gets the number of successful tests.
int successful_test_count() const; int successful_test_count() const;
// Gets the number of skipped tests.
int skipped_test_count() const;
// Gets the number of failed tests. // Gets the number of failed tests.
int failed_test_count() const; int failed_test_count() const;
...@@ -1230,19 +1349,25 @@ class GTEST_API_ UnitTest { ...@@ -1230,19 +1349,25 @@ class GTEST_API_ UnitTest {
// Gets the elapsed time, in milliseconds. // Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const; TimeInMillis elapsed_time() const;
// Returns true iff the unit test passed (i.e. all test cases passed). // Returns true if and only if the unit test passed (i.e. all test suites
// passed).
bool Passed() const; bool Passed() const;
// Returns true iff the unit test failed (i.e. some test case failed // Returns true if and only if the unit test failed (i.e. some test suite
// or something outside of all tests failed). // failed or something outside of all tests failed).
bool Failed() const; bool Failed() const;
// Gets the i-th test case among all the test cases. i can range from 0 to // Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
const TestSuite* GetTestSuite(int i) const;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* GetTestCase(int i) const; const TestCase* GetTestCase(int i) const;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Returns the TestResult containing information on test failures and // Returns the TestResult containing information on test failures and
// properties logged outside of individual test cases. // properties logged outside of individual test suites.
const TestResult& ad_hoc_test_result() const; const TestResult& ad_hoc_test_result() const;
// Returns the list of event listeners that can be used to track events // Returns the list of event listeners that can be used to track events
...@@ -1273,25 +1398,25 @@ class GTEST_API_ UnitTest { ...@@ -1273,25 +1398,25 @@ class GTEST_API_ UnitTest {
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
// Adds a TestProperty to the current TestResult object when invoked from // Adds a TestProperty to the current TestResult object when invoked from
// inside a test, to current TestCase's ad_hoc_test_result_ when invoked // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
// from SetUpTestCase or TearDownTestCase, or to the global property set // from SetUpTestSuite or TearDownTestSuite, or to the global property set
// when invoked elsewhere. If the result already contains a property with // when invoked elsewhere. If the result already contains a property with
// the same key, the value will be updated. // the same key, the value will be updated.
void RecordProperty(const std::string& key, const std::string& value); void RecordProperty(const std::string& key, const std::string& value);
// Gets the i-th test case among all the test cases. i can range from 0 to // Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
TestCase* GetMutableTestCase(int i); TestSuite* GetMutableTestSuite(int i);
// Accessors for the implementation object. // Accessors for the implementation object.
internal::UnitTestImpl* impl() { return impl_; } internal::UnitTestImpl* impl() { return impl_; }
const internal::UnitTestImpl* impl() const { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; }
// These classes and funcions are friends as they need to access private // These classes and functions are friends as they need to access private
// members of UnitTest. // members of UnitTest.
friend class ScopedTrace;
friend class Test; friend class Test;
friend class internal::AssertHelper; friend class internal::AssertHelper;
friend class internal::ScopedTrace;
friend class internal::StreamingListenerTest; friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper; friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env); friend Environment* AddGlobalTestEnvironment(Environment* env);
...@@ -1366,6 +1491,10 @@ GTEST_API_ void InitGoogleTest(int* argc, char** argv); ...@@ -1366,6 +1491,10 @@ GTEST_API_ void InitGoogleTest(int* argc, char** argv);
// UNICODE mode. // UNICODE mode.
GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
GTEST_API_ void InitGoogleTest();
namespace internal { namespace internal {
// Separate the error generating code from the code path to reduce the stack // Separate the error generating code from the code path to reduce the stack
...@@ -1382,17 +1511,22 @@ AssertionResult CmpHelperEQFailure(const char* lhs_expression, ...@@ -1382,17 +1511,22 @@ AssertionResult CmpHelperEQFailure(const char* lhs_expression,
false); false);
} }
// This block of code defines operator==/!=
// to block lexical scope lookup.
// It prevents using invalid operator==/!= defined at namespace scope.
struct faketype {};
inline bool operator==(faketype, faketype) { return true; }
inline bool operator!=(faketype, faketype) { return false; }
// The helper function for {ASSERT|EXPECT}_EQ. // The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2> template <typename T1, typename T2>
AssertionResult CmpHelperEQ(const char* lhs_expression, AssertionResult CmpHelperEQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression,
const T1& lhs, const T1& lhs,
const T2& rhs) { const T2& rhs) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */)
if (lhs == rhs) { if (lhs == rhs) {
return AssertionSuccess(); return AssertionSuccess();
} }
GTEST_DISABLE_MSC_WARNINGS_POP_()
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
} }
...@@ -1405,18 +1539,17 @@ GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, ...@@ -1405,18 +1539,17 @@ GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
BiggestInt lhs, BiggestInt lhs,
BiggestInt rhs); BiggestInt rhs);
// The helper class for {ASSERT|EXPECT}_EQ. The template argument
// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
// is a null pointer literal. The following default implementation is
// for lhs_is_null_literal being false.
template <bool lhs_is_null_literal>
class EqHelper { class EqHelper {
public: public:
// This templatized version is for the general case. // This templatized version is for the general case.
template <typename T1, typename T2> template <
typename T1, typename T2,
// Disable this overload for cases where one argument is a pointer
// and the other is the null pointer constant.
typename std::enable_if<!std::is_integral<T1>::value ||
!std::is_pointer<T2>::value>::type* = nullptr>
static AssertionResult Compare(const char* lhs_expression, static AssertionResult Compare(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const T1& lhs,
const T1& lhs,
const T2& rhs) { const T2& rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
} }
...@@ -1433,49 +1566,15 @@ class EqHelper { ...@@ -1433,49 +1566,15 @@ class EqHelper {
BiggestInt rhs) { BiggestInt rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
} }
};
// This specialization is used when the first argument to ASSERT_EQ()
// is a null pointer literal, like NULL, false, or 0.
template <>
class EqHelper<true> {
public:
// We define two overloaded versions of Compare(). The first
// version will be picked when the second argument to ASSERT_EQ() is
// NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
// EXPECT_EQ(false, a_bool).
template <typename T1, typename T2>
static AssertionResult Compare(
const char* lhs_expression,
const char* rhs_expression,
const T1& lhs,
const T2& rhs,
// The following line prevents this overload from being considered if T2
// is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr)
// expands to Compare("", "", NULL, my_ptr), which requires a conversion
// to match the Secret* in the other overload, which would otherwise make
// this template match better.
typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
}
// This version will be picked when the second argument to ASSERT_EQ() is a
// pointer, e.g. ASSERT_EQ(NULL, a_pointer).
template <typename T> template <typename T>
static AssertionResult Compare( static AssertionResult Compare(
const char* lhs_expression, const char* lhs_expression, const char* rhs_expression,
const char* rhs_expression, // Handle cases where '0' is used as a null pointer literal.
// We used to have a second template parameter instead of Secret*. That std::nullptr_t /* lhs */, T* rhs) {
// template parameter would deduce to 'long', making this a better match
// than the first overload even without the first overload's EnableIf.
// Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
// non-pointer argument" (even a deduced integral argument), so the old
// implementation caused warnings in user code.
Secret* /* lhs (NULL) */,
T* rhs) {
// We already know that 'lhs' is a null pointer. // We already know that 'lhs' is a null pointer.
return CmpHelperEQ(lhs_expression, rhs_expression, return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
static_cast<T*>(NULL), rhs); rhs);
} }
}; };
...@@ -1704,9 +1803,14 @@ class GTEST_API_ AssertHelper { ...@@ -1704,9 +1803,14 @@ class GTEST_API_ AssertHelper {
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
}; };
enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
const char* fmt,
...);
} // namespace internal } // namespace internal
#if GTEST_HAS_PARAM_TEST
// The pure interface class that all value-parameterized tests inherit from. // The pure interface class that all value-parameterized tests inherit from.
// A value-parameterized class must inherit from both ::testing::Test and // A value-parameterized class must inherit from both ::testing::Test and
// ::testing::WithParamInterface. In most cases that just means inheriting // ::testing::WithParamInterface. In most cases that just means inheriting
...@@ -1724,13 +1828,13 @@ class GTEST_API_ AssertHelper { ...@@ -1724,13 +1828,13 @@ class GTEST_API_ AssertHelper {
// FooTest() { // FooTest() {
// // Can use GetParam() here. // // Can use GetParam() here.
// } // }
// virtual ~FooTest() { // ~FooTest() override {
// // Can use GetParam() here. // // Can use GetParam() here.
// } // }
// virtual void SetUp() { // void SetUp() override {
// // Can use GetParam() here. // // Can use GetParam() here.
// } // }
// virtual void TearDown { // void TearDown override {
// // Can use GetParam() here. // // Can use GetParam() here.
// } // }
// }; // };
...@@ -1739,7 +1843,7 @@ class GTEST_API_ AssertHelper { ...@@ -1739,7 +1843,7 @@ class GTEST_API_ AssertHelper {
// Foo foo; // Foo foo;
// ASSERT_TRUE(foo.DoesBar(GetParam())); // ASSERT_TRUE(foo.DoesBar(GetParam()));
// } // }
// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
template <typename T> template <typename T>
class WithParamInterface { class WithParamInterface {
...@@ -1748,12 +1852,9 @@ class WithParamInterface { ...@@ -1748,12 +1852,9 @@ class WithParamInterface {
virtual ~WithParamInterface() {} virtual ~WithParamInterface() {}
// The current parameter value. Is also available in the test fixture's // The current parameter value. Is also available in the test fixture's
// constructor. This member function is non-static, even though it only // constructor.
// references static data, to reduce the opportunity for incorrect uses static const ParamType& GetParam() {
// like writing 'WithParamInterface<bool>::GetParam()' for a test that GTEST_CHECK_(parameter_ != nullptr)
// uses a fixture whose parameter type is int.
const ParamType& GetParam() const {
GTEST_CHECK_(parameter_ != NULL)
<< "GetParam() can only be called inside a value-parameterized test " << "GetParam() can only be called inside a value-parameterized test "
<< "-- did you intend to write TEST_P instead of TEST_F?"; << "-- did you intend to write TEST_P instead of TEST_F?";
return *parameter_; return *parameter_;
...@@ -1774,7 +1875,7 @@ class WithParamInterface { ...@@ -1774,7 +1875,7 @@ class WithParamInterface {
}; };
template <typename T> template <typename T>
const T* WithParamInterface<T>::parameter_ = NULL; const T* WithParamInterface<T>::parameter_ = nullptr;
// Most value-parameterized classes can ignore the existence of // Most value-parameterized classes can ignore the existence of
// WithParamInterface, and can just inherit from ::testing::TestWithParam. // WithParamInterface, and can just inherit from ::testing::TestWithParam.
...@@ -1783,10 +1884,13 @@ template <typename T> ...@@ -1783,10 +1884,13 @@ template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> { class TestWithParam : public Test, public WithParamInterface<T> {
}; };
#endif // GTEST_HAS_PARAM_TEST
// Macros for indicating success/failure in test code. // Macros for indicating success/failure in test code.
// Skips test in runtime.
// Skipping test aborts current function.
// Skipped tests are neither successful nor failed.
#define GTEST_SKIP() GTEST_SKIP_("Skipped")
// ADD_FAILURE unconditionally adds a failure to the current test. // ADD_FAILURE unconditionally adds a failure to the current test.
// SUCCEED generates a success - it doesn't automatically make the // SUCCEED generates a success - it doesn't automatically make the
// current test successful, as a test is only successful when it has // current test successful, as a test is only successful when it has
...@@ -1816,6 +1920,11 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1816,6 +1920,11 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// Generates a fatal failure with a generic message. // Generates a fatal failure with a generic message.
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Like GTEST_FAIL(), but at the given source file location.
#define GTEST_FAIL_AT(file, line) \
GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
// Define this macro to 1 to omit the definition of FAIL(), which is a // Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries. // generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_FAIL #if !GTEST_DONT_DEFINE_FAIL
...@@ -1857,22 +1966,18 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1857,22 +1966,18 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// AssertionResult. For more information on how to use AssertionResult with // AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class. // these macros see comments on that class.
#define EXPECT_TRUE(condition) \ #define EXPECT_TRUE(condition) \
GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_) GTEST_NONFATAL_FAILURE_)
#define EXPECT_FALSE(condition) \ #define EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_) GTEST_NONFATAL_FAILURE_)
#define ASSERT_TRUE(condition) \ #define ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_FATAL_FAILURE_) GTEST_FATAL_FAILURE_)
#define ASSERT_FALSE(condition) \ #define ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_) GTEST_FATAL_FAILURE_)
// Includes the auto-generated header that implements a family of
// generic predicate assertion macros.
#include "gtest/gtest_pred_impl.h"
// Macros for testing equalities and inequalities. // Macros for testing equalities and inequalities.
// //
// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
...@@ -1914,15 +2019,13 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1914,15 +2019,13 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// //
// Examples: // Examples:
// //
// EXPECT_NE(5, Foo()); // EXPECT_NE(Foo(), 5);
// EXPECT_EQ(NULL, a_pointer); // EXPECT_EQ(a_pointer, NULL);
// ASSERT_LT(i, array_size); // ASSERT_LT(i, array_size);
// ASSERT_GT(records.size(), 0) << "There is no record left."; // ASSERT_GT(records.size(), 0) << "There is no record left.";
#define EXPECT_EQ(val1, val2) \ #define EXPECT_EQ(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal:: \ EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
val1, val2)
#define EXPECT_NE(val1, val2) \ #define EXPECT_NE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
#define EXPECT_LE(val1, val2) \ #define EXPECT_LE(val1, val2) \
...@@ -1935,9 +2038,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1935,9 +2038,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
#define GTEST_ASSERT_EQ(val1, val2) \ #define GTEST_ASSERT_EQ(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal:: \ ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
val1, val2)
#define GTEST_ASSERT_NE(val1, val2) \ #define GTEST_ASSERT_NE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
#define GTEST_ASSERT_LE(val1, val2) \ #define GTEST_ASSERT_LE(val1, val2) \
...@@ -2101,6 +2202,51 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ...@@ -2101,6 +2202,51 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
#define EXPECT_NO_FATAL_FAILURE(statement) \ #define EXPECT_NO_FATAL_FAILURE(statement) \
GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
// Causes a trace (including the given source file path and line number,
// and the given message) to be included in every test failure message generated
// by code in the scope of the lifetime of an instance of this class. The effect
// is undone with the destruction of the instance.
//
// The message argument can be anything streamable to std::ostream.
//
// Example:
// testing::ScopedTrace trace("file.cc", 123, "message");
//
class GTEST_API_ ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
// Template version. Uses Message() to convert the values into strings.
// Slow, but flexible.
template <typename T>
ScopedTrace(const char* file, int line, const T& message) {
PushTrace(file, line, (Message() << message).GetString());
}
// Optimize for some known types.
ScopedTrace(const char* file, int line, const char* message) {
PushTrace(file, line, message ? message : "(null)");
}
ScopedTrace(const char* file, int line, const std::string& message) {
PushTrace(file, line, message);
}
// The d'tor pops the info pushed by the c'tor.
//
// Note that the d'tor is not virtual in order to be efficient.
// Don't inherit from ScopedTrace!
~ScopedTrace();
private:
void PushTrace(const char* file, int line, std::string message);
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
// c'tor and d'tor. Therefore it doesn't
// need to be used otherwise.
// Causes a trace (including the source file path, the current line // Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure // number, and the given message) to be included in every test failure
// message generated by code in the current scope. The effect is // message generated by code in the current scope. The effect is
...@@ -2112,13 +2258,17 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ...@@ -2112,13 +2258,17 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
// to appear in the same block - as long as they are on different // to appear in the same block - as long as they are on different
// lines. // lines.
//
// Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
#define SCOPED_TRACE(message) \ #define SCOPED_TRACE(message) \
::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
__FILE__, __LINE__, ::testing::Message() << (message)) __FILE__, __LINE__, (message))
// Compile-time assertion for type equality. // Compile-time assertion for type equality.
// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
// the same type. The value it returns is not interesting. // are the same type. The value it returns is not interesting.
// //
// Instead of making StaticAssertTypeEq a class template, we make it a // Instead of making StaticAssertTypeEq a class template, we make it a
// function template that invokes a helper class template. This // function template that invokes a helper class template. This
...@@ -2147,18 +2297,19 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ...@@ -2147,18 +2297,19 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
// //
// to cause a compiler error. // to cause a compiler error.
template <typename T1, typename T2> template <typename T1, typename T2>
bool StaticAssertTypeEq() { constexpr bool StaticAssertTypeEq() noexcept {
(void)internal::StaticAssertTypeEqHelper<T1, T2>(); static_assert(std::is_same<T1, T2>::value,
"type1 and type2 are not the same type");
return true; return true;
} }
// Defines a test. // Defines a test.
// //
// The first parameter is the name of the test case, and the second // The first parameter is the name of the test suite, and the second
// parameter is the name of the test within the test case. // parameter is the name of the test within the test suite.
// //
// The convention is to end the test case name with "Test". For // The convention is to end the test suite name with "Test". For
// example, a test case for the Foo class can be named FooTest. // example, a test suite for the Foo class can be named FooTest.
// //
// Test code should appear between braces after an invocation of // Test code should appear between braces after an invocation of
// this macro. Example: // this macro. Example:
...@@ -2177,28 +2328,28 @@ bool StaticAssertTypeEq() { ...@@ -2177,28 +2328,28 @@ bool StaticAssertTypeEq() {
// code. GetTestTypeId() is guaranteed to always return the same // code. GetTestTypeId() is guaranteed to always return the same
// value, as it always calls GetTypeId<>() from the Google Test // value, as it always calls GetTypeId<>() from the Google Test
// framework. // framework.
#define GTEST_TEST(test_case_name, test_name)\ #define GTEST_TEST(test_suite_name, test_name) \
GTEST_TEST_(test_case_name, test_name, \ GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
::testing::Test, ::testing::internal::GetTestTypeId()) ::testing::internal::GetTestTypeId())
// Define this macro to 1 to omit the definition of TEST(), which // Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries. // is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_TEST #if !GTEST_DONT_DEFINE_TEST
# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif #endif
// Defines a test that uses a test fixture. // Defines a test that uses a test fixture.
// //
// The first parameter is the name of the test fixture class, which // The first parameter is the name of the test fixture class, which
// also doubles as the test case name. The second parameter is the // also doubles as the test suite name. The second parameter is the
// name of the test within the test case. // name of the test within the test suite.
// //
// A test fixture class must be declared earlier. The user should put // A test fixture class must be declared earlier. The user should put
// his test code between braces after using this macro. Example: // the test code between braces after using this macro. Example:
// //
// class FooTest : public testing::Test { // class FooTest : public testing::Test {
// protected: // protected:
// virtual void SetUp() { b_.AddElement(3); } // void SetUp() override { b_.AddElement(3); }
// //
// Foo a_; // Foo a_;
// Foo b_; // Foo b_;
...@@ -2209,14 +2360,103 @@ bool StaticAssertTypeEq() { ...@@ -2209,14 +2360,103 @@ bool StaticAssertTypeEq() {
// } // }
// //
// TEST_F(FooTest, ReturnsElementCountCorrectly) { // TEST_F(FooTest, ReturnsElementCountCorrectly) {
// EXPECT_EQ(0, a_.size()); // EXPECT_EQ(a_.size(), 0);
// EXPECT_EQ(1, b_.size()); // EXPECT_EQ(b_.size(), 1);
// } // }
//
// GOOGLETEST_CM0011 DO NOT DELETE
#define TEST_F(test_fixture, test_name)\ #define TEST_F(test_fixture, test_name)\
GTEST_TEST_(test_fixture, test_name, test_fixture, \ GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>()) ::testing::internal::GetTypeId<test_fixture>())
// Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform.
GTEST_API_ std::string TempDir();
#ifdef _MSC_VER
# pragma warning(pop)
#endif
// Dynamically registers a test with the framework.
//
// This is an advanced API only to be used when the `TEST` macros are
// insufficient. The macros should be preferred when possible, as they avoid
// most of the complexity of calling this function.
//
// The `factory` argument is a factory callable (move-constructible) object or
// function pointer that creates a new instance of the Test object. It
// handles ownership to the caller. The signature of the callable is
// `Fixture*()`, where `Fixture` is the test fixture class for the test. All
// tests registered with the same `test_suite_name` must return the same
// fixture type. This is checked at runtime.
//
// The framework will infer the fixture class from the factory and will call
// the `SetUpTestSuite` and `TearDownTestSuite` for it.
//
// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
// undefined.
//
// Use case example:
//
// class MyFixture : public ::testing::Test {
// public:
// // All of these optional, just like in regular macro usage.
// static void SetUpTestSuite() { ... }
// static void TearDownTestSuite() { ... }
// void SetUp() override { ... }
// void TearDown() override { ... }
// };
//
// class MyTest : public MyFixture {
// public:
// explicit MyTest(int data) : data_(data) {}
// void TestBody() override { ... }
//
// private:
// int data_;
// };
//
// void RegisterMyTests(const std::vector<int>& values) {
// for (int v : values) {
// ::testing::RegisterTest(
// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
// std::to_string(v).c_str(),
// __FILE__, __LINE__,
// // Important to use the fixture type as the return type here.
// [=]() -> MyFixture* { return new MyTest(v); });
// }
// }
// ...
// int main(int argc, char** argv) {
// std::vector<int> values_to_test = LoadValuesFromConfig();
// RegisterMyTests(values_to_test);
// ...
// return RUN_ALL_TESTS();
// }
//
template <int&... ExplicitParameterBarrier, typename Factory>
TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param,
const char* file, int line, Factory factory) {
using TestT = typename std::remove_pointer<decltype(factory())>::type;
class FactoryImpl : public internal::TestFactoryBase {
public:
explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
Test* CreateTest() override { return factory_(); }
private:
Factory factory_;
};
return internal::MakeAndRegisterTestInfo(
test_suite_name, test_name, type_param, value_param,
internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
new FactoryImpl{std::move(factory)});
}
} // namespace testing } // namespace testing
// Use this function in main() to run all tests. It returns 0 if all // Use this function in main() to run all tests. It returns 0 if all
...@@ -2233,4 +2473,6 @@ inline int RUN_ALL_TESTS() { ...@@ -2233,4 +2473,6 @@ inline int RUN_ALL_TESTS() {
return ::testing::UnitTest::GetInstance()->Run(); return ::testing::UnitTest::GetInstance()->Run();
} }
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_INCLUDE_GTEST_GTEST_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_H_
...@@ -27,18 +27,18 @@ ...@@ -27,18 +27,18 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
// //
// Implements a family of generic predicate assertion macros. // Implements a family of generic predicate assertion macros.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
// Makes sure this header is not included before gtest.h. #include "gtest/gtest.h"
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. namespace testing {
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
// This header implements a family of generic predicate assertion // This header implements a family of generic predicate assertion
// macros: // macros:
...@@ -90,9 +90,10 @@ AssertionResult AssertPred1Helper(const char* pred_text, ...@@ -90,9 +90,10 @@ AssertionResult AssertPred1Helper(const char* pred_text,
const T1& v1) { const T1& v1) {
if (pred(v1)) return AssertionSuccess(); if (pred(v1)) return AssertionSuccess();
return AssertionFailure() << pred_text << "(" return AssertionFailure()
<< e1 << ") evaluates to false, where" << pred_text << "(" << e1 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1; << "\n"
<< e1 << " evaluates to " << ::testing::PrintToString(v1);
} }
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
...@@ -134,11 +135,12 @@ AssertionResult AssertPred2Helper(const char* pred_text, ...@@ -134,11 +135,12 @@ AssertionResult AssertPred2Helper(const char* pred_text,
const T2& v2) { const T2& v2) {
if (pred(v1, v2)) return AssertionSuccess(); if (pred(v1, v2)) return AssertionSuccess();
return AssertionFailure() << pred_text << "(" return AssertionFailure()
<< e1 << ", " << pred_text << "(" << e1 << ", " << e2
<< e2 << ") evaluates to false, where" << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1 << "\n"
<< "\n" << e2 << " evaluates to " << v2; << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
<< e2 << " evaluates to " << ::testing::PrintToString(v2);
} }
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
...@@ -185,13 +187,13 @@ AssertionResult AssertPred3Helper(const char* pred_text, ...@@ -185,13 +187,13 @@ AssertionResult AssertPred3Helper(const char* pred_text,
const T3& v3) { const T3& v3) {
if (pred(v1, v2, v3)) return AssertionSuccess(); if (pred(v1, v2, v3)) return AssertionSuccess();
return AssertionFailure() << pred_text << "(" return AssertionFailure()
<< e1 << ", " << pred_text << "(" << e1 << ", " << e2 << ", " << e3
<< e2 << ", " << ") evaluates to false, where"
<< e3 << ") evaluates to false, where" << "\n"
<< "\n" << e1 << " evaluates to " << v1 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
<< "\n" << e2 << " evaluates to " << v2 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
<< "\n" << e3 << " evaluates to " << v3; << e3 << " evaluates to " << ::testing::PrintToString(v3);
} }
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
...@@ -243,15 +245,14 @@ AssertionResult AssertPred4Helper(const char* pred_text, ...@@ -243,15 +245,14 @@ AssertionResult AssertPred4Helper(const char* pred_text,
const T4& v4) { const T4& v4) {
if (pred(v1, v2, v3, v4)) return AssertionSuccess(); if (pred(v1, v2, v3, v4)) return AssertionSuccess();
return AssertionFailure() << pred_text << "(" return AssertionFailure()
<< e1 << ", " << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
<< e2 << ", " << ") evaluates to false, where"
<< e3 << ", " << "\n"
<< e4 << ") evaluates to false, where" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
<< "\n" << e1 << " evaluates to " << v1 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
<< "\n" << e2 << " evaluates to " << v2 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
<< "\n" << e3 << " evaluates to " << v3 << e4 << " evaluates to " << ::testing::PrintToString(v4);
<< "\n" << e4 << " evaluates to " << v4;
} }
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
...@@ -308,17 +309,15 @@ AssertionResult AssertPred5Helper(const char* pred_text, ...@@ -308,17 +309,15 @@ AssertionResult AssertPred5Helper(const char* pred_text,
const T5& v5) { const T5& v5) {
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
return AssertionFailure() << pred_text << "(" return AssertionFailure()
<< e1 << ", " << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
<< e2 << ", " << ", " << e5 << ") evaluates to false, where"
<< e3 << ", " << "\n"
<< e4 << ", " << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
<< e5 << ") evaluates to false, where" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
<< "\n" << e1 << " evaluates to " << v1 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
<< "\n" << e2 << " evaluates to " << v2 << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
<< "\n" << e3 << " evaluates to " << v3 << e5 << " evaluates to " << ::testing::PrintToString(v5);
<< "\n" << e4 << " evaluates to " << v4
<< "\n" << e5 << " evaluates to " << v5;
} }
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
...@@ -355,4 +354,6 @@ AssertionResult AssertPred5Helper(const char* pred_text, ...@@ -355,4 +354,6 @@ AssertionResult AssertPred5Helper(const char* pred_text,
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
...@@ -26,10 +26,10 @@ ...@@ -26,10 +26,10 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: wan@google.com (Zhanyong Wan) // Google C++ Testing and Mocking Framework definitions useful in production code.
// // GOOGLETEST_CM0003 DO NOT DELETE
// Google C++ Testing Framework definitions useful in production code.
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
...@@ -40,17 +40,20 @@ ...@@ -40,17 +40,20 @@
// //
// class MyClass { // class MyClass {
// private: // private:
// void MyMethod(); // void PrivateMethod();
// FRIEND_TEST(MyClassTest, MyMethod); // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
// }; // };
// //
// class MyClassTest : public testing::Test { // class MyClassTest : public testing::Test {
// // ... // // ...
// }; // };
// //
// TEST_F(MyClassTest, MyMethod) { // TEST_F(MyClassTest, PrivateMethodWorks) {
// // Can call MyClass::MyMethod() here. // // Can call MyClass::PrivateMethod() here.
// } // }
//
// Note: The test class must be in the same namespace as the class being tested.
// For example, putting MyClassTest in an anonymous namespace will not work.
#define FRIEND_TEST(test_case_name, test_name)\ #define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test friend class test_case_name##_##test_name##_Test
......
# Customization Points
The custom directory is an injection point for custom user configurations.
## Header `gtest.h`
### The following macros can be defined:
* `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of
`OsStackTraceGetterInterface`.
* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See
`testing::TempDir` for semantics and signature.
## Header `gtest-port.h`
The following macros can be defined:
### Flag related macros:
* `GTEST_FLAG(flag_name)`
* `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its
own flagfile flag parsing.
* `GTEST_DECLARE_bool_(name)`
* `GTEST_DECLARE_int32_(name)`
* `GTEST_DECLARE_string_(name)`
* `GTEST_DEFINE_bool_(name, default_val, doc)`
* `GTEST_DEFINE_int32_(name, default_val, doc)`
* `GTEST_DEFINE_string_(name, default_val, doc)`
### Logging:
* `GTEST_LOG_(severity)`
* `GTEST_CHECK_(condition)`
* Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.
### Threading:
* `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.
* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`
are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`
and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`
* `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`
* `GTEST_LOCK_EXCLUDED_(locks)`
### Underlying library support features
* `GTEST_HAS_CXXABI_H_`
### Exporting API symbols:
* `GTEST_API_` - Specifier for exported symbols.
## Header `gtest-printers.h`
* See documentation at `gtest/gtest-printers.h` for details on how to define a
custom printer.
...@@ -27,13 +27,11 @@ ...@@ -27,13 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// ============================================================ // Injection point for custom user configurations. See README for details
// An installation-specific extension point for gmock-matchers.h.
// ============================================================
// //
// Adds google3 callback support to CallableTraits. // ** Custom implementation starts here **
//
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
...@@ -31,8 +31,8 @@ ...@@ -31,8 +31,8 @@
// installation of gTest. // installation of gTest.
// It will be included from gtest-printers.h and the overrides in this file // It will be included from gtest-printers.h and the overrides in this file
// will be visible to everyone. // will be visible to everyone.
// See documentation at gtest/gtest-printers.h for details on how to define a //
// custom printer. // Injection point for custom user configurations. See README for details
// //
// ** Custom implementation starts here ** // ** Custom implementation starts here **
......
...@@ -27,11 +27,7 @@ ...@@ -27,11 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Injection point for custom user configurations. // Injection point for custom user configurations. See README for details
// The following macros can be defined:
//
// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of
// OsStackTraceGetterInterface.
// //
// ** Custom implementation starts here ** // ** Custom implementation starts here **
......
...@@ -27,19 +27,20 @@ ...@@ -27,19 +27,20 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file defines internal utilities needed for implementing // This header file defines internal utilities needed for implementing
// death tests. They are subject to change without notice. // death tests. They are subject to change without notice.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include <stdio.h> #include <stdio.h>
#include <memory>
namespace testing { namespace testing {
namespace internal { namespace internal {
...@@ -53,6 +54,9 @@ const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; ...@@ -53,6 +54,9 @@ const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
// DeathTest is a class that hides much of the complexity of the // DeathTest is a class that hides much of the complexity of the
// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
// returns a concrete class that depends on the prevailing death test // returns a concrete class that depends on the prevailing death test
...@@ -76,7 +80,7 @@ class GTEST_API_ DeathTest { ...@@ -76,7 +80,7 @@ class GTEST_API_ DeathTest {
// argument is set. If the death test should be skipped, the pointer // argument is set. If the death test should be skipped, the pointer
// is set to NULL; otherwise, it is set to the address of a new concrete // is set to NULL; otherwise, it is set to the address of a new concrete
// DeathTest object that controls the execution of the current test. // DeathTest object that controls the execution of the current test.
static bool Create(const char* statement, const RE* regex, static bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test); const char* file, int line, DeathTest** test);
DeathTest(); DeathTest();
virtual ~DeathTest() { } virtual ~DeathTest() { }
...@@ -136,25 +140,50 @@ class GTEST_API_ DeathTest { ...@@ -136,25 +140,50 @@ class GTEST_API_ DeathTest {
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
}; };
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// Factory interface for death tests. May be mocked out for testing. // Factory interface for death tests. May be mocked out for testing.
class DeathTestFactory { class DeathTestFactory {
public: public:
virtual ~DeathTestFactory() { } virtual ~DeathTestFactory() { }
virtual bool Create(const char* statement, const RE* regex, virtual bool Create(const char* statement,
const char* file, int line, DeathTest** test) = 0; Matcher<const std::string&> matcher, const char* file,
int line, DeathTest** test) = 0;
}; };
// A concrete DeathTestFactory implementation for normal use. // A concrete DeathTestFactory implementation for normal use.
class DefaultDeathTestFactory : public DeathTestFactory { class DefaultDeathTestFactory : public DeathTestFactory {
public: public:
virtual bool Create(const char* statement, const RE* regex, bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test); const char* file, int line, DeathTest** test) override;
}; };
// Returns true if exit_status describes a process that was terminated // Returns true if exit_status describes a process that was terminated
// by a signal, or exited normally with a nonzero exit code. // by a signal, or exited normally with a nonzero exit code.
GTEST_API_ bool ExitedUnsuccessfully(int exit_status); GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
// and interpreted as a regex (rather than an Eq matcher) for legacy
// compatibility.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
::testing::internal::RE regex) {
return ContainsRegex(regex.pattern());
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
return ContainsRegex(regex);
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
const ::std::string& regex) {
return ContainsRegex(regex);
}
// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
// used directly.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
Matcher<const ::std::string&> matcher) {
return matcher;
}
// Traps C++ exceptions escaping statement and reports them as test // Traps C++ exceptions escaping statement and reports them as test
// failures. Note that trapping SEH exceptions is not implemented here. // failures. Note that trapping SEH exceptions is not implemented here.
# if GTEST_HAS_EXCEPTIONS # if GTEST_HAS_EXCEPTIONS
...@@ -182,50 +211,53 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status); ...@@ -182,50 +211,53 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
// ASSERT_EXIT*, and EXPECT_EXIT*. // ASSERT_EXIT*, and EXPECT_EXIT*.
# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
const ::testing::internal::RE& gtest_regex = (regex); \ ::testing::internal::DeathTest* gtest_dt; \
::testing::internal::DeathTest* gtest_dt; \ if (!::testing::internal::DeathTest::Create( \
if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \ #statement, \
__FILE__, __LINE__, &gtest_dt)) { \ ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ __FILE__, __LINE__, &gtest_dt)) { \
} \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
if (gtest_dt != NULL) { \ } \
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ if (gtest_dt != nullptr) { \
gtest_dt_ptr(gtest_dt); \ std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
switch (gtest_dt->AssumeRole()) { \ switch (gtest_dt->AssumeRole()) { \
case ::testing::internal::DeathTest::OVERSEE_TEST: \ case ::testing::internal::DeathTest::OVERSEE_TEST: \
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
} \ } \
break; \ break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \
::testing::internal::DeathTest::ReturnSentinel \ ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_sentinel(gtest_dt); \ gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
break; \ break; \
} \ } \
default: \ default: \
break; \ break; \
} \ } \
} \ } \
} else \ } else \
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
fail(::testing::internal::DeathTest::LastMessage()) : fail(::testing::internal::DeathTest::LastMessage())
// The symbol "fail" here expands to something into which a message // The symbol "fail" here expands to something into which a message
// can be streamed. // can be streamed.
// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
// NDEBUG mode. In this case we need the statements to be executed, the regex is // NDEBUG mode. In this case we need the statements to be executed and the macro
// ignored, and the macro must accept a streamed message even though the message // must accept a streamed message even though the message is never printed.
// is never printed. // The regex object is not evaluated, but it is used to prevent "unused"
# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ // warnings and to avoid an expression that doesn't compile in debug mode.
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
if (::testing::internal::AlwaysTrue()) { \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ if (::testing::internal::AlwaysTrue()) { \
} else \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else if (!::testing::internal::AlwaysTrue()) { \
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
} else \
::testing::Message() ::testing::Message()
// A class representing the parsed contents of the // A class representing the parsed contents of the
...@@ -264,53 +296,6 @@ class InternalRunDeathTestFlag { ...@@ -264,53 +296,6 @@ class InternalRunDeathTestFlag {
// the flag is specified; otherwise returns NULL. // the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
#else // GTEST_HAS_DEATH_TEST
// This macro is used for implementing macros such as
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
// death tests are not supported. Those macros must compile on such systems
// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
// systems that support death tests. This allows one to write such a macro
// on a system that does not support death tests and be sure that it will
// compile on a death-test supporting system.
//
// Parameters:
// statement - A statement that a macro such as EXPECT_DEATH would test
// for program termination. This macro has to make sure this
// statement is compiled but not executed, to ensure that
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
// parameter iff EXPECT_DEATH compiles with it.
// regex - A regex that a macro such as EXPECT_DEATH would use to test
// the output of statement. This parameter has to be
// compiled but not evaluated by this macro, to ensure that
// this macro only accepts expressions that a macro such as
// EXPECT_DEATH would accept.
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
// compile inside functions where ASSERT_DEATH doesn't
// compile.
//
// The branch that has an always false condition is used to ensure that
// statement and regex are compiled (and thus syntactically correct) but
// never executed. The unreachable code macro protects the terminator
// statement from generating an 'unreachable code' warning in case
// statement unconditionally returns or throws. The Message constructor at
// the end allows the syntax of streaming additional messages into the
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_LOG_(WARNING) \
<< "Death tests are not supported on this platform.\n" \
<< "Statement '" #statement "' cannot be verified."; \
} else if (::testing::internal::AlwaysFalse()) { \
::testing::internal::RE::PartialMatch(".*", (regex)); \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
terminator; \
} else \
::testing::Message()
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
} // namespace internal } // namespace internal
......
...@@ -27,21 +27,24 @@ ...@@ -27,21 +27,24 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Author: keith.ray@gmail.com (Keith Ray)
//
// Google Test filepath utilities // Google Test filepath utilities
// //
// This header file declares classes and functions used internally by // This header file declares classes and functions used internally by
// Google Test. They are subject to change without notice. // Google Test. They are subject to change without notice.
// //
// This file is #included in <gtest/internal/gtest-internal.h>. // This file is #included in gtest/internal/gtest-internal.h.
// Do not include this header file separately! // Do not include this header file separately!
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing { namespace testing {
namespace internal { namespace internal {
...@@ -107,7 +110,7 @@ class GTEST_API_ FilePath { ...@@ -107,7 +110,7 @@ class GTEST_API_ FilePath {
const FilePath& base_name, const FilePath& base_name,
const char* extension); const char* extension);
// Returns true iff the path is "". // Returns true if and only if the path is "".
bool IsEmpty() const { return pathname_.empty(); } bool IsEmpty() const { return pathname_.empty(); }
// If input name has a trailing separator character, removes it and returns // If input name has a trailing separator character, removes it and returns
...@@ -203,4 +206,6 @@ class GTEST_API_ FilePath { ...@@ -203,4 +206,6 @@ class GTEST_API_ FilePath {
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
...@@ -27,13 +27,13 @@ ...@@ -27,13 +27,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // The Google C++ Testing and Mocking Framework (Google Test)
//
// The Google C++ Testing Framework (Google Test)
// //
// This header file declares functions and macros used internally by // This header file declares functions and macros used internally by
// Google Test. They are subject to change without notice. // Google Test. They are subject to change without notice.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
...@@ -58,11 +58,12 @@ ...@@ -58,11 +58,12 @@
#include <map> #include <map>
#include <set> #include <set>
#include <string> #include <string>
#include <type_traits>
#include <vector> #include <vector>
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/internal/gtest-string.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
#include "gtest/internal/gtest-string.h"
#include "gtest/internal/gtest-type-util.h" #include "gtest/internal/gtest-type-util.h"
// Due to C++ preprocessor weirdness, we need double indirection to // Due to C++ preprocessor weirdness, we need double indirection to
...@@ -76,7 +77,9 @@ ...@@ -76,7 +77,9 @@
#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
class ProtocolMessage; // Stringifies its argument.
#define GTEST_STRINGIFY_(name) #name
namespace proto2 { class Message; } namespace proto2 { class Message; }
namespace testing { namespace testing {
...@@ -88,7 +91,7 @@ class Message; // Represents a failure message. ...@@ -88,7 +91,7 @@ class Message; // Represents a failure message.
class Test; // Represents a test. class Test; // Represents a test.
class TestInfo; // Information about a test. class TestInfo; // Information about a test.
class TestPartResult; // Result of a test part. class TestPartResult; // Result of a test part.
class UnitTest; // A collection of test cases. class UnitTest; // A collection of test suites.
template <typename T> template <typename T>
::std::string PrintToString(const T& value); ::std::string PrintToString(const T& value);
...@@ -96,7 +99,6 @@ template <typename T> ...@@ -96,7 +99,6 @@ template <typename T>
namespace internal { namespace internal {
struct TraceInfo; // Information about a trace point. struct TraceInfo; // Information about a trace point.
class ScopedTrace; // Implements scoped trace.
class TestInfoImpl; // Opaque implementation of TestInfo class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest class UnitTestImpl; // Opaque implementation of UnitTest
...@@ -104,34 +106,22 @@ class UnitTestImpl; // Opaque implementation of UnitTest ...@@ -104,34 +106,22 @@ class UnitTestImpl; // Opaque implementation of UnitTest
// stack trace. // stack trace.
GTEST_API_ extern const char kStackTraceMarker[]; GTEST_API_ extern const char kStackTraceMarker[];
// Two overloaded helpers for checking at compile time whether an // An IgnoredValue object can be implicitly constructed from ANY value.
// expression is a null pointer literal (i.e. NULL or any 0-valued class IgnoredValue {
// compile-time integral constant). Their return values have struct Sink {};
// different sizes, so we can use sizeof() to test which version is public:
// picked by the compiler. These helpers have no implementations, as // This constructor template allows any value to be implicitly
// we only need their signatures. // converted to IgnoredValue. The object has no data member and
// // doesn't try to remember anything about the argument. We
// Given IsNullLiteralHelper(x), the compiler will pick the first // deliberately omit the 'explicit' keyword in order to allow the
// version if x can be implicitly converted to Secret*, and pick the // conversion to be implicit.
// second version otherwise. Since Secret is a secret and incomplete // Disable the conversion if T already has a magical conversion operator.
// type, the only expression a user can write that has type Secret* is // Otherwise we get ambiguity.
// a null pointer literal. Therefore, we know that x is a null template <typename T,
// pointer literal if and only if the first version is picked by the typename std::enable_if<!std::is_convertible<T, Sink>::value,
// compiler. int>::type = 0>
char IsNullLiteralHelper(Secret* p); IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
char (&IsNullLiteralHelper(...))[2]; // NOLINT };
// A compile-time bool constant that is true if and only if x is a
// null pointer literal (i.e. NULL or any 0-valued compile-time
// integral constant).
#ifdef GTEST_ELLIPSIS_NEEDS_POD_
// We lose support for NULL detection where the compiler doesn't like
// passing non-POD classes through ellipsis (...).
# define GTEST_IS_NULL_LITERAL_(x) false
#else
# define GTEST_IS_NULL_LITERAL_(x) \
(sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
#endif // GTEST_ELLIPSIS_NEEDS_POD_
// Appends the user-supplied message to the Google-Test-generated message. // Appends the user-supplied message to the Google-Test-generated message.
GTEST_API_ std::string AppendUserMessage( GTEST_API_ std::string AppendUserMessage(
...@@ -139,6 +129,9 @@ GTEST_API_ std::string AppendUserMessage( ...@@ -139,6 +129,9 @@ GTEST_API_ std::string AppendUserMessage(
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
/* an exported class was derived from a class that was not exported */)
// This exception is thrown by (and only by) a failed Google Test // This exception is thrown by (and only by) a failed Google Test
// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
// are enabled). We derive it from std::runtime_error, which is for // are enabled). We derive it from std::runtime_error, which is for
...@@ -150,32 +143,15 @@ class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { ...@@ -150,32 +143,15 @@ class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
explicit GoogleTestFailureException(const TestPartResult& failure); explicit GoogleTestFailureException(const TestPartResult& failure);
}; };
#endif // GTEST_HAS_EXCEPTIONS GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
// A helper class for creating scoped traces in user programs.
class GTEST_API_ ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
ScopedTrace(const char* file, int line, const Message& message);
// The d'tor pops the info pushed by the c'tor.
//
// Note that the d'tor is not virtual in order to be efficient.
// Don't inherit from ScopedTrace!
~ScopedTrace();
private: #endif // GTEST_HAS_EXCEPTIONS
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
// c'tor and d'tor. Therefore it doesn't
// need to be used otherwise.
namespace edit_distance { namespace edit_distance {
// Returns the optimal edits to go from 'left' to 'right'. // Returns the optimal edits to go from 'left' to 'right'.
// All edits cost the same, with replace having lower priority than // All edits cost the same, with replace having lower priority than
// add/remove. // add/remove.
// Simple implementation of the WagnerFischer algorithm. // Simple implementation of the Wagner-Fischer algorithm.
// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
enum EditType { kMatch, kAdd, kRemove, kReplace }; enum EditType { kMatch, kAdd, kRemove, kReplace };
GTEST_API_ std::vector<EditType> CalculateOptimalEdits( GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
...@@ -213,7 +189,7 @@ GTEST_API_ std::string DiffStrings(const std::string& left, ...@@ -213,7 +189,7 @@ GTEST_API_ std::string DiffStrings(const std::string& left,
// expected_value: "5" // expected_value: "5"
// actual_value: "6" // actual_value: "6"
// //
// The ignoring_case parameter is true iff the assertion is a // The ignoring_case parameter is true if and only if the assertion is a
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
// be inserted into the message. // be inserted into the message.
GTEST_API_ AssertionResult EqFailure(const char* expected_expression, GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
...@@ -342,15 +318,15 @@ class FloatingPoint { ...@@ -342,15 +318,15 @@ class FloatingPoint {
// Returns the sign bit of this number. // Returns the sign bit of this number.
Bits sign_bit() const { return kSignBitMask & u_.bits_; } Bits sign_bit() const { return kSignBitMask & u_.bits_; }
// Returns true iff this is NAN (not a number). // Returns true if and only if this is NAN (not a number).
bool is_nan() const { bool is_nan() const {
// It's a NAN if the exponent bits are all ones and the fraction // It's a NAN if the exponent bits are all ones and the fraction
// bits are not entirely zeros. // bits are not entirely zeros.
return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
} }
// Returns true iff this number is at most kMaxUlps ULP's away from // Returns true if and only if this number is at most kMaxUlps ULP's away
// rhs. In particular, this function: // from rhs. In particular, this function:
// //
// - returns false if either number is (or both are) NAN. // - returns false if either number is (or both are) NAN.
// - treats really large numbers as almost equal to infinity. // - treats really large numbers as almost equal to infinity.
...@@ -421,7 +397,7 @@ typedef FloatingPoint<float> Float; ...@@ -421,7 +397,7 @@ typedef FloatingPoint<float> Float;
typedef FloatingPoint<double> Double; typedef FloatingPoint<double> Double;
// In order to catch the mistake of putting tests that use different // In order to catch the mistake of putting tests that use different
// test fixture classes in the same test case, we need to assign // test fixture classes in the same test suite, we need to assign
// unique IDs to fixture classes and compare them. The TypeId type is // unique IDs to fixture classes and compare them. The TypeId type is
// used to hold such IDs. The user should treat TypeId as an opaque // used to hold such IDs. The user should treat TypeId as an opaque
// type: the only operation allowed on TypeId values is to compare // type: the only operation allowed on TypeId values is to compare
...@@ -481,7 +457,7 @@ class TestFactoryBase { ...@@ -481,7 +457,7 @@ class TestFactoryBase {
template <class TestClass> template <class TestClass>
class TestFactoryImpl : public TestFactoryBase { class TestFactoryImpl : public TestFactoryBase {
public: public:
virtual Test* CreateTest() { return new TestClass; } Test* CreateTest() override { return new TestClass; }
}; };
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
...@@ -497,23 +473,76 @@ GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, ...@@ -497,23 +473,76 @@ GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Types of SetUpTestCase() and TearDownTestCase() functions. // Types of SetUpTestSuite() and TearDownTestSuite() functions.
typedef void (*SetUpTestCaseFunc)(); using SetUpTestSuiteFunc = void (*)();
typedef void (*TearDownTestCaseFunc)(); using TearDownTestSuiteFunc = void (*)();
struct CodeLocation { struct CodeLocation {
CodeLocation(const string& a_file, int a_line) : file(a_file), line(a_line) {} CodeLocation(const std::string& a_file, int a_line)
: file(a_file), line(a_line) {}
string file; std::string file;
int line; int line;
}; };
// Helper to identify which setup function for TestCase / TestSuite to call.
// Only one function is allowed, either TestCase or TestSute but not both.
// Utility functions to help SuiteApiResolver
using SetUpTearDownSuiteFuncType = void (*)();
inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
return a == def ? nullptr : a;
}
template <typename T>
// Note that SuiteApiResolver inherits from T because
// SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
// SuiteApiResolver can access them.
struct SuiteApiResolver : T {
// testing::Test is only forward declared at this point. So we make it a
// dependend class for the compiler to be OK with it.
using Test =
typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
int line_num) {
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
GTEST_CHECK_(!test_case_fp || !test_suite_fp)
<< "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
"make sure there is only one present at "
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
}
static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
int line_num) {
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
GTEST_CHECK_(!test_case_fp || !test_suite_fp)
<< "Test can not provide both TearDownTestSuite and TearDownTestCase,"
" please make sure there is only one present at"
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
}
};
// Creates a new TestInfo object and registers it with Google Test; // Creates a new TestInfo object and registers it with Google Test;
// returns the created object. // returns the created object.
// //
// Arguments: // Arguments:
// //
// test_case_name: name of the test case // test_suite_name: name of the test suite
// name: name of the test // name: name of the test
// type_param the name of the test's type parameter, or NULL if // type_param the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test. // this is not a typed or a type-parameterized test.
...@@ -521,21 +550,16 @@ struct CodeLocation { ...@@ -521,21 +550,16 @@ struct CodeLocation {
// or NULL if this is not a type-parameterized test. // or NULL if this is not a type-parameterized test.
// code_location: code location where the test is defined // code_location: code location where the test is defined
// fixture_class_id: ID of the test fixture class // fixture_class_id: ID of the test fixture class
// set_up_tc: pointer to the function that sets up the test case // set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test case // tear_down_tc: pointer to the function that tears down the test suite
// factory: pointer to the factory that creates a test object. // factory: pointer to the factory that creates a test object.
// The newly created TestInfo instance will assume // The newly created TestInfo instance will assume
// ownership of the factory object. // ownership of the factory object.
GTEST_API_ TestInfo* MakeAndRegisterTestInfo( GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
const char* test_case_name, const char* test_suite_name, const char* name, const char* type_param,
const char* name, const char* value_param, CodeLocation code_location,
const char* type_param, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
const char* value_param, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
CodeLocation code_location,
TypeId fixture_class_id,
SetUpTestCaseFunc set_up_tc,
TearDownTestCaseFunc tear_down_tc,
TestFactoryBase* factory);
// If *pstr starts with the given prefix, modifies *pstr to be right // If *pstr starts with the given prefix, modifies *pstr to be right
// past the prefix and returns true; otherwise leaves *pstr unchanged // past the prefix and returns true; otherwise leaves *pstr unchanged
...@@ -544,19 +568,23 @@ GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); ...@@ -544,19 +568,23 @@ GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
// State of the definition of a type-parameterized test case. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
class GTEST_API_ TypedTestCasePState { /* class A needs to have dll-interface to be used by clients of class B */)
// State of the definition of a type-parameterized test suite.
class GTEST_API_ TypedTestSuitePState {
public: public:
TypedTestCasePState() : registered_(false) {} TypedTestSuitePState() : registered_(false) {}
// Adds the given test name to defined_test_names_ and return true // Adds the given test name to defined_test_names_ and return true
// if the test case hasn't been registered; otherwise aborts the // if the test suite hasn't been registered; otherwise aborts the
// program. // program.
bool AddTestName(const char* file, int line, const char* case_name, bool AddTestName(const char* file, int line, const char* case_name,
const char* test_name) { const char* test_name) {
if (registered_) { if (registered_) {
fprintf(stderr, "%s Test %s must be defined before " fprintf(stderr,
"REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", "%s Test %s must be defined before "
"REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
FormatFileLocation(file, line).c_str(), test_name, case_name); FormatFileLocation(file, line).c_str(), test_name, case_name);
fflush(stderr); fflush(stderr);
posix::Abort(); posix::Abort();
...@@ -589,12 +617,19 @@ class GTEST_API_ TypedTestCasePState { ...@@ -589,12 +617,19 @@ class GTEST_API_ TypedTestCasePState {
RegisteredTestsMap registered_tests_; RegisteredTestsMap registered_tests_;
}; };
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
using TypedTestCasePState = TypedTestSuitePState;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// Skips to the first non-space char after the first comma in 'str'; // Skips to the first non-space char after the first comma in 'str';
// returns NULL if no comma is found in 'str'. // returns NULL if no comma is found in 'str'.
inline const char* SkipComma(const char* str) { inline const char* SkipComma(const char* str) {
const char* comma = strchr(str, ','); const char* comma = strchr(str, ',');
if (comma == NULL) { if (comma == nullptr) {
return NULL; return nullptr;
} }
while (IsSpace(*(++comma))) {} while (IsSpace(*(++comma))) {}
return comma; return comma;
...@@ -604,7 +639,7 @@ inline const char* SkipComma(const char* str) { ...@@ -604,7 +639,7 @@ inline const char* SkipComma(const char* str) {
// the entire string if it contains no comma. // the entire string if it contains no comma.
inline std::string GetPrefixUntilComma(const char* str) { inline std::string GetPrefixUntilComma(const char* str) {
const char* comma = strchr(str, ','); const char* comma = strchr(str, ',');
return comma == NULL ? str : std::string(str, comma); return comma == nullptr ? str : std::string(str, comma);
} }
// Splits a given string on a given delimiter, populating a given // Splits a given string on a given delimiter, populating a given
...@@ -612,6 +647,37 @@ inline std::string GetPrefixUntilComma(const char* str) { ...@@ -612,6 +647,37 @@ inline std::string GetPrefixUntilComma(const char* str) {
void SplitString(const ::std::string& str, char delimiter, void SplitString(const ::std::string& str, char delimiter,
::std::vector< ::std::string>* dest); ::std::vector< ::std::string>* dest);
// The default argument to the template below for the case when the user does
// not provide a name generator.
struct DefaultNameGenerator {
template <typename T>
static std::string GetName(int i) {
return StreamableToString(i);
}
};
template <typename Provided = DefaultNameGenerator>
struct NameGeneratorSelector {
typedef Provided type;
};
template <typename NameGenerator>
void GenerateNamesRecursively(Types0, std::vector<std::string>*, int) {}
template <typename NameGenerator, typename Types>
void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
i + 1);
}
template <typename NameGenerator, typename Types>
std::vector<std::string> GenerateNames() {
std::vector<std::string> result;
GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
return result;
}
// TypeParameterizedTest<Fixture, TestSel, Types>::Register() // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
// registers a list of type-parameterized tests with Google Test. The // registers a list of type-parameterized tests with Google Test. The
// return value is insignificant - we just need to return something // return value is insignificant - we just need to return something
...@@ -623,13 +689,13 @@ template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types> ...@@ -623,13 +689,13 @@ template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
class TypeParameterizedTest { class TypeParameterizedTest {
public: public:
// 'index' is the index of the test in the type list 'Types' // 'index' is the index of the test in the type list 'Types'
// specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
// Types). Valid values for 'index' are [0, N - 1] where N is the // Types). Valid values for 'index' are [0, N - 1] where N is the
// length of Types. // length of Types.
static bool Register(const char* prefix, static bool Register(const char* prefix, const CodeLocation& code_location,
CodeLocation code_location, const char* case_name, const char* test_names, int index,
const char* case_name, const char* test_names, const std::vector<std::string>& type_names =
int index) { GenerateNames<DefaultNameGenerator, Types>()) {
typedef typename Types::Head Type; typedef typename Types::Head Type;
typedef Fixture<Type> FixtureClass; typedef Fixture<Type> FixtureClass;
typedef typename GTEST_BIND_(TestSel, Type) TestClass; typedef typename GTEST_BIND_(TestSel, Type) TestClass;
...@@ -637,20 +703,27 @@ class TypeParameterizedTest { ...@@ -637,20 +703,27 @@ class TypeParameterizedTest {
// First, registers the first type-parameterized test in the type // First, registers the first type-parameterized test in the type
// list. // list.
MakeAndRegisterTestInfo( MakeAndRegisterTestInfo(
(std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
+ StreamableToString(index)).c_str(), "/" + type_names[static_cast<size_t>(index)])
.c_str(),
StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
GetTypeName<Type>().c_str(), GetTypeName<Type>().c_str(),
NULL, // No value parameter. nullptr, // No value parameter.
code_location, code_location, GetTypeId<FixtureClass>(),
GetTypeId<FixtureClass>(), SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
TestClass::SetUpTestCase, code_location.file.c_str(), code_location.line),
TestClass::TearDownTestCase, SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
code_location.file.c_str(), code_location.line),
new TestFactoryImpl<TestClass>); new TestFactoryImpl<TestClass>);
// Next, recurses (at compile time) with the tail of the type list. // Next, recurses (at compile time) with the tail of the type list.
return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail> return TypeParameterizedTest<Fixture, TestSel,
::Register(prefix, code_location, case_name, test_names, index + 1); typename Types::Tail>::Register(prefix,
code_location,
case_name,
test_names,
index + 1,
type_names);
} }
}; };
...@@ -658,23 +731,27 @@ class TypeParameterizedTest { ...@@ -658,23 +731,27 @@ class TypeParameterizedTest {
template <GTEST_TEMPLATE_ Fixture, class TestSel> template <GTEST_TEMPLATE_ Fixture, class TestSel>
class TypeParameterizedTest<Fixture, TestSel, Types0> { class TypeParameterizedTest<Fixture, TestSel, Types0> {
public: public:
static bool Register(const char* /*prefix*/, CodeLocation, static bool Register(const char* /*prefix*/, const CodeLocation&,
const char* /*case_name*/, const char* /*test_names*/, const char* /*case_name*/, const char* /*test_names*/,
int /*index*/) { int /*index*/,
const std::vector<std::string>& =
std::vector<std::string>() /*type_names*/) {
return true; return true;
} }
}; };
// TypeParameterizedTestCase<Fixture, Tests, Types>::Register() // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
// registers *all combinations* of 'Tests' and 'Types' with Google // registers *all combinations* of 'Tests' and 'Types' with Google
// Test. The return value is insignificant - we just need to return // Test. The return value is insignificant - we just need to return
// something such that we can call this function in a namespace scope. // something such that we can call this function in a namespace scope.
template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types> template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
class TypeParameterizedTestCase { class TypeParameterizedTestSuite {
public: public:
static bool Register(const char* prefix, CodeLocation code_location, static bool Register(const char* prefix, CodeLocation code_location,
const TypedTestCasePState* state, const TypedTestSuitePState* state, const char* case_name,
const char* case_name, const char* test_names) { const char* test_names,
const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) {
std::string test_name = StripTrailingSpaces( std::string test_name = StripTrailingSpaces(
GetPrefixUntilComma(test_names)); GetPrefixUntilComma(test_names));
if (!state->TestExists(test_name)) { if (!state->TestExists(test_name)) {
...@@ -691,22 +768,26 @@ class TypeParameterizedTestCase { ...@@ -691,22 +768,26 @@ class TypeParameterizedTestCase {
// First, register the first test in 'Test' for each type in 'Types'. // First, register the first test in 'Test' for each type in 'Types'.
TypeParameterizedTest<Fixture, Head, Types>::Register( TypeParameterizedTest<Fixture, Head, Types>::Register(
prefix, test_location, case_name, test_names, 0); prefix, test_location, case_name, test_names, 0, type_names);
// Next, recurses (at compile time) with the tail of the test list. // Next, recurses (at compile time) with the tail of the test list.
return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types> return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
::Register(prefix, code_location, state, Types>::Register(prefix, code_location,
case_name, SkipComma(test_names)); state, case_name,
SkipComma(test_names),
type_names);
} }
}; };
// The base case for the compile time recursion. // The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, typename Types> template <GTEST_TEMPLATE_ Fixture, typename Types>
class TypeParameterizedTestCase<Fixture, Templates0, Types> { class TypeParameterizedTestSuite<Fixture, Templates0, Types> {
public: public:
static bool Register(const char* /*prefix*/, CodeLocation, static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestCasePState* /*state*/, const TypedTestSuitePState* /*state*/,
const char* /*case_name*/, const char* /*test_names*/) { const char* /*case_name*/, const char* /*test_names*/,
const std::vector<std::string>& =
std::vector<std::string>() /*type_names*/) {
return true; return true;
} }
}; };
...@@ -766,145 +847,16 @@ class GTEST_API_ Random { ...@@ -766,145 +847,16 @@ class GTEST_API_ Random {
GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
}; };
// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
// compiler error iff T1 and T2 are different types.
template <typename T1, typename T2>
struct CompileAssertTypesEqual;
template <typename T>
struct CompileAssertTypesEqual<T, T> {
};
// Removes the reference from a type if it is a reference type,
// otherwise leaves it unchanged. This is the same as
// tr1::remove_reference, which is not widely available yet.
template <typename T>
struct RemoveReference { typedef T type; }; // NOLINT
template <typename T>
struct RemoveReference<T&> { typedef T type; }; // NOLINT
// A handy wrapper around RemoveReference that works when the argument
// T depends on template parameters.
#define GTEST_REMOVE_REFERENCE_(T) \
typename ::testing::internal::RemoveReference<T>::type
// Removes const from a type if it is a const type, otherwise leaves
// it unchanged. This is the same as tr1::remove_const, which is not
// widely available yet.
template <typename T>
struct RemoveConst { typedef T type; }; // NOLINT
template <typename T>
struct RemoveConst<const T> { typedef T type; }; // NOLINT
// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
// definition to fail to remove the const in 'const int[3]' and 'const
// char[3][4]'. The following specialization works around the bug.
template <typename T, size_t N>
struct RemoveConst<const T[N]> {
typedef typename RemoveConst<T>::type type[N];
};
#if defined(_MSC_VER) && _MSC_VER < 1400
// This is the only specialization that allows VC++ 7.1 to remove const in
// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC
// and thus needs to be conditionally compiled.
template <typename T, size_t N>
struct RemoveConst<T[N]> {
typedef typename RemoveConst<T>::type type[N];
};
#endif
// A handy wrapper around RemoveConst that works when the argument
// T depends on template parameters.
#define GTEST_REMOVE_CONST_(T) \
typename ::testing::internal::RemoveConst<T>::type
// Turns const U&, U&, const U, and U all into U. // Turns const U&, U&, const U, and U all into U.
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) typename std::remove_const<typename std::remove_reference<T>::type>::type
// Adds reference to a type if it is not a reference type,
// otherwise leaves it unchanged. This is the same as
// tr1::add_reference, which is not widely available yet.
template <typename T>
struct AddReference { typedef T& type; }; // NOLINT
template <typename T>
struct AddReference<T&> { typedef T& type; }; // NOLINT
// A handy wrapper around AddReference that works when the argument T
// depends on template parameters.
#define GTEST_ADD_REFERENCE_(T) \
typename ::testing::internal::AddReference<T>::type
// Adds a reference to const on top of T as necessary. For example,
// it transforms
//
// char ==> const char&
// const char ==> const char&
// char& ==> const char&
// const char& ==> const char&
//
// The argument T must depend on some template parameters.
#define GTEST_REFERENCE_TO_CONST_(T) \
GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T))
// ImplicitlyConvertible<From, To>::value is a compile-time bool
// constant that's true iff type From can be implicitly converted to
// type To.
template <typename From, typename To>
class ImplicitlyConvertible {
private:
// We need the following helper functions only for their types.
// They have no implementations.
// MakeFrom() is an expression whose type is From. We cannot simply
// use From(), as the type From may not have a public default
// constructor.
static typename AddReference<From>::type MakeFrom();
// These two functions are overloaded. Given an expression
// Helper(x), the compiler will pick the first version if x can be
// implicitly converted to type To; otherwise it will pick the
// second version.
//
// The first version returns a value of size 1, and the second
// version returns a value of size 2. Therefore, by checking the
// size of Helper(x), which can be done at compile time, we can tell
// which version of Helper() is used, and hence whether x can be
// implicitly converted to type To.
static char Helper(To);
static char (&Helper(...))[2]; // NOLINT
// We have to put the 'public' section after the 'private' section,
// or MSVC refuses to compile the code.
public:
#if defined(__BORLANDC__)
// C++Builder cannot use member overload resolution during template
// instantiation. The simplest workaround is to use its C++0x type traits
// functions (C++Builder 2009 and above only).
static const bool value = __is_convertible(From, To);
#else
// MSVC warns about implicitly converting from double to int for
// possible loss of data, so we need to temporarily disable the
// warning.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244)
static const bool value =
sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif // __BORLANDC__
};
template <typename From, typename To>
const bool ImplicitlyConvertible<From, To>::value;
// IsAProtocolMessage<T>::value is a compile-time bool constant that's // IsAProtocolMessage<T>::value is a compile-time bool constant that's
// true iff T is type ProtocolMessage, proto2::Message, or a subclass // true if and only if T is type proto2::Message or a subclass of it.
// of those.
template <typename T> template <typename T>
struct IsAProtocolMessage struct IsAProtocolMessage
: public bool_constant< : public bool_constant<
ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value || std::is_convertible<const T*, const ::proto2::Message*>::value> {};
ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> {
};
// When the compiler sees expression IsContainerTest<C>(0), if C is an // When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest // STL-style container class, the first overload of IsContainerTest
...@@ -917,8 +869,11 @@ struct IsAProtocolMessage ...@@ -917,8 +869,11 @@ struct IsAProtocolMessage
// a container class by checking the type of IsContainerTest<C>(0). // a container class by checking the type of IsContainerTest<C>(0).
// The value of the expression is insignificant. // The value of the expression is insignificant.
// //
// Note that we look for both C::iterator and C::const_iterator. The // In C++11 mode we check the existence of a const_iterator and that an
// reason is that C++ injects the name of a class as a member of the // iterator is properly implemented for the container.
//
// For pre-C++11 that we look for both C::iterator and C::const_iterator.
// The reason is that C++ injects the name of a class as a member of the
// class itself (e.g. you can refer to class iterator as either // class itself (e.g. you can refer to class iterator as either
// 'iterator' or 'iterator::iterator'). If we look for C::iterator // 'iterator' or 'iterator::iterator'). If we look for C::iterator
// only, for example, we would mistakenly think that a class named // only, for example, we would mistakenly think that a class named
...@@ -928,10 +883,13 @@ struct IsAProtocolMessage ...@@ -928,10 +883,13 @@ struct IsAProtocolMessage
// IsContainerTest(typename C::const_iterator*) and // IsContainerTest(typename C::const_iterator*) and
// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
typedef int IsContainer; typedef int IsContainer;
template <class C> template <class C,
IsContainer IsContainerTest(int /* dummy */, class Iterator = decltype(::std::declval<const C&>().begin()),
typename C::iterator* /* it */ = NULL, class = decltype(::std::declval<const C&>().end()),
typename C::const_iterator* /* const_it */ = NULL) { class = decltype(++::std::declval<Iterator&>()),
class = decltype(*::std::declval<Iterator>()),
class = typename C::const_iterator>
IsContainer IsContainerTest(int /* dummy */) {
return 0; return 0;
} }
...@@ -939,12 +897,55 @@ typedef char IsNotContainer; ...@@ -939,12 +897,55 @@ typedef char IsNotContainer;
template <class C> template <class C>
IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
// EnableIf<condition>::type is void when 'Cond' is true, and // Trait to detect whether a type T is a hash table.
// undefined when 'Cond' is false. To use SFINAE to make a function // The heuristic used is that the type contains an inner type `hasher` and does
// overload only apply when a particular expression is true, add // not contain an inner type `reverse_iterator`.
// "typename EnableIf<expression>::type* = 0" as the last parameter. // If the container is iterable in reverse, then order might actually matter.
template<bool> struct EnableIf; template <typename T>
template<> struct EnableIf<true> { typedef void type; }; // NOLINT struct IsHashTable {
private:
template <typename U>
static char test(typename U::hasher*, typename U::reverse_iterator*);
template <typename U>
static int test(typename U::hasher*, ...);
template <typename U>
static char test(...);
public:
static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
};
template <typename T>
const bool IsHashTable<T>::value;
template <typename C,
bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
struct IsRecursiveContainerImpl;
template <typename C>
struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
// obey the same inconsistencies as the IsContainerTest, namely check if
// something is a container is relying on only const_iterator in C++11 and
// is relying on both const_iterator and iterator otherwise
template <typename C>
struct IsRecursiveContainerImpl<C, true> {
using value_type = decltype(*std::declval<typename C::const_iterator>());
using type =
std::is_same<typename std::remove_const<
typename std::remove_reference<value_type>::type>::type,
C>;
};
// IsRecursiveContainer<Type> is a unary compile-time predicate that
// evaluates whether C is a recursive container type. A recursive container
// type is a container type whose value_type is equal to the container type
// itself. An example for a recursive container type is
// boost::filesystem::path, whose iterator has a value_type that is equal to
// boost::filesystem::path.
template <typename C>
struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
// Utilities for native arrays. // Utilities for native arrays.
...@@ -1068,10 +1069,9 @@ class NativeArray { ...@@ -1068,10 +1069,9 @@ class NativeArray {
} }
private: private:
enum { static_assert(!std::is_const<Element>::value, "Type must not be const");
kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< static_assert(!std::is_reference<Element>::value,
Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value, "Type must not be a reference");
};
// Initializes this object with a copy of the input. // Initializes this object with a copy of the input.
void InitCopy(const Element* array, size_t a_size) { void InitCopy(const Element* array, size_t a_size) {
...@@ -1096,6 +1096,139 @@ class NativeArray { ...@@ -1096,6 +1096,139 @@ class NativeArray {
GTEST_DISALLOW_ASSIGN_(NativeArray); GTEST_DISALLOW_ASSIGN_(NativeArray);
}; };
// Backport of std::index_sequence.
template <size_t... Is>
struct IndexSequence {
using type = IndexSequence;
};
// Double the IndexSequence, and one if plus_one is true.
template <bool plus_one, typename T, size_t sizeofT>
struct DoubleSequence;
template <size_t... I, size_t sizeofT>
struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
};
template <size_t... I, size_t sizeofT>
struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
using type = IndexSequence<I..., (sizeofT + I)...>;
};
// Backport of std::make_index_sequence.
// It uses O(ln(N)) instantiation depth.
template <size_t N>
struct MakeIndexSequence
: DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
N / 2>::type {};
template <>
struct MakeIndexSequence<0> : IndexSequence<> {};
// FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
// but it is O(N^2) in total instantiations. Not sure if this is the best
// tradeoff, as it will make it somewhat slow to compile.
template <typename T, size_t, size_t>
struct ElemFromListImpl {};
template <typename T, size_t I>
struct ElemFromListImpl<T, I, I> {
using type = T;
};
// Get the Nth element from T...
// It uses O(1) instantiation depth.
template <size_t N, typename I, typename... T>
struct ElemFromList;
template <size_t N, size_t... I, typename... T>
struct ElemFromList<N, IndexSequence<I...>, T...>
: ElemFromListImpl<T, N, I>... {};
template <typename... T>
class FlatTuple;
template <typename Derived, size_t I>
struct FlatTupleElemBase;
template <typename... T, size_t I>
struct FlatTupleElemBase<FlatTuple<T...>, I> {
using value_type =
typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type,
T...>::type;
FlatTupleElemBase() = default;
explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
value_type value;
};
template <typename Derived, typename Idx>
struct FlatTupleBase;
template <size_t... Idx, typename... T>
struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
: FlatTupleElemBase<FlatTuple<T...>, Idx>... {
using Indices = IndexSequence<Idx...>;
FlatTupleBase() = default;
explicit FlatTupleBase(T... t)
: FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
};
// Analog to std::tuple but with different tradeoffs.
// This class minimizes the template instantiation depth, thus allowing more
// elements that std::tuple would. std::tuple has been seen to require an
// instantiation depth of more than 10x the number of elements in some
// implementations.
// FlatTuple and ElemFromList are not recursive and have a fixed depth
// regardless of T...
// MakeIndexSequence, on the other hand, it is recursive but with an
// instantiation depth of O(ln(N)).
template <typename... T>
class FlatTuple
: private FlatTupleBase<FlatTuple<T...>,
typename MakeIndexSequence<sizeof...(T)>::type> {
using Indices = typename FlatTuple::FlatTupleBase::Indices;
public:
FlatTuple() = default;
explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
template <size_t I>
const typename ElemFromList<I, Indices, T...>::type& Get() const {
return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
}
template <size_t I>
typename ElemFromList<I, Indices, T...>::type& Get() {
return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
}
};
// Utility functions to be called with static_assert to induce deprecation
// warnings.
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TEST_SUITE_P")
constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE_P is deprecated, please use "
"TYPED_TEST_SUITE_P")
constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE is deprecated, please use "
"TYPED_TEST_SUITE")
constexpr bool TypedTestCaseIsDeprecated() { return true; }
GTEST_INTERNAL_DEPRECATED(
"REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
"REGISTER_TYPED_TEST_SUITE_P")
constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TYPED_TEST_SUITE_P")
constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
...@@ -1115,7 +1248,10 @@ class NativeArray { ...@@ -1115,7 +1248,10 @@ class NativeArray {
#define GTEST_SUCCESS_(message) \ #define GTEST_SUCCESS_(message) \
GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
// Suppresses MSVC warnings 4072 (unreachable code) for the code following #define GTEST_SKIP_(message) \
return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
// Suppress MSVC warning 4072 (unreachable code) for the code following
// statement if it returns or throws (or doesn't return or throw in some // statement if it returns or throws (or doesn't return or throw in some
// situations). // situations).
#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
...@@ -1207,32 +1343,38 @@ class NativeArray { ...@@ -1207,32 +1343,38 @@ class NativeArray {
" Actual: it does.") " Actual: it does.")
// Expands to the name of the class that implements the given test. // Expands to the name of the class that implements the given test.
#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
test_case_name##_##test_name##_Test test_suite_name##_##test_name##_Test
// Helper macro for defining tests. // Helper macro for defining tests.
#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
public:\ "test_suite_name must not be empty"); \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
private:\ "test_name must not be empty"); \
virtual void TestBody();\ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ : public parent_class { \
GTEST_DISALLOW_COPY_AND_ASSIGN_(\ public: \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
};\ \
\ private: \
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ virtual void TestBody(); \
::test_info_ =\ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
::testing::internal::MakeAndRegisterTestInfo(\ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
#test_case_name, #test_name, NULL, NULL, \ test_name)); \
::testing::internal::CodeLocation(__FILE__, __LINE__), \ }; \
(parent_id), \ \
parent_class::SetUpTestCase, \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
parent_class::TearDownTestCase, \ test_name)::test_info_ = \
new ::testing::internal::TestFactoryImpl<\ ::testing::internal::MakeAndRegisterTestInfo( \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ #test_suite_name, #test_name, nullptr, nullptr, \
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
::testing::internal::SuiteApiResolver< \
parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
::testing::internal::SuiteApiResolver< \
parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
test_suite_name, test_name)>); \
void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment