Unverified Commit f11a8f91 authored by Conor Burgess's avatar Conor Burgess Committed by GitHub
Browse files

Merge branch 'master' into fix-argc

parents 27bb844e 15392f1a
...@@ -37,6 +37,7 @@ ...@@ -37,6 +37,7 @@
#include <string> #include <string>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h"
#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
...@@ -51,9 +52,9 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], ...@@ -51,9 +52,9 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) { const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose); const ::std::string old_verbose = GMOCK_FLAG(verbose);
int argc = M; int argc = M - 1;
InitGoogleMock(&argc, const_cast<Char**>(argv)); InitGoogleMock(&argc, const_cast<Char**>(argv));
ASSERT_EQ(N, argc) << "The new argv has wrong number of elements."; ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements.";
for (int i = 0; i < N; i++) { for (int i = 0; i < N; i++) {
EXPECT_STREQ(new_argv[i], argv[i]); EXPECT_STREQ(new_argv[i], argv[i]);
......
#!/usr/bin/env python
#
# Copyright 2006, Google Inc. # Copyright 2006, Google Inc.
# All rights reserved. # All rights reserved.
# #
...@@ -36,19 +34,19 @@ __author__ = 'wan@google.com (Zhanyong Wan)' ...@@ -36,19 +34,19 @@ __author__ = 'wan@google.com (Zhanyong Wan)'
import os import os
import sys import sys
# Determines path to gtest_test_utils and imports it. # Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.' SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links. # isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test') gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../googletest/test')
if os.path.isdir(gtest_tests_util_dir): if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else: else:
GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test') GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../googletest/test')
sys.path.append(GTEST_TESTS_UTIL_DIR) sys.path.append(GTEST_TESTS_UTIL_DIR)
import gtest_test_utils # pylint: disable-msg=C6204
# pylint: disable=C6204
import gtest_test_utils
def GetSourceDir(): def GetSourceDir():
......
...@@ -95,6 +95,9 @@ macro(config_compiler_and_linker) ...@@ -95,6 +95,9 @@ macro(config_compiler_and_linker)
set(cxx_no_rtti_flags "-GR-") set(cxx_no_rtti_flags "-GR-")
elseif (CMAKE_COMPILER_IS_GNUCXX) elseif (CMAKE_COMPILER_IS_GNUCXX)
set(cxx_base_flags "-Wall -Wshadow -Werror") set(cxx_base_flags "-Wall -Wshadow -Werror")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
endif()
set(cxx_exception_flags "-fexceptions") set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions") set(cxx_no_exception_flags "-fno-exceptions")
# Until version 4.3.2, GCC doesn't define a macro to indicate # Until version 4.3.2, GCC doesn't define a macro to indicate
......
...@@ -787,15 +787,17 @@ If a test sub-routine is called from several places, when an assertion ...@@ -787,15 +787,17 @@ If a test sub-routine is called from several places, when an assertion
inside it fails, it can be hard to tell which invocation of the inside it fails, it can be hard to tell which invocation of the
sub-routine the failure is from. You can alleviate this problem using sub-routine the failure is from. You can alleviate this problem using
extra logging or custom failure messages, but that usually clutters up extra logging or custom failure messages, but that usually clutters up
your tests. A better solution is to use the `SCOPED_TRACE` macro: your tests. A better solution is to use the `SCOPED_TRACE` macro or
the `ScopedTrace` utility:
| `SCOPED_TRACE(`_message_`);` | | `SCOPED_TRACE(`_message_`);` | `::testing::ScopedTrace trace(`_"file\_path"_`, `_line\_number_`, `_message_`);` |
|:-----------------------------| |:-----------------------------|:---------------------------------------------------------------------------------|
where _message_ can be anything streamable to `std::ostream`. This where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE`
macro will cause the current file name, line number, and the given macro will cause the current file name, line number, and the given message to be
message to be added in every failure message. The effect will be added in every failure message. `ScopedTrace` accepts explicit file name and
undone when the control leaves the current lexical scope. line number in arguments, which is useful for writing test helpers. The effect
will be undone when the control leaves the current lexical scope.
For example, For example,
...@@ -870,13 +872,33 @@ TEST(FooTest, Bar) { ...@@ -870,13 +872,33 @@ TEST(FooTest, Bar) {
} }
``` ```
Since we don't use exceptions, it is technically impossible to To alleviate this, gUnit provides three different solutions. You could use
implement the intended behavior here. To alleviate this, Google Test either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
provides two solutions. You could use either the `HasFatalFailure()` function. They are described in the following two
`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
subsections. subsections.
#### Asserting on Subroutines with an exception
The following code can turn ASSERT-failure into an exception:
```c++
class ThrowListener : public testing::EmptyTestEventListener {
void OnTestPartResult(const testing::TestPartResult& result) override {
if (result.type() == testing::TestPartResult::kFatalFailure) {
throw testing::AssertionException(result);
}
}
};
int main(int argc, char** argv) {
...
testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);
return RUN_ALL_TESTS();
}
```
This listener should be added after other listeners if you have any, otherwise
they won't see failed `OnTestPartResult`.
### Asserting on Subroutines ### ### Asserting on Subroutines ###
As shown above, if your test calls a subroutine that has an `ASSERT_*` As shown above, if your test calls a subroutine that has an `ASSERT_*`
...@@ -1949,6 +1971,17 @@ variable to `0` has the same effect. ...@@ -1949,6 +1971,17 @@ variable to `0` has the same effect.
_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, _Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower,
the default behavior is that the elapsed time is **not** printed.) the default behavior is that the elapsed time is **not** printed.)
**Availability**: Linux, Windows, Mac.
#### Suppressing UTF-8 Text Output
In case of assertion failures, gUnit prints expected and actual values of type
`string` both as hex-encoded strings as well as in readable UTF-8 text if they
contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text
because, for example, you don't have an UTF-8 compatible output medium, run the
test program with `--gunit_print_utf8=0` or set the `GUNIT_PRINT_UTF8`
environment variable to `0`.
### Generating an XML Report ### ### Generating an XML Report ###
Google Test can emit a detailed XML report to a file in addition to its normal Google Test can emit a detailed XML report to a file in addition to its normal
......
...@@ -12,5 +12,5 @@ the respective git branch/tag).** ...@@ -12,5 +12,5 @@ the respective git branch/tag).**
To contribute code to Google Test, read: To contribute code to Google Test, read:
* [CONTRIBUTING](../CONTRIBUTING.md) -- read this _before_ writing your first patch. * [CONTRIBUTING](../../CONTRIBUTING.md) -- read this _before_ writing your first patch.
* [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files. * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files.
...@@ -460,7 +460,7 @@ following benefits: ...@@ -460,7 +460,7 @@ following benefits:
You may still want to use `SetUp()/TearDown()` in the following rare cases: You may still want to use `SetUp()/TearDown()` in the following rare cases:
* If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
* The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag.
* In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`. * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use `SetUp()/TearDown()`.
## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## ## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
......
...@@ -46,6 +46,10 @@ ...@@ -46,6 +46,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.
...@@ -107,6 +111,11 @@ ...@@ -107,6 +111,11 @@
# include <tuple> # include <tuple>
#endif #endif
#if GTEST_HAS_ABSL
#include "absl/types/optional.h"
#include "absl/strings/string_view.h"
#endif // GTEST_HAS_ABSL
namespace testing { namespace testing {
// Definitions in the 'internal' and 'internal2' name spaces are // Definitions in the 'internal' and 'internal2' name spaces are
...@@ -125,7 +134,11 @@ enum TypeKind { ...@@ -125,7 +134,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
...@@ -138,7 +151,7 @@ class TypeWithoutFormatter { ...@@ -138,7 +151,7 @@ class TypeWithoutFormatter {
// 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(static_cast<const unsigned char*>( PrintBytesInObjectTo(static_cast<const unsigned char*>(
reinterpret_cast<const void *>(&value)), reinterpret_cast<const void*>(&value)),
sizeof(value), os); sizeof(value), os);
} }
}; };
...@@ -176,6 +189,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> { ...@@ -176,6 +189,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
...@@ -203,10 +229,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> { ...@@ -203,10 +229,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 ? : internal::ImplicitlyConvertible<
kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); const T&, internal::BiggestInt>::value
? kConvertibleToInteger
:
#if GTEST_HAS_ABSL
internal::ImplicitlyConvertible<
const T&, absl::string_view>::value
? kConvertibleToStringView
:
#endif
kOtherType)>::PrintValue(x, &os);
return os; return os;
} }
...@@ -427,7 +462,8 @@ void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */, ...@@ -427,7 +462,8 @@ void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
*os << "NULL"; *os << "NULL";
} else { } else {
// T is a function type, so '*os << p' doesn't do what we want // T is a function type, so '*os << p' doesn't do what we want
// (it just prints p as bool). Cast p to const void* to print it. // (it just prints p as bool). We want to print p as a const
// void*.
*os << reinterpret_cast<const void*>(p); *os << reinterpret_cast<const void*>(p);
} }
} }
...@@ -456,17 +492,15 @@ void PrintTo(const T& value, ::std::ostream* os) { ...@@ -456,17 +492,15 @@ void PrintTo(const T& value, ::std::ostream* os) {
// DefaultPrintTo() is overloaded. The type of its first argument // DefaultPrintTo() is overloaded. The type of its first argument
// determines which version will be picked. // determines which version will be picked.
// //
// Note that we check for recursive and other container types here, prior // Note that we check for container types here, prior to we check
// to we check for protocol message types in our operator<<. The rationale is: // for protocol message types in our operator<<. The rationale is:
// //
// For protocol messages, we want to give people a chance to // For protocol messages, we want to give people a chance to
// override Google Mock's format by defining a PrintTo() or // override Google Mock's format by defining a PrintTo() or
// operator<<. For STL containers, other formats can be // operator<<. For STL containers, other formats can be
// incompatible with Google Mock's format for the container // incompatible with Google Mock's format for the container
// 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. To prevent an infinite runtime recursion // that our format is used.
// during the output of recursive container types, we check first for
// those.
// //
// Note that MSVC and clang-cl do allow an implicit conversion from // Note that MSVC and clang-cl do allow an implicit conversion from
// pointer-to-function to pointer-to-object, but clang-cl warns on it. // pointer-to-function to pointer-to-object, but clang-cl warns on it.
...@@ -484,8 +518,8 @@ void PrintTo(const T& value, ::std::ostream* os) { ...@@ -484,8 +518,8 @@ void PrintTo(const T& value, ::std::ostream* os) {
#else #else
: !internal::ImplicitlyConvertible<T, const void*>::value : !internal::ImplicitlyConvertible<T, const void*>::value
#endif #endif
? kPrintFunctionPointer ? kPrintFunctionPointer
: kPrintPointer>(), : kPrintPointer>(),
value, os); value, os);
} }
...@@ -593,6 +627,13 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { ...@@ -593,6 +627,13 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_ABSL
// Overload for absl::string_view.
inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
PrintTo(::std::string(sp), os);
}
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
// Helper function for printing a tuple. T must be instantiated with // Helper function for printing a tuple. T must be instantiated with
// a tuple type. // a tuple type.
...@@ -722,6 +763,26 @@ class UniversalPrinter { ...@@ -722,6 +763,26 @@ 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 << ')';
}
};
#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>
...@@ -868,7 +929,7 @@ void UniversalPrint(const T& value, ::std::ostream* os) { ...@@ -868,7 +929,7 @@ 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: // TuplePolicy<TupleT> must provide:
// - tuple_size // - tuple_size
...@@ -988,6 +1049,16 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { ...@@ -988,6 +1049,16 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // 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;
......
...@@ -115,6 +115,9 @@ GTEST_DECLARE_string_(output); ...@@ -115,6 +115,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 +138,7 @@ GTEST_DECLARE_int32_(stack_trace_depth); ...@@ -135,7 +138,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
...@@ -349,6 +352,15 @@ GTEST_API_ AssertionResult AssertionFailure(); ...@@ -349,6 +352,15 @@ 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 TestCases, and
...@@ -359,7 +371,7 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg); ...@@ -359,7 +371,7 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
// 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:
...@@ -554,9 +566,8 @@ class GTEST_API_ TestResult { ...@@ -554,9 +566,8 @@ class GTEST_API_ TestResult {
// 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 // Returns the i-th test part result among all the results. i can range from 0
// from 0 to test_property_count() - 1. If i is not in that range, aborts // to total_part_count() - 1. If i is not in that range, aborts the program.
// 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
...@@ -679,6 +690,9 @@ class GTEST_API_ TestInfo { ...@@ -679,6 +690,9 @@ 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.
...@@ -699,10 +713,9 @@ class GTEST_API_ TestInfo { ...@@ -699,10 +713,9 @@ class GTEST_API_ TestInfo {
// Returns true iff this test will appear in the XML report. // Returns true iff 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.
...@@ -766,6 +779,7 @@ class GTEST_API_ TestInfo { ...@@ -766,6 +779,7 @@ class GTEST_API_ TestInfo {
bool is_disabled_; // True iff this test is disabled bool is_disabled_; // True iff 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
...@@ -990,6 +1004,18 @@ class Environment { ...@@ -990,6 +1004,18 @@ class Environment {
virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
}; };
#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 {
...@@ -1018,6 +1044,8 @@ class TestEventListener { ...@@ -1018,6 +1044,8 @@ class TestEventListener {
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.
...@@ -1291,9 +1319,9 @@ class GTEST_API_ UnitTest { ...@@ -1291,9 +1319,9 @@ class GTEST_API_ UnitTest {
// These classes and functions 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);
...@@ -1782,7 +1810,6 @@ template <typename T> ...@@ -1782,7 +1810,6 @@ template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> { class TestWithParam : public Test, public WithParamInterface<T> {
}; };
// Macros for indicating success/failure in test code. // Macros for indicating success/failure in test code.
// ADD_FAILURE unconditionally adds a failure to the current test. // ADD_FAILURE unconditionally adds a failure to the current test.
...@@ -1855,22 +1882,18 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1855,22 +1882,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
...@@ -1912,8 +1935,8 @@ class TestWithParam : public Test, public WithParamInterface<T> { ...@@ -1912,8 +1935,8 @@ 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.";
...@@ -2099,6 +2122,57 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ...@@ -2099,6 +2122,57 @@ 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)");
}
#if GTEST_HAS_GLOBAL_STRING
ScopedTrace(const char* file, int line, const ::string& message) {
PushTrace(file, line, message);
}
#endif
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
...@@ -2115,7 +2189,7 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ...@@ -2115,7 +2189,7 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
// Therefore, a SCOPED_TRACE() would (correctly) only affect the // Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread. // 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__, (message)) __FILE__, __LINE__, (message))
...@@ -2212,8 +2286,8 @@ bool StaticAssertTypeEq() { ...@@ -2212,8 +2286,8 @@ 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);
// } // }
#define TEST_F(test_fixture, test_name)\ #define TEST_F(test_fixture, test_name)\
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +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.
// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command // This file is AUTOMATICALLY GENERATED on 01/02/2018 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.
...@@ -35,10 +35,9 @@ ...@@ -35,10 +35,9 @@
#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:
...@@ -66,8 +65,6 @@ ...@@ -66,8 +65,6 @@
// We also define the EXPECT_* variations. // We also define the EXPECT_* variations.
// //
// For now we only support predicates whose arity is at most 5. // For now we only support predicates whose arity is at most 5.
// Please email googletestframework@googlegroups.com if you need
// support for higher arities.
// GTEST_ASSERT_ is the basic statement to which all of the assertions // GTEST_ASSERT_ is the basic statement to which all of the assertions
// in this file reduce. Don't use this in your code. // in this file reduce. Don't use this in your code.
...@@ -355,4 +352,6 @@ AssertionResult AssertPred5Helper(const char* pred_text, ...@@ -355,4 +352,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_
...@@ -191,7 +191,7 @@ class GTEST_API_ FilePath { ...@@ -191,7 +191,7 @@ class GTEST_API_ FilePath {
void Normalize(); void Normalize();
// Returns a pointer to the last occurence of a valid path separator in // Returns a pointer to the last ioccurrence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path // the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found. // separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const; const char* FindLastPathSeparator() const;
......
...@@ -95,7 +95,6 @@ template <typename T> ...@@ -95,7 +95,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
...@@ -151,53 +150,11 @@ class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { ...@@ -151,53 +150,11 @@ class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// 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.
// 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)");
}
#if GTEST_HAS_GLOBAL_STRING
ScopedTrace(const char* file, int line, const ::string& message) {
PushTrace(file, line, message);
}
#endif
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.
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 Wagner-Fischer algorithm. // Simple implementation of the WagnerFischer 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(
...@@ -650,7 +607,7 @@ class TypeParameterizedTest { ...@@ -650,7 +607,7 @@ class TypeParameterizedTest {
// 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,
CodeLocation code_location, const CodeLocation& code_location,
const char* case_name, const char* test_names, const char* case_name, const char* test_names,
int index) { int index) {
typedef typename Types::Head Type; typedef typename Types::Head Type;
...@@ -681,7 +638,7 @@ class TypeParameterizedTest { ...@@ -681,7 +638,7 @@ 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*/) {
return true; return true;
...@@ -727,7 +684,7 @@ class TypeParameterizedTestCase { ...@@ -727,7 +684,7 @@ class TypeParameterizedTestCase {
template <GTEST_TEMPLATE_ Fixture, typename Types> template <GTEST_TEMPLATE_ Fixture, typename Types>
class TypeParameterizedTestCase<Fixture, Templates0, Types> { class TypeParameterizedTestCase<Fixture, Templates0, Types> {
public: public:
static bool Register(const char* /*prefix*/, CodeLocation, static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestCasePState* /*state*/, const TypedTestCasePState* /*state*/,
const char* /*case_name*/, const char* /*test_names*/) { const char* /*case_name*/, const char* /*test_names*/) {
return true; return true;
......
...@@ -54,6 +54,9 @@ ...@@ -54,6 +54,9 @@
# define GTEST_OS_WINDOWS_PHONE 1 # define GTEST_OS_WINDOWS_PHONE 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
# define GTEST_OS_WINDOWS_RT 1 # define GTEST_OS_WINDOWS_RT 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
# define GTEST_OS_WINDOWS_PHONE 1
# define GTEST_OS_WINDOWS_TV_TITLE 1
# else # else
// WINAPI_FAMILY defined but no known partition matched. // WINAPI_FAMILY defined but no known partition matched.
// Default to desktop. // Default to desktop.
......
...@@ -73,11 +73,9 @@ ...@@ -73,11 +73,9 @@
// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
// are enabled. // are enabled.
// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define // is/isn't available
// ::string, which is different to std::string). // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::wstring
// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available
// is/isn't available (some systems define
// ::wstring, which is different to std::wstring).
// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
// expressions are/aren't available. // expressions are/aren't available.
// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
...@@ -178,7 +176,7 @@ ...@@ -178,7 +176,7 @@
// GTEST_HAS_POSIX_RE (see above) which users can // GTEST_HAS_POSIX_RE (see above) which users can
// define themselves. // define themselves.
// GTEST_USES_SIMPLE_RE - our own simple regex is used; // GTEST_USES_SIMPLE_RE - our own simple regex is used;
// the above two are mutually exclusive. // the above RE\b(s) are mutually exclusive.
// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
// Misc public macros // Misc public macros
...@@ -207,6 +205,7 @@ ...@@ -207,6 +205,7 @@
// //
// C++11 feature wrappers: // C++11 feature wrappers:
// //
// testing::internal::forward - portability wrapper for std::forward.
// testing::internal::move - portability wrapper for std::move. // testing::internal::move - portability wrapper for std::move.
// //
// Synchronization: // Synchronization:
...@@ -272,10 +271,12 @@ ...@@ -272,10 +271,12 @@
# include <TargetConditionals.h> # include <TargetConditionals.h>
#endif #endif
// Brings in the definition of HAS_GLOBAL_STRING. This must be done
// BEFORE we test HAS_GLOBAL_STRING.
#include <string> // NOLINT
#include <algorithm> // NOLINT #include <algorithm> // NOLINT
#include <iostream> // NOLINT #include <iostream> // NOLINT
#include <sstream> // NOLINT #include <sstream> // NOLINT
#include <string> // NOLINT
#include <utility> #include <utility>
#include <vector> // NOLINT #include <vector> // NOLINT
...@@ -611,8 +612,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; ...@@ -611,8 +612,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// //
// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
// to your compiler flags. // to your compiler flags.
#define GTEST_HAS_PTHREAD \ #define GTEST_HAS_PTHREAD \
(GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA) GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA)
#endif // GTEST_HAS_PTHREAD #endif // GTEST_HAS_PTHREAD
...@@ -806,9 +807,9 @@ using ::std::tuple_size; ...@@ -806,9 +807,9 @@ using ::std::tuple_size;
// Google Test does not support death tests for VC 7.1 and earlier as // Google Test does not support death tests for VC 7.1 and earlier as
// abort() in a VC 7.1 application compiled as GUI in debug config // abort() in a VC 7.1 application compiled as GUI in debug config
// pops up a dialog window that cannot be suppressed programmatically. // pops up a dialog window that cannot be suppressed programmatically.
#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
(GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \
(GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NETBSD) GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NETBSD)
# define GTEST_HAS_DEATH_TEST 1 # define GTEST_HAS_DEATH_TEST 1
...@@ -824,9 +825,10 @@ using ::std::tuple_size; ...@@ -824,9 +825,10 @@ using ::std::tuple_size;
# define GTEST_HAS_TYPED_TEST_P 1 # define GTEST_HAS_TYPED_TEST_P 1
#endif #endif
// Determines whether to support Combine(). // Determines whether to support Combine(). This only makes sense when
// The implementation doesn't work on Sun Studio since it doesn't // value-parameterized tests are enabled. The implementation doesn't
// understand templated conversion operators. // work on Sun Studio since it doesn't understand templated conversion
// operators.
#if (GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_) && !defined(__SUNPRO_CC) #if (GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_) && !defined(__SUNPRO_CC)
# define GTEST_HAS_COMBINE 1 # define GTEST_HAS_COMBINE 1
#endif #endif
...@@ -980,7 +982,7 @@ using ::std::tuple_size; ...@@ -980,7 +982,7 @@ using ::std::tuple_size;
#endif #endif
// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) #if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
# define GTEST_HAS_CXXABI_H_ 1 # define GTEST_HAS_CXXABI_H_ 1
#else #else
# define GTEST_HAS_CXXABI_H_ 0 # define GTEST_HAS_CXXABI_H_ 0
...@@ -1126,6 +1128,16 @@ struct StaticAssertTypeEqHelper<T, T> { ...@@ -1126,6 +1128,16 @@ struct StaticAssertTypeEqHelper<T, T> {
enum { value = true }; enum { value = true };
}; };
// Same as std::is_same<>.
template <typename T, typename U>
struct IsSame {
enum { value = false };
};
template <typename T>
struct IsSame<T, T> {
enum { value = true };
};
// Evaluates to the number of elements in 'array'. // Evaluates to the number of elements in 'array'.
#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
...@@ -1189,6 +1201,10 @@ class scoped_ptr { ...@@ -1189,6 +1201,10 @@ class scoped_ptr {
// Defines RE. // Defines RE.
#if GTEST_USES_PCRE
using ::RE;
#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
// Regular Expression syntax. // Regular Expression syntax.
class GTEST_API_ RE { class GTEST_API_ RE {
...@@ -1200,11 +1216,11 @@ class GTEST_API_ RE { ...@@ -1200,11 +1216,11 @@ class GTEST_API_ RE {
// Constructs an RE from a string. // Constructs an RE from a string.
RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
#if GTEST_HAS_GLOBAL_STRING # if GTEST_HAS_GLOBAL_STRING
RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT
#endif // GTEST_HAS_GLOBAL_STRING # endif // GTEST_HAS_GLOBAL_STRING
RE(const char* regex) { Init(regex); } // NOLINT RE(const char* regex) { Init(regex); } // NOLINT
~RE(); ~RE();
...@@ -1226,7 +1242,7 @@ class GTEST_API_ RE { ...@@ -1226,7 +1242,7 @@ class GTEST_API_ RE {
return PartialMatch(str.c_str(), re); return PartialMatch(str.c_str(), re);
} }
#if GTEST_HAS_GLOBAL_STRING # if GTEST_HAS_GLOBAL_STRING
static bool FullMatch(const ::string& str, const RE& re) { static bool FullMatch(const ::string& str, const RE& re) {
return FullMatch(str.c_str(), re); return FullMatch(str.c_str(), re);
...@@ -1235,7 +1251,7 @@ class GTEST_API_ RE { ...@@ -1235,7 +1251,7 @@ class GTEST_API_ RE {
return PartialMatch(str.c_str(), re); return PartialMatch(str.c_str(), re);
} }
#endif // GTEST_HAS_GLOBAL_STRING # endif // GTEST_HAS_GLOBAL_STRING
static bool FullMatch(const char* str, const RE& re); static bool FullMatch(const char* str, const RE& re);
static bool PartialMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re);
...@@ -1249,20 +1265,22 @@ class GTEST_API_ RE { ...@@ -1249,20 +1265,22 @@ class GTEST_API_ RE {
const char* pattern_; const char* pattern_;
bool is_valid_; bool is_valid_;
#if GTEST_USES_POSIX_RE # if GTEST_USES_POSIX_RE
regex_t full_regex_; // For FullMatch(). regex_t full_regex_; // For FullMatch().
regex_t partial_regex_; // For PartialMatch(). regex_t partial_regex_; // For PartialMatch().
#else // GTEST_USES_SIMPLE_RE # else // GTEST_USES_SIMPLE_RE
const char* full_pattern_; // For FullMatch(); const char* full_pattern_; // For FullMatch();
#endif # endif
GTEST_DISALLOW_ASSIGN_(RE); GTEST_DISALLOW_ASSIGN_(RE);
}; };
#endif // GTEST_USES_PCRE
// Formats a source file path and a line number as they would appear // Formats a source file path and a line number as they would appear
// in an error message from the compiler used to compile this code. // in an error message from the compiler used to compile this code.
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
...@@ -1349,12 +1367,23 @@ inline void FlushInfoLog() { fflush(NULL); } ...@@ -1349,12 +1367,23 @@ inline void FlushInfoLog() { fflush(NULL); }
<< gtest_error << gtest_error
#if GTEST_HAS_STD_MOVE_ #if GTEST_HAS_STD_MOVE_
using std::forward;
using std::move; using std::move;
template <typename T>
struct RvalueRef {
typedef T&& type;
};
#else // GTEST_HAS_STD_MOVE_ #else // GTEST_HAS_STD_MOVE_
template <typename T> template <typename T>
const T& move(const T& t) { const T& move(const T& t) {
return t; return t;
} }
template <typename T>
struct RvalueRef {
typedef const T& type;
};
#endif // GTEST_HAS_STD_MOVE_ #endif // GTEST_HAS_STD_MOVE_
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
...@@ -1455,7 +1484,6 @@ GTEST_API_ void CaptureStderr(); ...@@ -1455,7 +1484,6 @@ GTEST_API_ void CaptureStderr();
GTEST_API_ std::string GetCapturedStderr(); GTEST_API_ std::string GetCapturedStderr();
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// Returns the size (in bytes) of a file. // Returns the size (in bytes) of a file.
GTEST_API_ size_t GetFileSize(FILE* file); GTEST_API_ size_t GetFileSize(FILE* file);
......
...@@ -73,7 +73,7 @@ namespace testing { ...@@ -73,7 +73,7 @@ namespace testing {
// Constants. // Constants.
// The default death test style. // The default death test style.
static const char kDefaultDeathTestStyle[] = "fast"; static const char kDefaultDeathTestStyle[] = "threadsafe";
GTEST_DEFINE_string_( GTEST_DEFINE_string_(
death_test_style, death_test_style,
...@@ -555,7 +555,13 @@ bool DeathTestImpl::Passed(bool status_ok) { ...@@ -555,7 +555,13 @@ bool DeathTestImpl::Passed(bool status_ok) {
break; break;
case DIED: case DIED:
if (status_ok) { if (status_ok) {
# if GTEST_USES_PCRE
// PCRE regexes support embedded NULs.
// GTEST_USES_PCRE is defined only in google3 mode
const bool matched = RE::PartialMatch(error_message, *regex());
# else
const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
# endif // GTEST_USES_PCRE
if (matched) { if (matched) {
success = true; success = true;
} else { } else {
......
...@@ -128,7 +128,7 @@ FilePath FilePath::RemoveExtension(const char* extension) const { ...@@ -128,7 +128,7 @@ FilePath FilePath::RemoveExtension(const char* extension) const {
return *this; return *this;
} }
// Returns a pointer to the last occurence of a valid path separator in // Returns a pointer to the last occurrence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path // the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found. // separators. Returns NULL if no path separator was found.
const char* FilePath::FindLastPathSeparator() const { const char* FilePath::FindLastPathSeparator() const {
......
...@@ -86,6 +86,7 @@ const char kFilterFlag[] = "filter"; ...@@ -86,6 +86,7 @@ const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests"; const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output"; const char kOutputFlag[] = "output";
const char kPrintTimeFlag[] = "print_time"; const char kPrintTimeFlag[] = "print_time";
const char kPrintUTF8Flag[] = "print_utf8";
const char kRandomSeedFlag[] = "random_seed"; const char kRandomSeedFlag[] = "random_seed";
const char kRepeatFlag[] = "repeat"; const char kRepeatFlag[] = "repeat";
const char kShuffleFlag[] = "shuffle"; const char kShuffleFlag[] = "shuffle";
...@@ -166,6 +167,7 @@ class GTestFlagSaver { ...@@ -166,6 +167,7 @@ class GTestFlagSaver {
list_tests_ = GTEST_FLAG(list_tests); list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output); output_ = GTEST_FLAG(output);
print_time_ = GTEST_FLAG(print_time); print_time_ = GTEST_FLAG(print_time);
print_utf8_ = GTEST_FLAG(print_utf8);
random_seed_ = GTEST_FLAG(random_seed); random_seed_ = GTEST_FLAG(random_seed);
repeat_ = GTEST_FLAG(repeat); repeat_ = GTEST_FLAG(repeat);
shuffle_ = GTEST_FLAG(shuffle); shuffle_ = GTEST_FLAG(shuffle);
...@@ -187,6 +189,7 @@ class GTestFlagSaver { ...@@ -187,6 +189,7 @@ class GTestFlagSaver {
GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_; GTEST_FLAG(output) = output_;
GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(print_utf8) = print_utf8_;
GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(random_seed) = random_seed_;
GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(repeat) = repeat_;
GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(shuffle) = shuffle_;
...@@ -208,6 +211,7 @@ class GTestFlagSaver { ...@@ -208,6 +211,7 @@ class GTestFlagSaver {
bool list_tests_; bool list_tests_;
std::string output_; std::string output_;
bool print_time_; bool print_time_;
bool print_utf8_;
internal::Int32 random_seed_; internal::Int32 random_seed_;
internal::Int32 repeat_; internal::Int32 repeat_;
bool shuffle_; bool shuffle_;
......
...@@ -43,12 +43,13 @@ ...@@ -43,12 +43,13 @@
// defines Foo. // defines Foo.
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h> #include <stdio.h>
#include <cctype>
#include <cwchar> #include <cwchar>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
namespace testing { namespace testing {
...@@ -123,7 +124,7 @@ namespace internal { ...@@ -123,7 +124,7 @@ namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one // Depending on the value of a char (or wchar_t), we print it in one
// of three formats: // of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a hexadecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n'). // - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat { enum CharFormat {
kAsIs, kAsIs,
...@@ -230,7 +231,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) { ...@@ -230,7 +231,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
return; return;
*os << " (" << static_cast<int>(c); *os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal, // For more convenience, we print c's code again in hexadecimal,
// unless c was already printed in the form '\x##' or the code is in // unless c was already printed in the form '\x##' or the code is in
// [1, 9]. // [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) { if (format == kHexEscape || (1 <= c && c <= 9)) {
...@@ -262,11 +263,12 @@ template <typename CharType> ...@@ -262,11 +263,12 @@ template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
static void PrintCharsAsStringTo( static CharFormat PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) { const CharType* begin, size_t len, ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin; *os << kQuoteBegin;
bool is_previous_hex = false; bool is_previous_hex = false;
CharFormat print_format = kAsIs;
for (size_t index = 0; index < len; ++index) { for (size_t index = 0; index < len; ++index) {
const CharType cur = begin[index]; const CharType cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) { if (is_previous_hex && IsXDigit(cur)) {
...@@ -276,8 +278,13 @@ static void PrintCharsAsStringTo( ...@@ -276,8 +278,13 @@ static void PrintCharsAsStringTo(
*os << "\" " << kQuoteBegin; *os << "\" " << kQuoteBegin;
} }
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
// Remember if any characters required hex escaping.
if (is_previous_hex) {
print_format = kHexEscape;
}
} }
*os << "\""; *os << "\"";
return print_format;
} }
// Prints a (const) char/wchar_t array of 'len' elements, starting at address // Prints a (const) char/wchar_t array of 'len' elements, starting at address
...@@ -347,15 +354,88 @@ void PrintTo(const wchar_t* s, ostream* os) { ...@@ -347,15 +354,88 @@ void PrintTo(const wchar_t* s, ostream* os) {
} }
#endif // wchar_t is native #endif // wchar_t is native
namespace {
bool ContainsUnprintableControlCodes(const char* str, size_t length) {
for (size_t i = 0; i < length; i++) {
char ch = *str++;
if (std::iscntrl(ch)) {
switch (ch) {
case '\t':
case '\n':
case '\r':
break;
default:
return true;
}
}
}
return false;
}
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
bool IsValidUTF8(const char* str, size_t length) {
const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
for (size_t i = 0; i < length;) {
unsigned char lead = s[i++];
if (lead <= 0x7f) {
continue; // single-byte character (ASCII) 0..7F
}
if (lead < 0xc2) {
return false; // trail byte or non-shortest form
} else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
++i; // 2-byte character
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
IsUTF8TrailByte(s[i]) &&
IsUTF8TrailByte(s[i + 1]) &&
// check for non-shortest form and surrogate
(lead != 0xe0 || s[i] >= 0xa0) &&
(lead != 0xed || s[i] < 0xa0)) {
i += 2; // 3-byte character
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
IsUTF8TrailByte(s[i]) &&
IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 2]) &&
// check for non-shortest form
(lead != 0xf0 || s[i] >= 0x90) &&
(lead != 0xf4 || s[i] < 0x90)) {
i += 3; // 4-byte character
} else {
return false;
}
}
return true;
}
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
if (!ContainsUnprintableControlCodes(str, length) &&
IsValidUTF8(str, length)) {
*os << "\n As Text: \"" << str << "\"";
}
}
} // anonymous namespace
// Prints a ::string object. // Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) { void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os); if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
if (GTEST_FLAG(print_utf8)) {
ConditionalPrintAsText(s.data(), s.size(), os);
}
}
} }
#endif // GTEST_HAS_GLOBAL_STRING #endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) { void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os); if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
if (GTEST_FLAG(print_utf8)) {
ConditionalPrintAsText(s.data(), s.size(), os);
}
}
} }
// Prints a ::wstring object. // Prints a ::wstring object.
......
...@@ -252,6 +252,12 @@ GTEST_DEFINE_bool_( ...@@ -252,6 +252,12 @@ GTEST_DEFINE_bool_(
"True iff " GTEST_NAME_ "True iff " GTEST_NAME_
" should display elapsed time in text output."); " should display elapsed time in text output.");
GTEST_DEFINE_bool_(
print_utf8,
internal::BoolFromGTestEnv("print_utf8", true),
"True iff " GTEST_NAME_
" prints UTF8 characters as text.");
GTEST_DEFINE_int32_( GTEST_DEFINE_int32_(
random_seed, random_seed,
internal::Int32FromGTestEnv("random_seed", 0), internal::Int32FromGTestEnv("random_seed", 0),
...@@ -293,7 +299,7 @@ GTEST_DEFINE_bool_( ...@@ -293,7 +299,7 @@ GTEST_DEFINE_bool_(
internal::BoolFromGTestEnv("throw_on_failure", false), internal::BoolFromGTestEnv("throw_on_failure", false),
"When this flag is specified, a failed assertion will throw an exception " "When this flag is specified, a failed assertion will throw an exception "
"if exceptions are enabled or exit the program with a non-zero code " "if exceptions are enabled or exit the program with a non-zero code "
"otherwise."); "otherwise. For use with an external test framework.");
#if GTEST_USE_OWN_FLAGFILE_FLAG_ #if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DEFINE_string_( GTEST_DEFINE_string_(
...@@ -1661,7 +1667,7 @@ namespace { ...@@ -1661,7 +1667,7 @@ namespace {
AssertionResult HRESULTFailureHelper(const char* expr, AssertionResult HRESULTFailureHelper(const char* expr,
const char* expected, const char* expected,
long hr) { // NOLINT long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
// Windows CE doesn't support FormatMessage. // Windows CE doesn't support FormatMessage.
const char error_text[] = ""; const char error_text[] = "";
...@@ -1718,7 +1724,7 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT ...@@ -1718,7 +1724,7 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
// Utility functions for encoding Unicode text (wide strings) in // Utility functions for encoding Unicode text (wide strings) in
// UTF-8. // UTF-8.
// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
// like this: // like this:
// //
// Code-point length Encoding // Code-point length Encoding
...@@ -2435,6 +2441,8 @@ Result HandleExceptionsInMethodIfSupported( ...@@ -2435,6 +2441,8 @@ Result HandleExceptionsInMethodIfSupported(
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
try { try {
return HandleSehExceptionsInMethodIfSupported(object, method, location); return HandleSehExceptionsInMethodIfSupported(object, method, location);
} catch (const AssertionException&) { // NOLINT
// This failure was reported already.
} catch (const internal::GoogleTestFailureException&) { // NOLINT } catch (const internal::GoogleTestFailureException&) { // NOLINT
// This exception type can only be thrown by a failed Google // This exception type can only be thrown by a failed Google
// Test assertion with the intention of letting another testing // Test assertion with the intention of letting another testing
...@@ -3841,26 +3849,6 @@ void StreamingListener::SocketWriter::MakeConnection() { ...@@ -3841,26 +3849,6 @@ void StreamingListener::SocketWriter::MakeConnection() {
// End of class Streaming Listener // End of class Streaming Listener
#endif // GTEST_CAN_STREAM_RESULTS__ #endif // GTEST_CAN_STREAM_RESULTS__
// Class ScopedTrace
// Pushes the given source file location and message onto a per-thread
// trace stack maintained by Google Test.
void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
TraceInfo trace;
trace.file = file;
trace.line = line;
trace.message.swap(message);
UnitTest::GetInstance()->PushGTestTrace(trace);
}
// Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace()
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace();
}
// class OsStackTraceGetter // class OsStackTraceGetter
const char* const OsStackTraceGetterInterface::kElidedFramesMarker = const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
...@@ -4839,10 +4827,11 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { ...@@ -4839,10 +4827,11 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
matches_filter; matches_filter;
const bool is_selected = is_runnable && const bool is_in_another_shard =
(shard_tests == IGNORE_SHARDING_PROTOCOL || shard_tests != IGNORE_SHARDING_PROTOCOL &&
ShouldRunTestOnShard(total_shards, shard_index, !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
num_runnable_tests)); test_info->is_in_another_shard_ = is_in_another_shard;
const bool is_selected = is_runnable && !is_in_another_shard;
num_runnable_tests += is_runnable; num_runnable_tests += is_runnable;
num_selected_tests += is_selected; num_selected_tests += is_selected;
...@@ -5220,7 +5209,8 @@ static const char kColorEncodedHelpMessage[] = ...@@ -5220,7 +5209,8 @@ static const char kColorEncodedHelpMessage[] =
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\n" " Turn assertion failures into debugger break-points.\n"
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
" Turn assertion failures into C++ exceptions.\n" " Turn assertion failures into C++ exceptions for use by an external\n"
" test framework.\n"
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
" Do not report exceptions as test failures. Instead, allow them\n" " Do not report exceptions as test failures. Instead, allow them\n"
" to crash the program or throw a pop-up (on Windows).\n" " to crash the program or throw a pop-up (on Windows).\n"
...@@ -5255,6 +5245,7 @@ static bool ParseGoogleTestFlag(const char* const arg) { ...@@ -5255,6 +5245,7 @@ static bool ParseGoogleTestFlag(const char* const arg) {
ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) || ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) || ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) || ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) || ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) || ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) || ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
...@@ -5432,4 +5423,23 @@ std::string TempDir() { ...@@ -5432,4 +5423,23 @@ std::string TempDir() {
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} }
// Class ScopedTrace
// Pushes the given source file location and message onto a per-thread
// trace stack maintained by Google Test.
void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
internal::TraceInfo trace;
trace.file = file;
trace.line = line;
trace.message.swap(message);
UnitTest::GetInstance()->PushGTestTrace(trace);
}
// Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace()
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace();
}
} // namespace testing } // namespace testing
...@@ -26,9 +26,9 @@ ...@@ -26,9 +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.
//
#include <stdio.h> #include <stdio.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) { GTEST_API_ int main(int argc, char **argv) {
......
# Copyright 2017 Google Inc. # Copyright 2017 Google Inc.
# All Rights Reserved. # All Rights Reserved.
# #
# #
...@@ -119,3 +119,252 @@ cc_test( ...@@ -119,3 +119,252 @@ cc_test(
"//:gtest", "//:gtest",
], ],
) )
# Py tests
py_library(
name = "gtest_test_utils",
testonly = 1,
srcs = ["gtest_test_utils.py"],
)
cc_binary(
name = "gtest_help_test_",
testonly = 1,
srcs = ["gtest_help_test_.cc"],
deps = ["//:gtest_main"],
)
py_test(
name = "gtest_help_test",
size = "small",
srcs = ["gtest_help_test.py"],
data = [":gtest_help_test_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_output_test_",
testonly = 1,
srcs = ["gtest_output_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_output_test",
size = "small",
srcs = ["gtest_output_test.py"],
data = [
"gtest_output_test_golden_lin.txt",
":gtest_output_test_",
],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_color_test_",
testonly = 1,
srcs = ["gtest_color_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_color_test",
size = "small",
srcs = ["gtest_color_test.py"],
data = [":gtest_color_test_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_env_var_test_",
testonly = 1,
srcs = ["gtest_env_var_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_env_var_test",
size = "small",
srcs = ["gtest_env_var_test.py"],
data = [":gtest_env_var_test_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_filter_unittest_",
testonly = 1,
srcs = ["gtest_filter_unittest_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_filter_unittest",
size = "small",
srcs = ["gtest_filter_unittest.py"],
data = [":gtest_filter_unittest_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_break_on_failure_unittest_",
testonly = 1,
srcs = ["gtest_break_on_failure_unittest_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_break_on_failure_unittest",
size = "small",
srcs = ["gtest_break_on_failure_unittest.py"],
data = [":gtest_break_on_failure_unittest_"],
deps = [":gtest_test_utils"],
)
cc_test(
name = "gtest_assert_by_exception_test",
size = "small",
srcs = ["gtest_assert_by_exception_test.cc"],
deps = ["//:gtest"],
)
cc_binary(
name = "gtest_throw_on_failure_test_",
testonly = 1,
srcs = ["gtest_throw_on_failure_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_throw_on_failure_test",
size = "small",
srcs = ["gtest_throw_on_failure_test.py"],
data = [":gtest_throw_on_failure_test_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_list_tests_unittest_",
testonly = 1,
srcs = ["gtest_list_tests_unittest_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_list_tests_unittest",
size = "small",
srcs = ["gtest_list_tests_unittest.py"],
data = [":gtest_list_tests_unittest_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_shuffle_test_",
srcs = ["gtest_shuffle_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_shuffle_test",
size = "small",
srcs = ["gtest_shuffle_test.py"],
data = [":gtest_shuffle_test_"],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_catch_exceptions_no_ex_test_",
testonly = 1,
srcs = ["gtest_catch_exceptions_test_.cc"],
deps = ["//:gtest_main"],
)
cc_binary(
name = "gtest_catch_exceptions_ex_test_",
testonly = 1,
srcs = ["gtest_catch_exceptions_test_.cc"],
copts = ["-fexceptions"],
deps = ["//:gtest_main"],
)
py_test(
name = "gtest_catch_exceptions_test",
size = "small",
srcs = ["gtest_catch_exceptions_test.py"],
data = [
":gtest_catch_exceptions_ex_test_",
":gtest_catch_exceptions_no_ex_test_",
],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_xml_output_unittest_",
testonly = 1,
srcs = ["gtest_xml_output_unittest_.cc"],
deps = ["//:gtest"],
)
cc_test(
name = "gtest_no_test_unittest",
size = "small",
srcs = ["gtest_no_test_unittest.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_xml_output_unittest",
size = "small",
srcs = [
"gtest_xml_output_unittest.py",
"gtest_xml_test_utils.py",
],
data = [
# We invoke gtest_no_test_unittest to verify the XML output
# when the test program contains no test definition.
":gtest_no_test_unittest",
":gtest_xml_output_unittest_",
],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_xml_outfile1_test_",
testonly = 1,
srcs = ["gtest_xml_outfile1_test_.cc"],
deps = ["//:gtest_main"],
)
cc_binary(
name = "gtest_xml_outfile2_test_",
testonly = 1,
srcs = ["gtest_xml_outfile2_test_.cc"],
deps = ["//:gtest_main"],
)
py_test(
name = "gtest_xml_outfiles_test",
size = "small",
srcs = [
"gtest_xml_outfiles_test.py",
"gtest_xml_test_utils.py",
],
data = [
":gtest_xml_outfile1_test_",
":gtest_xml_outfile2_test_",
],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "gtest_uninitialized_test_",
testonly = 1,
srcs = ["gtest_uninitialized_test_.cc"],
deps = ["//:gtest"],
)
py_test(
name = "gtest_uninitialized_test",
size = "medium",
srcs = ["gtest_uninitialized_test.py"],
data = [":gtest_uninitialized_test_"],
deps = [":gtest_test_utils"],
)
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