Merge branch 'master' into fix-argc

This commit is contained in:
Conor Burgess 2018-02-12 17:35:07 +00:00 committed by GitHub
commit f11a8f9131
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
66 changed files with 1319 additions and 388 deletions

View File

@ -46,6 +46,12 @@ config_setting(
values = {"cpu": "x64_windows_msvc"},
)
config_setting(
name = "has_absl",
values = {"define": "absl=1"},
)
# Google Test including Google Mock
cc_library(
name = "gtest",
@ -88,6 +94,21 @@ cc_library(
"-pthread",
],
}),
defines = select ({
":has_absl": [
"GTEST_HAS_ABSL=1",
],
"//conditions:default": [],
}
),
deps = select ({
":has_absl": [
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/strings"
],
"//conditions:default": [],
}
)
)
cc_library(

View File

@ -103,7 +103,7 @@ package (as described below):
### Windows Requirements ###
* Microsoft Visual C++ 2010 or newer
* Microsoft Visual C++ 2015 or newer
### Cygwin Requirements ###

View File

@ -1 +1,8 @@
workspace(name = "com_google_googletest")
# Abseil
http_archive(
name = "com_google_absl",
urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
strip_prefix = "abseil-cpp-master",
)

View File

@ -15,25 +15,11 @@ environment:
- compiler: msvc-14-seh
generator: "Visual Studio 14 2015"
enabled_on_pr: yes
- compiler: msvc-14-seh
generator: "Visual Studio 14 2015 Win64"
- compiler: msvc-12-seh
generator: "Visual Studio 12 2013"
- compiler: msvc-12-seh
generator: "Visual Studio 12 2013 Win64"
- compiler: msvc-11-seh
generator: "Visual Studio 11 2012"
- compiler: msvc-11-seh
generator: "Visual Studio 11 2012 Win64"
- compiler: msvc-10-seh
generator: "Visual Studio 10 2010"
- compiler: gcc-5.3.0-posix
generator: "MinGW Makefiles"
cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin'

View File

@ -33,3 +33,4 @@ set -e
bazel build --curses=no //...:all
bazel test --curses=no //...:all
bazel test --curses=no //...:all --define absl=1

View File

@ -88,16 +88,23 @@ endif()
# Google Mock libraries. We build them using more strict warnings than what
# are used for other targets, to ensure that Google Mock can be compiled by
# a user aggressive about warnings.
cxx_library(gmock
if (MSVC)
cxx_library(gmock
"${cxx_strict}"
"${gtest_dir}/src/gtest-all.cc"
src/gmock-all.cc)
cxx_library(gmock_main
cxx_library(gmock_main
"${cxx_strict}"
"${gtest_dir}/src/gtest-all.cc"
src/gmock-all.cc
src/gmock_main.cc)
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock gtest)
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main gmock)
endif()
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
@ -177,13 +184,14 @@ if (gmock_build_tests)
############################################################
# C++ tests built with non-standard compiler flags.
if (MSVC)
cxx_library(gmock_main_no_exception "${cxx_no_exception}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010.
if (MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010.
# Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
# conflict with our own definitions. Therefore using our own tuple does not
# work on those compilers.
@ -193,7 +201,16 @@ if (gmock_build_tests)
cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}"
gmock_main_use_own_tuple test/gmock-spec-builders_test.cc)
endif()
else()
cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc)
target_link_libraries(gmock_main_no_exception gmock)
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc)
target_link_libraries(gmock_main_no_rtti gmock)
cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" src/gmock_main.cc)
target_link_libraries(gmock_main_use_own_tuple gmock)
endif()
cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
gmock_main_no_exception test/gmock-more-actions_test.cc)

View File

@ -1231,7 +1231,7 @@ that references the implementation object dies, the implementation
object will be deleted.
Therefore, if you have some complex matcher that you want to use again
and again, there is no need to build it everytime. Just assign it to a
and again, there is no need to build it every time. Just assign it to a
matcher variable and use that variable repeatedly! For example,
```
@ -1403,7 +1403,7 @@ edge from node A to node B wherever A must occur before B, we can get
a DAG. We use the term "sequence" to mean a directed path in this
DAG. Now, if we decompose the DAG into sequences, we just need to know
which sequences each `EXPECT_CALL()` belongs to in order to be able to
reconstruct the orginal DAG.
reconstruct the original DAG.
So, to specify the partial order on the expectations we need to do two
things: first to define some `Sequence` objects, and then for each
@ -2182,7 +2182,7 @@ the implementation object dies, the implementation object will be
deleted.
If you have some complex action that you want to use again and again,
you may not have to build it from scratch everytime. If the action
you may not have to build it from scratch every time. If the action
doesn't have an internal state (i.e. if it always does the same thing
no matter how many times it has been called), you can assign it to an
action variable and use that variable repeatedly. For example:

View File

@ -47,10 +47,9 @@
#include <string>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#if GTEST_HAS_STD_INITIALIZER_LIST_
# include <initializer_list> // NOLINT -- must be after gtest.h
@ -1551,7 +1550,7 @@ class BothOfMatcherImpl : public MatcherInterface<T> {
// MatcherList provides mechanisms for storing a variable number of matchers in
// a list structure (ListType) and creating a combining matcher from such a
// list.
// The template is defined recursively using the following template paramters:
// The template is defined recursively using the following template parameters:
// * kSize is the length of the MatcherList.
// * Head is the type of the first matcher of the list.
// * Tail denotes the types of the remaining matchers of the list.
@ -2380,7 +2379,7 @@ class ResultOfMatcher {
private:
// Functors often define operator() as non-const method even though
// they are actualy stateless. But we need to use them even when
// they are actually stateless. But we need to use them even when
// 'this' is a const pointer. It's the user's responsibility not to
// use stateful callables with ResultOf(), which does't guarantee
// how many times the callable will be invoked.

View File

@ -53,6 +53,22 @@ MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
return false;
}
// Define a matcher that matches a value that evaluates in boolean
// context to true. Useful for types that define "explicit operator
// bool" operators and so can't be compared for equality with true
// and false.
MATCHER(IsTrue, negation ? "is false" : "is true") {
return static_cast<bool>(arg);
}
// Define a matcher that matches a value that evaluates in boolean
// context to false. Useful for types that define "explicit operator
// bool" operators and so can't be compared for equality with true
// and false.
MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
} // namespace testing
#endif // GMOCK_GMOCK_MORE_MATCHERS_H_

View File

@ -65,11 +65,6 @@
#include <sstream>
#include <string>
#include <vector>
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept> // NOLINT
#endif
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-matchers.h"
@ -77,6 +72,10 @@
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept> // NOLINT
#endif
namespace testing {
// An abstract handle of an expectation.

View File

@ -59,8 +59,8 @@
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-generated-actions.h"
#include "gmock/gmock-generated-function-mockers.h"
#include "gmock/gmock-generated-nice-strict.h"
#include "gmock/gmock-generated-matchers.h"
#include "gmock/gmock-generated-nice-strict.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-actions.h"
#include "gmock/gmock-more-matchers.h"

View File

@ -90,42 +90,48 @@ struct MatcherTuple< ::testing::tuple<A1, A2, A3> > {
template <typename A1, typename A2, typename A3, typename A4>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>,
Matcher<A4> > type;
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5> > type;
Matcher<A5> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5>, Matcher<A6> > type;
Matcher<A5>, Matcher<A6> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5>, Matcher<A6>, Matcher<A7> > type;
Matcher<A5>, Matcher<A6>, Matcher<A7> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type;
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9>
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type;
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>,
Matcher<A9> >
type;
};
template <typename A1, typename A2, typename A3, typename A4, typename A5,
@ -133,8 +139,9 @@ template <typename A1, typename A2, typename A3, typename A4, typename A5,
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
A10> > {
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>,
Matcher<A10> > type;
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>,
Matcher<A9>, Matcher<A10> >
type;
};
// Template struct Function<F>, where F must be a function type, contains

View File

@ -41,7 +41,6 @@
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gmock/internal/gmock-generated-internal-utils.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
@ -49,11 +48,15 @@
namespace testing {
namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields);
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name);
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
// PointeeOf<Pointer>::type is the type of a value pointed to by a
// Pointer, which can be either a smart pointer or a raw pointer. The
@ -503,8 +506,38 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
template <bool kValue>
struct BooleanConstant {};
// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
// reduce code size.
void IllegalDoDefault(const char* file, int line);
#if GTEST_LANG_CXX11
// Helper types for Apply() below.
template <size_t... Is> struct int_pack { typedef int_pack type; };
template <class Pack, size_t I> struct append;
template <size_t... Is, size_t I>
struct append<int_pack<Is...>, I> : int_pack<Is..., I> {};
template <size_t C>
struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {};
template <> struct make_int_pack<0> : int_pack<> {};
template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
}
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args)
-> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
make_int_pack<std::tuple_size<Tuple>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
make_int_pack<std::tuple_size<Tuple>::value>());
}
#endif
} // namespace internal
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_

View File

@ -50,15 +50,11 @@
// portability utilities to Google Test's gtest-port.h instead of
// here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock.
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h"
#include "gmock/internal/custom/gmock-port.h"
// To avoid conditional compilation everywhere, we make it
// gmock-port.h's responsibility to #include the header implementing
// tr1/tuple. gmock-port.h does this via gtest-port.h, which is
// guaranteed to pull in the tuple header.
// For MS Visual C++, check the compiler version. At least VS 2003 is
// required to compile Google Mock.
#if defined(_MSC_VER) && _MSC_VER < 1310
@ -72,18 +68,18 @@
#if !defined(GMOCK_DECLARE_bool_)
// Macros for declaring flags.
#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
#define GMOCK_DECLARE_int32_(name) \
# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
# define GMOCK_DECLARE_int32_(name) \
extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
#define GMOCK_DECLARE_string_(name) \
# define GMOCK_DECLARE_string_(name) \
extern GTEST_API_ ::std::string GMOCK_FLAG(name)
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
# define GMOCK_DEFINE_bool_(name, default_val, doc) \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
# define GMOCK_DEFINE_int32_(name, default_val, doc) \
GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
#define GMOCK_DEFINE_string_(name, default_val, doc) \
# define GMOCK_DEFINE_string_(name, default_val, doc) \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
#endif // !defined(GMOCK_DECLARE_bool_)

View File

@ -338,7 +338,7 @@ class Class(_GenericDeclaration):
# TODO(nnorwitz): handle namespaces, etc.
if self.bases:
for token_list in self.bases:
# TODO(nnorwitz): bases are tokens, do name comparision.
# TODO(nnorwitz): bases are tokens, do name comparison.
for token in token_list:
if token.name == node.name:
return True
@ -381,7 +381,7 @@ class Function(_GenericDeclaration):
def Requires(self, node):
if self.parameters:
# TODO(nnorwitz): parameters are tokens, do name comparision.
# TODO(nnorwitz): parameters are tokens, do name comparison.
for p in self.parameters:
if p.name == node.name:
return True
@ -858,7 +858,7 @@ class AstBuilder(object):
last_token = self._GetNextToken()
return tokens, last_token
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary.
def _IgnoreUpTo(self, token_type, token):
unused_tokens = self._GetTokensUpTo(token_type, token)

View File

@ -53,3 +53,71 @@ cc_test(
}),
deps = ["//:gtest"],
)
# Py tests
py_library(
name = "gmock_test_utils",
testonly = 1,
srcs = ["gmock_test_utils.py"],
)
cc_binary(
name = "gmock_leak_test_",
testonly = 1,
srcs = ["gmock_leak_test_.cc"],
deps = [
"//:gtest_main",
],
)
py_test(
name = "gmock_leak_test",
size = "medium",
srcs = ["gmock_leak_test.py"],
data = [
":gmock_leak_test_",
":gmock_test_utils",
],
)
cc_test(
name = "gmock_link_test",
size = "small",
srcs = [
"gmock_link2_test.cc",
"gmock_link_test.cc",
"gmock_link_test.h",
],
deps = [
"//:gtest_main",
],
)
cc_binary(
name = "gmock_output_test_",
srcs = ["gmock_output_test_.cc"],
deps = [
"//:gtest",
],
)
py_test(
name = "gmock_output_test",
size = "medium",
srcs = ["gmock_output_test.py"],
data = [
":gmock_output_test_",
":gmock_output_test_golden.txt",
],
deps = [":gmock_test_utils"],
)
cc_test(
name = "gmock_test",
size = "small",
srcs = ["gmock_test.cc"],
deps = [
"//:gtest_main",
],
)

View File

@ -751,7 +751,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
}
// Tests that DoDefault() returns the default value set by
// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1);
MockClass mock;

View File

@ -915,7 +915,7 @@ TEST(TypedEqTest, CanDescribeSelf) {
// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
// is a "bare" type (i.e. not in the form of const U or U&). If v's
// type is not T, the compiler will generate a message about
// "undefined referece".
// "undefined reference".
template <typename T>
struct Type {
static bool IsTypeOf(const T& /* v */) { return true; }
@ -1424,7 +1424,7 @@ TEST(PairTest, MatchesCorrectly) {
EXPECT_THAT(p, Pair(25, "foo"));
EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
// 'first' doesnt' match, but 'second' matches.
// 'first' does not match, but 'second' matches.
EXPECT_THAT(p, Not(Pair(42, "foo")));
EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
@ -4263,7 +4263,7 @@ TYPED_TEST(ContainerEqTest, DuplicateDifference) {
#endif // GTEST_HAS_TYPED_TEST
// Tests that mutliple missing values are reported.
// Using just vector here, so order is predicatble.
// Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest, MultipleValuesMissing) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {2, 1, 5};
@ -4276,7 +4276,7 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) {
}
// Tests that added values are reported.
// Using just vector here, so order is predicatble.
// Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest, MultipleValuesAdded) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};

View File

@ -31,11 +31,11 @@
"""Tests the text output of Google C++ Mocking Framework.
SYNOPSIS
gmock_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gmock_output_test_ file.
gmock_output_test.py --gengolden
gmock_output_test.py
To update the golden file:
gmock_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gmock_output_test_ file.
gmock_output_test.py --gengolden
gmock_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
@ -176,5 +176,8 @@ if __name__ == '__main__':
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
# Suppress the error "googletest was imported but a call to its main()
# was never detected."
os._exit(0)
else:
gmock_test_utils.Main()

View File

@ -33,12 +33,13 @@
// threads concurrently.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace {
// From <gtest/internal/gtest-port.h>.
// From "gtest/internal/gtest-port.h".
using ::testing::internal::ThreadWithParam;
// The maximum number of test threads (not including helper threads)

View File

@ -37,6 +37,7 @@
#include <string>
#include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h"
#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
@ -51,9 +52,9 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose);
int argc = M;
int argc = M - 1;
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++) {
EXPECT_STREQ(new_argv[i], argv[i]);

View File

@ -1,5 +1,3 @@
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
@ -36,19 +34,19 @@ __author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
# Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# 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):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
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)
import gtest_test_utils # pylint: disable-msg=C6204
# pylint: disable=C6204
import gtest_test_utils
def GetSourceDir():

View File

@ -95,6 +95,9 @@ macro(config_compiler_and_linker)
set(cxx_no_rtti_flags "-GR-")
elseif (CMAKE_COMPILER_IS_GNUCXX)
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_no_exception_flags "-fno-exceptions")
# Until version 4.3.2, GCC doesn't define a macro to indicate

View File

@ -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
sub-routine the failure is from. You can alleviate this problem using
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
macro will cause the current file name, line number, and the given
message to be added in every failure message. The effect will be
undone when the control leaves the current lexical scope.
where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE`
macro will cause the current file name, line number, and the given message to be
added in every failure message. `ScopedTrace` accepts explicit file name and
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,
@ -870,13 +872,33 @@ TEST(FooTest, Bar) {
}
```
Since we don't use exceptions, it is technically impossible to
implement the intended behavior here. To alleviate this, Google Test
provides two solutions. You could use either the
`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
To alleviate this, gUnit provides three different solutions. You could use
either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
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 ###
As shown above, if your test calls a subroutine that has an `ASSERT_*`
@ -1949,6 +1971,17 @@ variable to `0` has the same effect.
_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower,
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 ###
Google Test can emit a detailed XML report to a file in addition to its normal

View File

@ -12,5 +12,5 @@ the respective git branch/tag).**
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.

View File

@ -460,7 +460,7 @@ following benefits:
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.
* 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? ##

View File

@ -46,6 +46,10 @@
// 2. operator<<(ostream&, const T&) defined in either foo or the
// 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
// the value if it is a protocol buffer, or print the raw bytes in the
// value otherwise.
@ -107,6 +111,11 @@
# include <tuple>
#endif
#if GTEST_HAS_ABSL
#include "absl/types/optional.h"
#include "absl/strings/string_view.h"
#endif // GTEST_HAS_ABSL
namespace testing {
// Definitions in the 'internal' and 'internal2' name spaces are
@ -125,6 +134,10 @@ enum TypeKind {
kProtobuf, // a protobuf type
kConvertibleToInteger, // a type implicitly convertible to BiggestInt
// (e.g. a named or unnamed enum type)
#if GTEST_HAS_ABSL
kConvertibleToStringView, // a type implicitly convertible to
// absl::string_view
#endif
kOtherType // anything else
};
@ -138,7 +151,7 @@ class TypeWithoutFormatter {
// This default version is called when kTypeKind is kOtherType.
static void PrintValue(const T& value, ::std::ostream* os) {
PrintBytesInObjectTo(static_cast<const unsigned char*>(
reinterpret_cast<const void *>(&value)),
reinterpret_cast<const void*>(&value)),
sizeof(value), os);
}
};
@ -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
// 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
@ -203,10 +229,19 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
template <typename Char, typename CharTraits, typename T>
::std::basic_ostream<Char, CharTraits>& operator<<(
::std::basic_ostream<Char, CharTraits>& os, const T& x) {
TypeWithoutFormatter<T,
(internal::IsAProtocolMessage<T>::value ? kProtobuf :
internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ?
kConvertibleToInteger : kOtherType)>::PrintValue(x, &os);
TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
? kProtobuf
: internal::ImplicitlyConvertible<
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;
}
@ -427,7 +462,8 @@ void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
*os << "NULL";
} else {
// 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);
}
}
@ -456,17 +492,15 @@ void PrintTo(const T& value, ::std::ostream* os) {
// DefaultPrintTo() is overloaded. The type of its first argument
// determines which version will be picked.
//
// Note that we check for recursive and other container types here, prior
// to we check for protocol message types in our operator<<. The rationale is:
// Note that we check for container types here, prior to we check
// for protocol message types in our operator<<. The rationale is:
//
// For protocol messages, we want to give people a chance to
// override Google Mock's format by defining a PrintTo() or
// operator<<. For STL containers, other formats can be
// incompatible with Google Mock's format for the container
// elements; therefore we check for container types here to ensure
// that our format is used. To prevent an infinite runtime recursion
// during the output of recursive container types, we check first for
// those.
// that our format is used.
//
// 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.
@ -593,6 +627,13 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
}
#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_
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
@ -722,6 +763,26 @@ class UniversalPrinter {
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'
// elements, starting at address 'begin'.
template <typename T>
@ -868,7 +929,7 @@ void UniversalPrint(const T& value, ::std::ostream* os) {
UniversalPrinter<T1>::Print(value, os);
}
typedef ::std::vector<string> Strings;
typedef ::std::vector< ::std::string> Strings;
// TuplePolicy<TupleT> must provide:
// - tuple_size
@ -988,6 +1049,16 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // 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>
::std::string PrintToString(const T& value) {
::std::stringstream ss;

View File

@ -115,6 +115,9 @@ GTEST_DECLARE_string_(output);
// test.
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.
GTEST_DECLARE_int32_(random_seed);
@ -135,7 +138,7 @@ GTEST_DECLARE_int32_(stack_trace_depth);
// 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 otherwise.
// non-zero code otherwise. For use with an external test framework.
GTEST_DECLARE_bool_(throw_on_failure);
// When this flag is set with a "host:port" string, on supported
@ -349,6 +352,15 @@ GTEST_API_ AssertionResult AssertionFailure();
// Deprecated; use AssertionFailure() << 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.
//
// In Google Test, a unit test program contains one or many TestCases, and
@ -359,7 +371,7 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
// this for you.
//
// 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 {
// protected:
@ -554,9 +566,8 @@ class GTEST_API_ TestResult {
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns the i-th test part result among all the results. i can range
// from 0 to test_property_count() - 1. If i is not in that range, aborts
// the program.
// 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;
// Returns the i-th test property. i can range from 0 to
@ -679,6 +690,9 @@ class GTEST_API_ TestInfo {
// Returns the line where this test is defined.
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
// disabled (or it is disabled but the also_run_disabled_tests flag has
// been specified) and its full name matches the user-specified filter.
@ -699,10 +713,9 @@ class GTEST_API_ TestInfo {
// Returns true iff this test will appear in the XML report.
bool is_reportable() const {
// For now, the XML report includes all tests matching the filter.
// In the future, we may trim tests that are excluded because of
// sharding.
return matches_filter_;
// The XML report includes tests matching the filter, excluding those
// run in other shards.
return matches_filter_ && !is_in_another_shard_;
}
// Returns the result of the test.
@ -766,6 +779,7 @@ class GTEST_API_ TestInfo {
bool is_disabled_; // True iff this test is disabled
bool matches_filter_; // True if this test matches the
// user-specified filter.
bool is_in_another_shard_; // Will be run in another shard.
internal::TestFactoryBase* const factory_; // The factory that creates
// the test object
@ -990,6 +1004,18 @@ class Environment {
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 order the corresponding events are fired.
class TestEventListener {
@ -1018,6 +1044,8 @@ class TestEventListener {
virtual void OnTestStart(const TestInfo& test_info) = 0;
// 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;
// Fired after the test ends.
@ -1291,9 +1319,9 @@ class GTEST_API_ UnitTest {
// These classes and functions are friends as they need to access private
// members of UnitTest.
friend class ScopedTrace;
friend class Test;
friend class internal::AssertHelper;
friend class internal::ScopedTrace;
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env);
@ -1782,7 +1810,6 @@ template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> {
};
// Macros for indicating success/failure in test code.
// ADD_FAILURE unconditionally adds a failure to the current test.
@ -1855,22 +1882,18 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class.
#define EXPECT_TRUE(condition) \
GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_)
#define EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
#define ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_FATAL_FAILURE_)
#define ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
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.
//
// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
@ -1912,8 +1935,8 @@ class TestWithParam : public Test, public WithParamInterface<T> {
//
// Examples:
//
// EXPECT_NE(5, Foo());
// EXPECT_EQ(NULL, a_pointer);
// EXPECT_NE(Foo(), 5);
// EXPECT_EQ(a_pointer, NULL);
// ASSERT_LT(i, array_size);
// ASSERT_GT(records.size(), 0) << "There is no record left.";
@ -2099,6 +2122,57 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
#define EXPECT_NO_FATAL_FAILURE(statement) \
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
// number, and the given message) to be included in every test failure
// 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,
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
#define SCOPED_TRACE(message) \
::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
__FILE__, __LINE__, (message))
@ -2212,8 +2286,8 @@ bool StaticAssertTypeEq() {
// }
//
// TEST_F(FooTest, ReturnsElementCountCorrectly) {
// EXPECT_EQ(0, a_.size());
// EXPECT_EQ(1, b_.size());
// EXPECT_EQ(a_.size(), 0);
// EXPECT_EQ(b_.size(), 1);
// }
#define TEST_F(test_fixture, test_name)\

View File

@ -27,7 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// 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!
//
// Implements a family of generic predicate assertion macros.
@ -35,10 +35,9 @@
#ifndef 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.
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
# error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
#include "gtest/gtest.h"
namespace testing {
// This header implements a family of generic predicate assertion
// macros:
@ -66,8 +65,6 @@
// We also define the EXPECT_* variations.
//
// 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
// in this file reduce. Don't use this in your code.
@ -355,4 +352,6 @@ AssertionResult AssertPred5Helper(const char* pred_text,
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_

View File

@ -191,7 +191,7 @@ class GTEST_API_ FilePath {
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
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;

View File

@ -95,7 +95,6 @@ template <typename T>
namespace internal {
struct TraceInfo; // Information about a trace point.
class ScopedTrace; // Implements scoped trace.
class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest
@ -151,53 +150,11 @@ class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
#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 {
// Returns the optimal edits to go from 'left' to 'right'.
// All edits cost the same, with replace having lower priority than
// add/remove.
// Simple implementation of the Wagner-Fischer algorithm.
// Simple implementation of the WagnerFischer algorithm.
// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
enum EditType { kMatch, kAdd, kRemove, kReplace };
GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
@ -650,7 +607,7 @@ class TypeParameterizedTest {
// Types). Valid values for 'index' are [0, N - 1] where N is the
// length of Types.
static bool Register(const char* prefix,
CodeLocation code_location,
const CodeLocation& code_location,
const char* case_name, const char* test_names,
int index) {
typedef typename Types::Head Type;
@ -681,7 +638,7 @@ class TypeParameterizedTest {
template <GTEST_TEMPLATE_ Fixture, class TestSel>
class TypeParameterizedTest<Fixture, TestSel, Types0> {
public:
static bool Register(const char* /*prefix*/, CodeLocation,
static bool Register(const char* /*prefix*/, const CodeLocation&,
const char* /*case_name*/, const char* /*test_names*/,
int /*index*/) {
return true;
@ -727,7 +684,7 @@ class TypeParameterizedTestCase {
template <GTEST_TEMPLATE_ Fixture, typename Types>
class TypeParameterizedTestCase<Fixture, Templates0, Types> {
public:
static bool Register(const char* /*prefix*/, CodeLocation,
static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestCasePState* /*state*/,
const char* /*case_name*/, const char* /*test_names*/) {
return true;

View File

@ -54,6 +54,9 @@
# define GTEST_OS_WINDOWS_PHONE 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
# 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
// WINAPI_FAMILY defined but no known partition matched.
// Default to desktop.

View File

@ -73,11 +73,9 @@
// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
// are enabled.
// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::string, which is different to std::string).
// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::wstring, which is different to std::wstring).
// is/isn't available
// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::wstring
// is/isn't available
// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
// expressions are/aren't available.
// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
@ -178,7 +176,7 @@
// GTEST_HAS_POSIX_RE (see above) which users can
// define themselves.
// 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().
// Misc public macros
@ -207,6 +205,7 @@
//
// C++11 feature wrappers:
//
// testing::internal::forward - portability wrapper for std::forward.
// testing::internal::move - portability wrapper for std::move.
//
// Synchronization:
@ -272,10 +271,12 @@
# include <TargetConditionals.h>
#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 <iostream> // NOLINT
#include <sstream> // NOLINT
#include <string> // NOLINT
#include <utility>
#include <vector> // NOLINT
@ -824,9 +825,10 @@ using ::std::tuple_size;
# define GTEST_HAS_TYPED_TEST_P 1
#endif
// Determines whether to support Combine().
// The implementation doesn't work on Sun Studio since it doesn't
// understand templated conversion operators.
// Determines whether to support Combine(). This only makes sense when
// value-parameterized tests are enabled. The implementation doesn't
// work on Sun Studio since it doesn't understand templated conversion
// operators.
#if (GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_) && !defined(__SUNPRO_CC)
# define GTEST_HAS_COMBINE 1
#endif
@ -980,7 +982,7 @@ using ::std::tuple_size;
#endif
// _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
#else
# define GTEST_HAS_CXXABI_H_ 0
@ -1126,6 +1128,16 @@ struct StaticAssertTypeEqHelper<T, T> {
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'.
#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
@ -1189,6 +1201,10 @@ class scoped_ptr {
// 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
// Regular Expression syntax.
class GTEST_API_ RE {
@ -1200,11 +1216,11 @@ class GTEST_API_ RE {
// Constructs an RE from a string.
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
#endif // GTEST_HAS_GLOBAL_STRING
# endif // GTEST_HAS_GLOBAL_STRING
RE(const char* regex) { Init(regex); } // NOLINT
~RE();
@ -1226,7 +1242,7 @@ class GTEST_API_ 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) {
return FullMatch(str.c_str(), re);
@ -1235,7 +1251,7 @@ class GTEST_API_ 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 PartialMatch(const char* str, const RE& re);
@ -1249,20 +1265,22 @@ class GTEST_API_ RE {
const char* pattern_;
bool is_valid_;
#if GTEST_USES_POSIX_RE
# if GTEST_USES_POSIX_RE
regex_t full_regex_; // For FullMatch().
regex_t partial_regex_; // For PartialMatch().
#else // GTEST_USES_SIMPLE_RE
# else // GTEST_USES_SIMPLE_RE
const char* full_pattern_; // For FullMatch();
#endif
# endif
GTEST_DISALLOW_ASSIGN_(RE);
};
#endif // GTEST_USES_PCRE
// 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.
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
@ -1349,12 +1367,23 @@ inline void FlushInfoLog() { fflush(NULL); }
<< gtest_error
#if GTEST_HAS_STD_MOVE_
using std::forward;
using std::move;
template <typename T>
struct RvalueRef {
typedef T&& type;
};
#else // GTEST_HAS_STD_MOVE_
template <typename T>
const T& move(const T& t) {
return t;
}
template <typename T>
struct RvalueRef {
typedef const T& type;
};
#endif // GTEST_HAS_STD_MOVE_
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@ -1455,7 +1484,6 @@ GTEST_API_ void CaptureStderr();
GTEST_API_ std::string GetCapturedStderr();
#endif // GTEST_HAS_STREAM_REDIRECTION
// Returns the size (in bytes) of a file.
GTEST_API_ size_t GetFileSize(FILE* file);

View File

@ -73,7 +73,7 @@ namespace testing {
// Constants.
// The default death test style.
static const char kDefaultDeathTestStyle[] = "fast";
static const char kDefaultDeathTestStyle[] = "threadsafe";
GTEST_DEFINE_string_(
death_test_style,
@ -555,7 +555,13 @@ bool DeathTestImpl::Passed(bool status_ok) {
break;
case DIED:
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());
# endif // GTEST_USES_PCRE
if (matched) {
success = true;
} else {

View File

@ -128,7 +128,7 @@ FilePath FilePath::RemoveExtension(const char* extension) const {
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
// separators. Returns NULL if no path separator was found.
const char* FilePath::FindLastPathSeparator() const {

View File

@ -86,6 +86,7 @@ const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output";
const char kPrintTimeFlag[] = "print_time";
const char kPrintUTF8Flag[] = "print_utf8";
const char kRandomSeedFlag[] = "random_seed";
const char kRepeatFlag[] = "repeat";
const char kShuffleFlag[] = "shuffle";
@ -166,6 +167,7 @@ class GTestFlagSaver {
list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output);
print_time_ = GTEST_FLAG(print_time);
print_utf8_ = GTEST_FLAG(print_utf8);
random_seed_ = GTEST_FLAG(random_seed);
repeat_ = GTEST_FLAG(repeat);
shuffle_ = GTEST_FLAG(shuffle);
@ -187,6 +189,7 @@ class GTestFlagSaver {
GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_;
GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(print_utf8) = print_utf8_;
GTEST_FLAG(random_seed) = random_seed_;
GTEST_FLAG(repeat) = repeat_;
GTEST_FLAG(shuffle) = shuffle_;
@ -208,6 +211,7 @@ class GTestFlagSaver {
bool list_tests_;
std::string output_;
bool print_time_;
bool print_utf8_;
internal::Int32 random_seed_;
internal::Int32 repeat_;
bool shuffle_;

View File

@ -43,12 +43,13 @@
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <cctype>
#include <cwchar>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
namespace testing {
@ -123,7 +124,7 @@ namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - 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').
enum CharFormat {
kAsIs,
@ -230,7 +231,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
return;
*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
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
@ -262,11 +263,12 @@ template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
static void PrintCharsAsStringTo(
static CharFormat PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin;
bool is_previous_hex = false;
CharFormat print_format = kAsIs;
for (size_t index = 0; index < len; ++index) {
const CharType cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
@ -276,8 +278,13 @@ static void PrintCharsAsStringTo(
*os << "\" " << kQuoteBegin;
}
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
// Remember if any characters required hex escaping.
if (is_previous_hex) {
print_format = kHexEscape;
}
}
*os << "\"";
return print_format;
}
// 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) {
}
#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.
#if GTEST_HAS_GLOBAL_STRING
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
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.

View File

@ -252,6 +252,12 @@ GTEST_DEFINE_bool_(
"True iff " GTEST_NAME_
" 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_(
random_seed,
internal::Int32FromGTestEnv("random_seed", 0),
@ -293,7 +299,7 @@ GTEST_DEFINE_bool_(
internal::BoolFromGTestEnv("throw_on_failure", false),
"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 "
"otherwise.");
"otherwise. For use with an external test framework.");
#if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DEFINE_string_(
@ -1661,7 +1667,7 @@ namespace {
AssertionResult HRESULTFailureHelper(const char* expr,
const char* expected,
long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
// Windows CE doesn't support FormatMessage.
const char error_text[] = "";
@ -1718,7 +1724,7 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
// Utility functions for encoding Unicode text (wide strings) in
// 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:
//
// Code-point length Encoding
@ -2435,6 +2441,8 @@ Result HandleExceptionsInMethodIfSupported(
#if GTEST_HAS_EXCEPTIONS
try {
return HandleSehExceptionsInMethodIfSupported(object, method, location);
} catch (const AssertionException&) { // NOLINT
// This failure was reported already.
} catch (const internal::GoogleTestFailureException&) { // NOLINT
// This exception type can only be thrown by a failed Google
// Test assertion with the intention of letting another testing
@ -3841,26 +3849,6 @@ void StreamingListener::SocketWriter::MakeConnection() {
// End of class Streaming Listener
#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
const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
@ -4839,10 +4827,11 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
matches_filter;
const bool is_selected = is_runnable &&
(shard_tests == IGNORE_SHARDING_PROTOCOL ||
ShouldRunTestOnShard(total_shards, shard_index,
num_runnable_tests));
const bool is_in_another_shard =
shard_tests != IGNORE_SHARDING_PROTOCOL &&
!ShouldRunTestOnShard(total_shards, shard_index, 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_selected_tests += is_selected;
@ -5220,7 +5209,8 @@ static const char kColorEncodedHelpMessage[] =
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\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"
" Do not report exceptions as test failures. Instead, allow them\n"
" to crash the program or throw a pop-up (on Windows).\n"
@ -5255,6 +5245,7 @@ static bool ParseGoogleTestFlag(const char* const arg) {
ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
@ -5432,4 +5423,23 @@ std::string TempDir() {
#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

View File

@ -26,9 +26,9 @@
// 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.
//
#include <stdio.h>
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {

View File

@ -119,3 +119,252 @@ cc_test(
"//: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"],
)

View File

@ -33,7 +33,7 @@
// Google Test work.
#include "gtest/gtest.h"
#include "test/gtest-param-test_test.h"
#include "gtest-param-test_test.h"
using ::testing::Values;
using ::testing::internal::ParamGenerator;

View File

@ -275,11 +275,11 @@ using hash_multiset = ::std::unordered_multiset<Key>;
#elif GTEST_HAS_HASH_SET_
#ifdef _STLP_HASH_MAP // We got <hash_map> from STLport.
using ::std::hash_set;
using ::std::hash_multiset;
using ::std::hash_map;
using ::std::hash_multimap;
#elif _MSC_VER
using ::stdext::hash_set;
using ::stdext::hash_multiset;
using ::stdext::hash_map;
using ::stdext::hash_multimap;
#endif
#endif
@ -837,22 +837,22 @@ TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
}
#if GTEST_HAS_STRING_PIECE_
#if GTEST_HAS_ABSL
// Tests printing StringPiece.
// Tests printing ::absl::string_view.
TEST(PrintStringPieceTest, SimpleStringPiece) {
const StringPiece sp = "Hello";
TEST(PrintStringViewTest, SimpleStringView) {
const ::absl::string_view sp = "Hello";
EXPECT_EQ("\"Hello\"", Print(sp));
}
TEST(PrintStringPieceTest, UnprintableCharacters) {
TEST(PrintStringViewTest, UnprintableCharacters) {
const char str[] = "NUL (\0) and \r\t";
const StringPiece sp(str, sizeof(str) - 1);
const ::absl::string_view sp(str, sizeof(str) - 1);
EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
}
#endif // GTEST_HAS_STRING_PIECE_
#endif // GTEST_HAS_ABSL
// Tests printing STL containers.
@ -1327,7 +1327,7 @@ TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
}
// Tests formatting a char pointer when it's compared with another pointer.
// In this case we want to print it as a raw pointer, as the comparision is by
// In this case we want to print it as a raw pointer, as the comparison is by
// pointer.
// char pointer vs pointer
@ -1552,6 +1552,78 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
}
TEST(PrintToStringTest, ContainsNonLatin) {
// Sanity test with valid UTF-8. Prints both in hex and as text.
std::string non_ascii_str = ::std::string("오전 4:30");
EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
" As Text: \"오전 4:30\"");
non_ascii_str = ::std::string("From ä — ẑ");
EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
"\n As Text: \"From ä — ẑ\"");
}
TEST(IsValidUTF8Test, IllFormedUTF8) {
// The following test strings are ill-formed UTF-8 and are printed
// as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
// expected to fail, thus output does not contain "As Text:".
static const char *const kTestdata[][2] = {
// 2-byte lead byte followed by a single-byte character.
{"\xC3\x74", "\"\\xC3t\""},
// Valid 2-byte character followed by an orphan trail byte.
{"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
// Lead byte without trail byte.
{"abc\xC3", "\"abc\\xC3\""},
// 3-byte lead byte, single-byte character, orphan trail byte.
{"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
// Truncated 3-byte character.
{"\xE2\x80", "\"\\xE2\\x80\""},
// Truncated 3-byte character followed by valid 2-byte char.
{"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
// Truncated 3-byte character followed by a single-byte character.
{"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
// 3-byte lead byte followed by valid 3-byte character.
{"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
// 4-byte lead byte followed by valid 3-byte character.
{"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
// Truncated 4-byte character.
{"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
// Invalid UTF-8 byte sequences embedded in other chars.
{"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
{"abc\xC3\x84\xE2\x80\xC3\x84xyz",
"\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
// Non-shortest UTF-8 byte sequences are also ill-formed.
// The classics: xC0, xC1 lead byte.
{"\xC0\x80", "\"\\xC0\\x80\""},
{"\xC1\x81", "\"\\xC1\\x81\""},
// Non-shortest sequences.
{"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
{"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
// Last valid code point before surrogate range, should be printed as text,
// too.
{"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
// Start of surrogate lead. Surrogates are not printed as text.
{"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
// Last non-private surrogate lead.
{"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
// First private-use surrogate lead.
{"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
// Last private-use surrogate lead.
{"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
// Mid-point of surrogate trail.
{"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
// First valid code point after surrogate range, should be printed as text,
// too.
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
};
for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
}
}
#undef EXPECT_PRINT_TO_STRING_
TEST(UniversalTersePrintTest, WorksForNonReference) {
@ -1693,5 +1765,17 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
#endif // GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_ABSL
TEST(PrintOptionalTest, Basic) {
absl::optional<int> value;
EXPECT_EQ("(nullopt)", PrintToString(value));
value = {7};
EXPECT_EQ("(7)", PrintToString(value));
EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
}
#endif // GTEST_HAS_ABSL
} // namespace gtest_printers_test
} // namespace testing

View File

@ -31,7 +31,7 @@
#include <vector>
#include "test/gtest-typed-test_test.h"
#include "gtest-typed-test_test.h"
#include "gtest/gtest.h"
#if GTEST_HAS_TYPED_TEST_P

View File

@ -29,7 +29,7 @@
//
// Author: wan@google.com (Zhanyong Wan)
#include "test/gtest-typed-test_test.h"
#include "gtest-typed-test_test.h"
#include <set>
#include <vector>

View File

@ -0,0 +1,119 @@
// Copyright 2009, 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests Google Test's assert-by-exception mode with exceptions enabled.
#include "gtest/gtest.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
class ThrowListener : public testing::EmptyTestEventListener {
void OnTestPartResult(const testing::TestPartResult& result) override {
if (result.type() == testing::TestPartResult::kFatalFailure) {
throw testing::AssertionException(result);
}
}
};
// Prints the given failure message and exits the program with
// non-zero. We use this instead of a Google Test assertion to
// indicate a failure, as the latter is been tested and cannot be
// relied on.
void Fail(const char* msg) {
printf("FAILURE: %s\n", msg);
fflush(stdout);
exit(1);
}
static void AssertFalse() {
ASSERT_EQ(2, 3) << "Expected failure";
}
// Tests that an assertion failure throws a subclass of
// std::runtime_error.
TEST(Test, Test) {
// A successful assertion shouldn't throw.
try {
EXPECT_EQ(3, 3);
} catch(...) {
Fail("A successful assertion wrongfully threw.");
}
// A successful assertion shouldn't throw.
try {
EXPECT_EQ(3, 4);
} catch(...) {
Fail("A failed non-fatal assertion wrongfully threw.");
}
// A failed assertion should throw.
try {
AssertFalse();
} catch(const testing::AssertionException& e) {
if (strstr(e.what(), "Expected failure") != NULL)
throw;
printf("%s",
"A failed assertion did throw an exception of the right type, "
"but the message is incorrect. Instead of containing \"Expected "
"failure\", it is:\n");
Fail(e.what());
} catch(...) {
Fail("A failed assertion threw the wrong type of exception.");
}
Fail("A failed assertion should've thrown but didn't.");
}
int kTestForContinuingTest = 0;
TEST(Test, Test2) {
// FIXME(sokolov): how to force Test2 to be after Test?
kTestForContinuingTest = 1;
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);
int result = RUN_ALL_TESTS();
if (result == 0) {
printf("RUN_ALL_TESTS returned %d\n", result);
Fail("Expected failure instead.");
}
if (kTestForContinuingTest == 0) {
Fail("Should have continued with other tests, but did not.");
}
return 0;
}

View File

@ -40,10 +40,8 @@ Google Test) with different environments and command line flags.
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
import gtest_test_utils
# Constants.

View File

@ -37,8 +37,6 @@ Google Test) and verifies their output.
__author__ = 'vladl@google.com (Vlad Losev)'
import os
import gtest_test_utils
# Constants.

View File

@ -36,8 +36,7 @@ __author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
IS_WINDOWS = os.name = 'nt'
IS_WINDOWS = os.name == 'nt'
COLOR_ENV_VAR = 'GTEST_COLOR'
COLOR_FLAG = 'gtest_color'

View File

@ -47,8 +47,8 @@ environ = os.environ.copy()
def AssertEq(expected, actual):
if expected != actual:
print('Expected: %s' % (expected,))
print(' Actual: %s' % (actual,))
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
@ -92,7 +92,7 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
TestFlag('death_test_style', 'threadsafe', 'fast')
TestFlag('death_test_style', 'fast', 'threadsafe')
TestFlag('catch_exceptions', '0', '1')
if IS_LINUX:

View File

@ -44,12 +44,8 @@ __author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
try:
from sets import Set as set # For Python 2.3 compatibility
except ImportError:
pass
import sets
import sys
import gtest_test_utils
# Constants.
@ -59,10 +55,12 @@ import gtest_test_utils
# script in a subprocess to print whether the variable is STILL in
# os.environ. We then use 'eval' to parse the child's output so that an
# exception is thrown if the input is anything other than 'True' nor 'False'.
os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print(\'EMPTY_VAR\' in os.environ)'])
CAN_PASS_EMPTY_ENV = eval(child.output)
CAN_PASS_EMPTY_ENV = False
if sys.executable:
os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ'])
CAN_PASS_EMPTY_ENV = eval(child.output)
# Check if this platform can unset environment variables in child processes.
@ -71,11 +69,14 @@ CAN_PASS_EMPTY_ENV = eval(child.output)
# is NO LONGER in os.environ.
# We use 'eval' to parse the child's output so that an exception
# is thrown if the input is neither 'True' nor 'False'.
os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print(\'UNSET_VAR\' not in os.environ)'])
CAN_UNSET_ENV = eval(child.output)
CAN_UNSET_ENV = False
if sys.executable:
os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ'
])
CAN_UNSET_ENV = eval(child.output)
# Checks if we should test with an empty filter. This doesn't
@ -97,7 +98,7 @@ SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
FILTER_FLAG = 'gtest_filter'
# The command line flag for including disabled tests.
ALSO_RUN_DISABED_TESTS_FLAG = 'gtest_also_run_disabled_tests'
ALSO_RUN_DISABLED_TESTS_FLAG = 'gtest_also_run_disabled_tests'
# Command to run the gtest_filter_unittest_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_filter_unittest_')
@ -246,14 +247,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
for slice_var in list_of_sets:
full_partition.extend(slice_var)
self.assertEqual(len(set_var), len(full_partition))
self.assertEqual(set(set_var), set(full_partition))
self.assertEqual(sets.Set(set_var), sets.Set(full_partition))
def AdjustForParameterizedTests(self, tests_to_run):
"""Adjust tests_to_run in case value parameterized tests are disabled."""
global param_tests_present
if not param_tests_present:
return list(set(tests_to_run) - set(PARAM_TESTS))
return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS))
else:
return tests_to_run
@ -294,6 +295,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
Runs all shards of gtest_filter_unittest_ with the given filter, and
verifies that the right set of tests were run. The union of tests run
on each shard should be identical to tests_to_run, without duplicates.
If check_exit_0, .
Args:
gtest_filter: A filter to apply to the tests.
@ -339,7 +341,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
# Construct the command line.
args = ['--%s' % ALSO_RUN_DISABED_TESTS_FLAG]
args = ['--%s' % ALSO_RUN_DISABLED_TESTS_FLAG]
if gtest_filter is not None:
args.append('--%s=%s' % (FILTER_FLAG, gtest_filter))

View File

@ -39,9 +39,8 @@ Google Test) the command line flags.
__author__ = 'phanna@google.com (Patrick Hanna)'
import gtest_test_utils
import re
import gtest_test_utils
# Constants.
@ -123,6 +122,7 @@ def Run(args):
# The unit test.
class GTestListTestsUnitTest(gtest_test_utils.TestCase):
"""Tests using the --gtest_list_tests flag to list all tests."""

View File

@ -31,6 +31,7 @@
"""Tests the text output of Google C++ Testing Framework.
SYNOPSIS
gtest_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gtest_output_test_ file.
@ -51,6 +52,7 @@ import gtest_test_utils
GENGOLDEN_FLAG = '--gengolden'
CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
IS_WINDOWS = os.name == 'nt'
# TODO(vladl@google.com): remove the _lin suffix.
@ -99,7 +101,8 @@ def RemoveLocations(test_output):
'FILE_NAME:#: '.
"""
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
return re.sub(r'.*[/\\]((gtest_output_test_|gtest).cc)(\:\d+|\(\d+\))\: ',
r'\1:#: ', test_output)
def RemoveStackTraceDetails(output):
@ -249,11 +252,12 @@ test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
SUPPORTS_STACK_TRACES = False
SUPPORTS_STACK_TRACES = IS_LINUX
CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
SUPPORTS_TYPED_TESTS and
SUPPORTS_THREADS and
SUPPORTS_STACK_TRACES and
not IS_WINDOWS)
class GTestOutputTest(gtest_test_utils.TestCase):
@ -279,7 +283,7 @@ class GTestOutputTest(gtest_test_utils.TestCase):
def testOutput(self):
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'r')
golden_file = open(GOLDEN_PATH, 'rb')
# A mis-configured source control system can cause \r appear in EOL
# sequences when we read the golden file irrespective of an operating
# system used. Therefore, we need to strip those \r's from newlines
@ -330,9 +334,9 @@ if __name__ == '__main__':
else:
message = (
"""Unable to write a golden file when compiled in an environment
that does not support all the required features (death tests, typed tests,
and multiple threads). Please generate the golden file using a binary built
with those features enabled.""")
that does not support all the required features (death tests,
typed tests, stack traces, and multiple threads).
Please build this test and generate the golden file using Blaze on Linux.""")
sys.stderr.write(message)
sys.exit(1)

View File

@ -168,6 +168,16 @@ void SubWithTrace(int n) {
SubWithoutTrace(n);
}
TEST(SCOPED_TRACETest, AcceptedValues) {
SCOPED_TRACE("literal string");
SCOPED_TRACE(std::string("std::string"));
SCOPED_TRACE(1337); // streamable type
const char* null_value = NULL;
SCOPED_TRACE(null_value);
ADD_FAILURE() << "Just checking that all these values work fine.";
}
// Tests that SCOPED_TRACE() obeys lexical scopes.
TEST(SCOPED_TRACETest, ObeysScopes) {
printf("(expected to fail)\n");
@ -315,6 +325,13 @@ TEST(SCOPED_TRACETest, WorksConcurrently) {
}
#endif // GTEST_IS_THREADSAFE
// Tests basic functionality of the ScopedTrace utility (most of its features
// are already tested in SCOPED_TRACETest).
TEST(ScopedTraceTest, WithExplicitFileAndLine) {
testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message");
ADD_FAILURE() << "Check that the trace is attached to a particular location.";
}
TEST(DisabledTestsWarningTest,
DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
// This test body is intentionally empty. Its sole purpose is for

View File

@ -8,7 +8,7 @@ gtest_output_test_.cc:#: Failure
Expected equality of these values:
2
3
[==========] Running 66 tests from 29 test cases.
[==========] Running 68 tests from 30 test cases.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
@ -95,7 +95,17 @@ i == 3
gtest_output_test_.cc:#: Failure
Expected: (3) >= (a[i]), actual: 3 vs 6
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[----------] 6 tests from SCOPED_TRACETest
[----------] 7 tests from SCOPED_TRACETest
[ RUN ] SCOPED_TRACETest.AcceptedValues
gtest_output_test_.cc:#: Failure
Failed
Just checking that all these values work fine.
Google Test trace:
gtest_output_test_.cc:#: (null)
gtest_output_test_.cc:#: 1337
gtest_output_test_.cc:#: std::string
gtest_output_test_.cc:#: literal string
[ FAILED ] SCOPED_TRACETest.AcceptedValues
[ RUN ] SCOPED_TRACETest.ObeysScopes
(expected to fail)
gtest_output_test_.cc:#: Failure
@ -212,6 +222,14 @@ gtest_output_test_.cc:#: Failure
Failed
Expected failure #6 (in thread A, no trace alive).
[ FAILED ] SCOPED_TRACETest.WorksConcurrently
[----------] 1 test from ScopedTraceTest
[ RUN ] ScopedTraceTest.WithExplicitFileAndLine
gtest_output_test_.cc:#: Failure
Failed
Check that the trace is attached to a particular location.
Google Test trace:
explicit_file.cc:123: expected trace message
[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine
[----------] 1 test from NonFatalFailureInFixtureConstructorTest
[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
(expecting 5 failures)
@ -466,7 +484,7 @@ Expected equality of these values:
Which is: '\0'
Expected failure
[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char
[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int
[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned
[ RUN ] Unsigned/TypedTestP/1.Success
[ OK ] Unsigned/TypedTestP/1.Success
[ RUN ] Unsigned/TypedTestP/1.Failure
@ -477,7 +495,7 @@ Expected equality of these values:
TypeParam()
Which is: 0
Expected failure
[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int
[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned
[----------] 4 tests from ExpectFailureTest
[ RUN ] ExpectFailureTest.ExpectFatalFailure
(expecting 1 failure)
@ -636,21 +654,23 @@ FooEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected fatal failure.
[==========] 66 tests from 29 test cases ran.
[==========] 68 tests from 30 test cases ran.
[ PASSED ] 22 tests.
[ FAILED ] 44 tests, listed below:
[ FAILED ] 46 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[ FAILED ] SCOPED_TRACETest.AcceptedValues
[ FAILED ] SCOPED_TRACETest.ObeysScopes
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ FAILED ] SCOPED_TRACETest.CanBeNested
[ FAILED ] SCOPED_TRACETest.CanBeRepeated
[ FAILED ] SCOPED_TRACETest.WorksConcurrently
[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine
[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp
@ -673,7 +693,7 @@ Expected fatal failure.
[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows
[ FAILED ] TypedTest/0.Failure, where TypeParam = int
[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char
[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int
[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned
[ FAILED ] ExpectFailureTest.ExpectFatalFailure
[ FAILED ] ExpectFailureTest.ExpectNonFatalFailure
[ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads
@ -684,7 +704,7 @@ Expected fatal failure.
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
44 FAILED TESTS
46 FAILED TESTS
 YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.*

View File

@ -27,7 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// 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!
// Regression test for gtest_pred_impl.h

View File

@ -29,10 +29,10 @@
//
// Author: wan@google.com (Zhanyong Wan)
//
// Unit test for include/gtest/gtest_prod.h.
// Unit test for gtest/gtest_prod.h.
#include "production.h"
#include "gtest/gtest.h"
#include "test/production.h"
// Tests that private members can be accessed from a TEST declared as
// a friend of the class.

View File

@ -67,7 +67,7 @@ namespace {
// Used for verifying that global environment set-up and tear-down are
// inside the gtest_repeat loop.
// inside the --gtest_repeat loop.
int g_environment_set_up_count = 0;
int g_environment_tear_down_count = 0;

View File

@ -1,5 +1,3 @@
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
@ -30,19 +28,24 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for Google C++ Testing Framework."""
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
__author__ = 'wan@google.com (Zhanyong Wan)'
import atexit
import os
import shutil
import sys
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
IS_WINDOWS = os.name == 'nt'
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
import atexit
import shutil
import tempfile
import unittest
_test_module = unittest
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
try:
import subprocess
_SUBPROCESS_MODULE_AVAILABLE = True
@ -53,9 +56,6 @@ except:
GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
IS_WINDOWS = os.name == 'nt'
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
# The environment variable for specifying the path to the premature-exit file.
PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
@ -145,8 +145,6 @@ atexit.register(_RemoveTempDir)
def GetTempDir():
"""Returns a directory for temporary files."""
global _temp_dir
if not _temp_dir:
_temp_dir = tempfile.mkdtemp()
@ -178,7 +176,7 @@ def GetTestExecutablePath(executable_name, build_dir=None):
'Unable to find the test binary "%s". Please make sure to provide\n'
'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
'environment variable.' % path)
sys.stdout.write(message)
print >> sys.stderr, message
sys.exit(1)
return path
@ -229,7 +227,7 @@ class Subprocess:
combined in a string.
"""
# The subprocess module is the preferrable way of running programs
# The subprocess module is the preferable way of running programs
# since it is available and behaves consistently on all platforms,
# including Windows. But it is only available starting in python 2.4.
# In earlier python versions, we revert to the popen2 module, which is

View File

@ -70,7 +70,7 @@ def SetEnvVar(env_var, value):
def Run(command):
"""Runs a command; returns True/False if its exit code is/isn't 0."""
print('Running "%s". . .' % ' '.join(command))
print 'Running "%s". . .' % ' '.join(command)
p = gtest_test_utils.Subprocess(command)
return p.exited and p.exit_code == 0

View File

@ -33,9 +33,9 @@
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_')
@ -46,8 +46,8 @@ def Assert(condition):
def AssertEq(expected, actual):
if expected != actual:
print('Expected: %s' % (expected,))
print(' Actual: %s' % (actual,))
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
@ -56,8 +56,8 @@ def TestExitCodeAndOutput(command):
# Verifies that 'command' exits with code 1.
p = gtest_test_utils.Subprocess(command)
Assert(p.exited)
AssertEq(1, p.exit_code)
if p.exited and p.exit_code == 0:
Assert('IMPORTANT NOTICE' in p.output);
Assert('InitGoogleTest' in p.output)

View File

@ -34,8 +34,8 @@
TEST(DummyTest, Dummy) {
// This test doesn't verify anything. We just need it to create a
// realistic stage for testing the behavior of Google Test when
// RUN_ALL_TESTS() is called without testing::InitGoogleTest() being
// called first.
// RUN_ALL_TESTS() is called without
// testing::InitGoogleTest() being called first.
}
int main() {

View File

@ -34,9 +34,9 @@
#include "gtest/gtest.h"
// Verifies that the command line flag variables can be accessed
// in code once <gtest/gtest.h> has been #included.
// Do not move it after other #includes.
// Verifies that the command line flag variables can be accessed in
// code once "gtest/gtest.h" has been
// #included. Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
|| testing::GTEST_FLAG(break_on_failure)
@ -538,7 +538,7 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
// 101 0111 0110 => 110-10101 10-110110
// Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
// in wide strings and wide chars. In order to accomodate them, we have to
// in wide strings and wide chars. In order to accommodate them, we have to
// introduce such character constants as integers.
EXPECT_EQ("\xD5\xB6",
CodePointToUtf8(static_cast<wchar_t>(0x576)));
@ -1779,7 +1779,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
}
// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable cannot be represnted by an Int32.
// if the variable cannot be represented by an Int32.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
EXPECT_DEATH_IF_SUPPORTED(
@ -3658,7 +3658,7 @@ TEST(AssertionTest, AssertFalseWithAssertionResult) {
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" supressed them
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
@ -4384,7 +4384,7 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) {
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" supressed them
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
@ -6642,7 +6642,7 @@ TEST(StreamingAssertionsTest, Truth2) {
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" supressed them
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif

View File

@ -31,15 +31,11 @@
"""Unit test for the gtest_xml_output module."""
__author__ = "keith.ray@gmail.com (Keith Ray)"
import os
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_OUTPUT_SUBDIR = "xml_outfiles"
GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"

View File

@ -31,8 +31,6 @@
"""Unit test for the gtest_xml_output module"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import datetime
import errno
import os
@ -43,12 +41,16 @@ from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_FILTER_FLAG = '--gtest_filter'
GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
GTEST_OUTPUT_FLAG = '--gtest_output'
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
SUPPORTS_STACK_TRACES = False
@ -141,6 +143,19 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
</testsuite>
</testsuites>"""
EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="NoFixtureTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
</testsuite>
<testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" />
</testsuite>
</testsuites>"""
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests">
@ -182,7 +197,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
Runs a test program that generates an empty XML output, and checks if
the timestamp attribute in the testsuites tag is valid.
"""
actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0)
actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)
date_time_str = actual.documentElement.getAttributeNode('timestamp').value
# datetime.strptime() is only available in Python 2.5+ so we have to
# parse the expected datetime manually.
@ -212,8 +227,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
'gtest_no_test_unittest')
try:
os.remove(output_file)
except OSError:
e = sys.exc_info()[1]
except OSError, e:
if e.errno != errno.ENOENT:
raise
@ -263,7 +277,22 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code):
def testShardedTestXmlOutput(self):
"""Verifies XML output when run using multiple shards.
Runs a test program that executes only one shard and verifies that tests
from other shards do not show up in the XML output.
"""
self._TestXmlOutput(
GTEST_PROGRAM_NAME,
EXPECTED_SHARDED_TEST_XML,
0,
extra_env={SHARD_INDEX_ENV_VAR: '0',
TOTAL_SHARDS_ENV_VAR: '10'})
def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env,
expected_exit_code):
"""
Returns the xml output generated by running the program gtest_prog_name.
Furthermore, the program's exit code must be expected_exit_code.
@ -274,7 +303,11 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
extra_args)
p = gtest_test_utils.Subprocess(command)
environ_copy = os.environ.copy()
if extra_env:
environ_copy.update(extra_env)
p = gtest_test_utils.Subprocess(command, env=environ_copy)
if p.terminated_by_signal:
self.assert_(False,
'%s was killed by signal %d' % (gtest_prog_name, p.signal))
@ -288,7 +321,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
return actual
def _TestXmlOutput(self, gtest_prog_name, expected_xml,
expected_exit_code, extra_args=None):
expected_exit_code, extra_args=None, extra_env=None):
"""
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
@ -297,7 +330,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
expected_exit_code)
extra_env or {}, expected_exit_code)
expected = minidom.parseString(expected_xml)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,

View File

@ -1,5 +1,3 @@
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
@ -31,15 +29,10 @@
"""Unit test utilities for gtest_xml_output"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import re
from xml.dom import minidom, Node
import gtest_test_utils
GTEST_OUTPUT_FLAG = '--gtest_output'
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
class GTestXMLTestCase(gtest_test_utils.TestCase):
@ -101,7 +94,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
self.assertEquals(
len(expected_children), len(actual_children),
'number of child elements differ in element ' + actual_node.tagName)
for child_id, child in expected_children.items():
for child_id, child in expected_children.iteritems():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))
@ -187,8 +180,8 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
# Replaces the source line information with a normalized form.
cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
# Removes the actual stack trace.
child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*',
'', cdata)
child.nodeValue = re.sub(r'Stack trace:\n(.|\n)*',
'Stack trace:\n*', cdata)
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)

View File

@ -29,7 +29,7 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""A script to prepare version informtion for use the gtest Info.plist file.
"""A script to prepare version information for use the gtest Info.plist file.
This script extracts the version information from the configure.ac file and
uses it to generate a header file containing the same information. The