Unfortunately, the svn repo is a bit out of date. This commit contains 8

changes that haven't made it to svn. The descriptions of each change are listed
below.

- Fixes some python shebang lines.

- Add ElementsAreArray overloads to gmock. ElementsAreArray now makes a copy of
  its input elements before the conversion to a Matcher. ElementsAreArray can
  now take a vector as input. ElementsAreArray can now take an iterator pair as
  input.

- Templatize MatchAndExplain to allow independent string types for the matcher
  and matchee. I also templatized the ConstCharPointer version of
  MatchAndExplain to avoid calls with "char*" from using the new templated
  MatchAndExplain.

- Fixes the bug where the constructor of the return type of ElementsAre() saves
  a reference instead of a copy of the arguments.

- Extends ElementsAre() to accept arrays whose sizes aren't known.

- Switches gTest's internal FilePath class from testing::internal::String to
  std::string. testing::internal::String was introduced when gTest couldn't
  depend on std::string.  It's now deprecated.

- Switches gTest & gMock from using testing::internal::String objects to
  std::string. Some static methods of String are still in use.  We may be able
  to remove some but not all of them.  In particular, String::Format() should
  eventually be removed as it truncates the result at 4096 characters, often
  causing problems.
This commit is contained in:
jgm 2012-11-15 15:47:38 +00:00
parent 78bf6d5724
commit 87fdda2cf2
28 changed files with 533 additions and 1090 deletions

View File

@ -183,11 +183,11 @@ class GTEST_API_ Message {
Message& operator <<(const ::wstring& wstr); Message& operator <<(const ::wstring& wstr);
#endif // GTEST_HAS_GLOBAL_WSTRING #endif // GTEST_HAS_GLOBAL_WSTRING
// Gets the text streamed to this object so far as a String. // Gets the text streamed to this object so far as an std::string.
// Each '\0' character in the buffer is replaced with "\\0". // Each '\0' character in the buffer is replaced with "\\0".
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::String GetString() const { std::string GetString() const {
return internal::StringStreamToString(ss_.get()); return internal::StringStreamToString(ss_.get());
} }

View File

@ -62,7 +62,7 @@ class GTEST_API_ TestPartResult {
int a_line_number, int a_line_number,
const char* a_message) const char* a_message)
: type_(a_type), : type_(a_type),
file_name_(a_file_name), file_name_(a_file_name == NULL ? "" : a_file_name),
line_number_(a_line_number), line_number_(a_line_number),
summary_(ExtractSummary(a_message)), summary_(ExtractSummary(a_message)),
message_(a_message) { message_(a_message) {
@ -73,7 +73,9 @@ class GTEST_API_ TestPartResult {
// Gets the name of the source file where the test part took place, or // Gets the name of the source file where the test part took place, or
// NULL if it's unknown. // NULL if it's unknown.
const char* file_name() const { return file_name_.c_str(); } const char* file_name() const {
return file_name_.empty() ? NULL : file_name_.c_str();
}
// Gets the line in the source file where the test part took place, // Gets the line in the source file where the test part took place,
// or -1 if it's unknown. // or -1 if it's unknown.
@ -102,16 +104,16 @@ class GTEST_API_ TestPartResult {
// Gets the summary of the failure message by omitting the stack // Gets the summary of the failure message by omitting the stack
// trace in it. // trace in it.
static internal::String ExtractSummary(const char* message); static std::string ExtractSummary(const char* message);
// The name of the source file where the test part took place, or // The name of the source file where the test part took place, or
// NULL if the source file is unknown. // "" if the source file is unknown.
internal::String file_name_; std::string file_name_;
// The line in the source file where the test part took place, or -1 // The line in the source file where the test part took place, or -1
// if the line number is unknown. // if the line number is unknown.
int line_number_; int line_number_;
internal::String summary_; // The test failure summary. std::string summary_; // The test failure summary.
internal::String message_; // The test failure message. std::string message_; // The test failure message.
}; };
// Prints a TestPartResult object. // Prints a TestPartResult object.

View File

@ -160,9 +160,9 @@ class TestEventRepeater;
class WindowsDeathTest; class WindowsDeathTest;
class UnitTestImpl* GetUnitTestImpl(); class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const String& message); const std::string& message);
// Converts a streamable value to a String. A NULL pointer is // Converts a streamable value to an std::string. A NULL pointer is
// converted to "(null)". When the input value is a ::string, // converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL // ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0". // character in it is replaced with "\\0".
@ -170,7 +170,7 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
// to the definition of the Message class, required by the ARM // to the definition of the Message class, required by the ARM
// compiler. // compiler.
template <typename T> template <typename T>
String StreamableToString(const T& streamable) { std::string StreamableToString(const T& streamable) {
return (Message() << streamable).GetString(); return (Message() << streamable).GetString();
} }
@ -495,9 +495,9 @@ class TestProperty {
private: private:
// The key supplied by the user. // The key supplied by the user.
internal::String key_; std::string key_;
// The value supplied by the user. // The value supplied by the user.
internal::String value_; std::string value_;
}; };
// The result of a single Test. This includes a list of // The result of a single Test. This includes a list of
@ -869,7 +869,7 @@ class GTEST_API_ TestCase {
void UnshuffleTests(); void UnshuffleTests();
// Name of the test case. // Name of the test case.
internal::String name_; std::string name_;
// Name of the parameter type, or NULL if this is not a typed or a // Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test. // type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_; const internal::scoped_ptr<const ::std::string> type_param_;
@ -1196,8 +1196,8 @@ class GTEST_API_ UnitTest {
void AddTestPartResult(TestPartResult::Type result_type, void AddTestPartResult(TestPartResult::Type result_type,
const char* file_name, const char* file_name,
int line_number, int line_number,
const internal::String& message, const std::string& message,
const internal::String& os_stack_trace) const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
// Adds a TestProperty to the current TestResult object. If the result already // Adds a TestProperty to the current TestResult object. If the result already
@ -1221,7 +1221,7 @@ class GTEST_API_ UnitTest {
friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation( friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type, TestPartResult::Type result_type,
const internal::String& message); const std::string& message);
// Creates an empty UnitTest. // Creates an empty UnitTest.
UnitTest(); UnitTest();
@ -1383,8 +1383,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2> template <typename T1, typename T2>
String FormatForComparisonFailureMessage(const T1& value, std::string FormatForComparisonFailureMessage(
const T2& /* other_operand */) { const T1& value, const T2& /* other_operand */) {
return FormatForComparison<T1, T2>::Format(value); return FormatForComparison<T1, T2>::Format(value);
} }
@ -1701,9 +1701,9 @@ class GTEST_API_ AssertHelper {
: type(t), file(srcfile), line(line_num), message(msg) { } : type(t), file(srcfile), line(line_num), message(msg) { }
TestPartResult::Type const type; TestPartResult::Type const type;
const char* const file; const char* const file;
int const line; int const line;
String const message; std::string const message;
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
@ -1981,7 +1981,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif #endif
// C String Comparisons. All tests treat NULL and any non-NULL string // C-string Comparisons. All tests treat NULL and any non-NULL string
// as different. Two NULLs are equal. // as different. Two NULLs are equal.
// //
// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2

View File

@ -127,11 +127,11 @@ class GTEST_API_ DeathTest {
// the last death test. // the last death test.
static const char* LastMessage(); static const char* LastMessage();
static void set_last_death_test_message(const String& message); static void set_last_death_test_message(const std::string& message);
private: private:
// A string containing a description of the outcome of the last death test. // A string containing a description of the outcome of the last death test.
static String last_death_test_message_; static std::string last_death_test_message_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
}; };
@ -233,7 +233,7 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// RUN_ALL_TESTS was called. // RUN_ALL_TESTS was called.
class InternalRunDeathTestFlag { class InternalRunDeathTestFlag {
public: public:
InternalRunDeathTestFlag(const String& a_file, InternalRunDeathTestFlag(const std::string& a_file,
int a_line, int a_line,
int an_index, int an_index,
int a_write_fd) int a_write_fd)
@ -245,13 +245,13 @@ class InternalRunDeathTestFlag {
posix::Close(write_fd_); posix::Close(write_fd_);
} }
String file() const { return file_; } const std::string& file() const { return file_; }
int line() const { return line_; } int line() const { return line_; }
int index() const { return index_; } int index() const { return index_; }
int write_fd() const { return write_fd_; } int write_fd() const { return write_fd_; }
private: private:
String file_; std::string file_;
int line_; int line_;
int index_; int index_;
int write_fd_; int write_fd_;

View File

@ -61,11 +61,7 @@ class GTEST_API_ FilePath {
FilePath() : pathname_("") { } FilePath() : pathname_("") { }
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
explicit FilePath(const char* pathname) : pathname_(pathname) { explicit FilePath(const std::string& pathname) : pathname_(pathname) {
Normalize();
}
explicit FilePath(const String& pathname) : pathname_(pathname) {
Normalize(); Normalize();
} }
@ -78,7 +74,7 @@ class GTEST_API_ FilePath {
pathname_ = rhs.pathname_; pathname_ = rhs.pathname_;
} }
String ToString() const { return pathname_; } const std::string& string() const { return pathname_; }
const char* c_str() const { return pathname_.c_str(); } const char* c_str() const { return pathname_.c_str(); }
// Returns the current working directory, or "" if unsuccessful. // Returns the current working directory, or "" if unsuccessful.
@ -111,8 +107,8 @@ class GTEST_API_ FilePath {
const FilePath& base_name, const FilePath& base_name,
const char* extension); const char* extension);
// Returns true iff the path is NULL or "". // Returns true iff the path is "".
bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } bool IsEmpty() const { return pathname_.empty(); }
// If input name has a trailing separator character, removes it and returns // If input name has a trailing separator character, removes it and returns
// the name, otherwise return the name string unmodified. // the name, otherwise return the name string unmodified.
@ -201,7 +197,7 @@ class GTEST_API_ FilePath {
// separators. Returns NULL if no path separator was found. // separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const; const char* FindLastPathSeparator() const;
String pathname_; std::string pathname_;
}; // class FilePath }; // class FilePath
} // namespace internal } // namespace internal

View File

@ -163,8 +163,8 @@ char (&IsNullLiteralHelper(...))[2]; // NOLINT
#endif // GTEST_ELLIPSIS_NEEDS_POD_ #endif // GTEST_ELLIPSIS_NEEDS_POD_
// Appends the user-supplied message to the Google-Test-generated message. // Appends the user-supplied message to the Google-Test-generated message.
GTEST_API_ String AppendUserMessage(const String& gtest_msg, GTEST_API_ std::string AppendUserMessage(
const Message& user_msg); const std::string& gtest_msg, const Message& user_msg);
// A helper class for creating scoped traces in user programs. // A helper class for creating scoped traces in user programs.
class GTEST_API_ ScopedTrace { class GTEST_API_ ScopedTrace {
@ -185,7 +185,7 @@ class GTEST_API_ ScopedTrace {
// c'tor and d'tor. Therefore it doesn't // c'tor and d'tor. Therefore it doesn't
// need to be used otherwise. // need to be used otherwise.
// Converts a streamable value to a String. A NULL pointer is // Converts a streamable value to an std::string. A NULL pointer is
// converted to "(null)". When the input value is a ::string, // converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL // ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0". // character in it is replaced with "\\0".
@ -193,7 +193,7 @@ class GTEST_API_ ScopedTrace {
// to the definition of the Message class, required by the ARM // to the definition of the Message class, required by the ARM
// compiler. // compiler.
template <typename T> template <typename T>
String StreamableToString(const T& streamable); std::string StreamableToString(const T& streamable);
// Constructs and returns the message for an equality assertion // Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
@ -212,12 +212,12 @@ String StreamableToString(const T& streamable);
// be inserted into the message. // be inserted into the message.
GTEST_API_ AssertionResult EqFailure(const char* expected_expression, GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression, const char* actual_expression,
const String& expected_value, const std::string& expected_value,
const String& actual_value, const std::string& actual_value,
bool ignoring_case); bool ignoring_case);
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GTEST_API_ String GetBoolAssertionFailureMessage( GTEST_API_ std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result, const AssertionResult& assertion_result,
const char* expression_text, const char* expression_text,
const char* actual_predicate_value, const char* actual_predicate_value,
@ -563,9 +563,9 @@ inline const char* SkipComma(const char* str) {
// Returns the prefix of 'str' before the first comma in it; returns // Returns the prefix of 'str' before the first comma in it; returns
// the entire string if it contains no comma. // the entire string if it contains no comma.
inline String GetPrefixUntilComma(const char* str) { inline std::string GetPrefixUntilComma(const char* str) {
const char* comma = strchr(str, ','); const char* comma = strchr(str, ',');
return comma == NULL ? String(str) : String(str, comma - str); return comma == NULL ? str : std::string(str, comma);
} }
// TypeParameterizedTest<Fixture, TestSel, Types>::Register() // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
@ -650,7 +650,7 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> {
#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -660,8 +660,8 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
int skip_count); UnitTest* unit_test, int skip_count);
// Helpers for suppressing warnings on unreachable code or constant // Helpers for suppressing warnings on unreachable code or constant
// condition. // condition.

View File

@ -239,6 +239,9 @@
# define GTEST_OS_MAC 1 # define GTEST_OS_MAC 1
# if TARGET_OS_IPHONE # if TARGET_OS_IPHONE
# define GTEST_OS_IOS 1 # define GTEST_OS_IOS 1
# if TARGET_IPHONE_SIMULATOR
# define GEST_OS_IOS_SIMULATOR 1
# endif
# endif # endif
#elif defined __linux__ #elif defined __linux__
# define GTEST_OS_LINUX 1 # define GTEST_OS_LINUX 1
@ -635,7 +638,7 @@ using ::std::tuple_size;
// abort() in a VC 7.1 application compiled as GUI in debug config // abort() in a VC 7.1 application compiled as GUI in debug config
// pops up a dialog window that cannot be suppressed programmatically. // pops up a dialog window that cannot be suppressed programmatically.
#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
(GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_MAC && (!GTEST_OS_IOS || GEST_OS_IOS_SIMULATOR)) || \
(GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
GTEST_OS_OPENBSD || GTEST_OS_QNX) GTEST_OS_OPENBSD || GTEST_OS_QNX)
@ -780,8 +783,6 @@ class Message;
namespace internal { namespace internal {
class String;
// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
// expression is true. For example, you could use it to verify the // expression is true. For example, you could use it to verify the
// size of a static array: // size of a static array:
@ -964,10 +965,9 @@ class GTEST_API_ RE {
private: private:
void Init(const char* regex); void Init(const char* regex);
// We use a const char* instead of a string, as Google Test may be used // We use a const char* instead of an std::string, as Google Test used to be
// where string is not available. We also do not use Google Test's own // used where std::string is not available. TODO(wan@google.com): change to
// String type here, in order to simplify dependencies between the // std::string.
// files.
const char* pattern_; const char* pattern_;
bool is_valid_; bool is_valid_;
@ -1150,9 +1150,9 @@ Derived* CheckedDowncastToActualType(Base* base) {
// GetCapturedStderr - stops capturing stderr and returns the captured string. // GetCapturedStderr - stops capturing stderr and returns the captured string.
// //
GTEST_API_ void CaptureStdout(); GTEST_API_ void CaptureStdout();
GTEST_API_ String GetCapturedStdout(); GTEST_API_ std::string GetCapturedStdout();
GTEST_API_ void CaptureStderr(); GTEST_API_ void CaptureStderr();
GTEST_API_ String GetCapturedStderr(); GTEST_API_ std::string GetCapturedStderr();
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
@ -1903,7 +1903,7 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
#define GTEST_DECLARE_int32_(name) \ #define GTEST_DECLARE_int32_(name) \
GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
#define GTEST_DECLARE_string_(name) \ #define GTEST_DECLARE_string_(name) \
GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) GTEST_API_ extern ::std::string GTEST_FLAG(name)
// Macros for defining flags. // Macros for defining flags.
#define GTEST_DEFINE_bool_(name, default_val, doc) \ #define GTEST_DEFINE_bool_(name, default_val, doc) \
@ -1911,7 +1911,7 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
#define GTEST_DEFINE_int32_(name, default_val, doc) \ #define GTEST_DEFINE_int32_(name, default_val, doc) \
GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
#define GTEST_DEFINE_string_(name, default_val, doc) \ #define GTEST_DEFINE_string_(name, default_val, doc) \
GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
// Thread annotations // Thread annotations
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) #define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)

View File

@ -54,30 +54,7 @@
namespace testing { namespace testing {
namespace internal { namespace internal {
// String - a UTF-8 string class. // String - an abstract class holding static string utilities.
//
// For historic reasons, we don't use std::string.
//
// TODO(wan@google.com): replace this class with std::string or
// implement it in terms of the latter.
//
// Note that String can represent both NULL and the empty string,
// while std::string cannot represent NULL.
//
// NULL and the empty string are considered different. NULL is less
// than anything (including the empty string) except itself.
//
// This class only provides minimum functionality necessary for
// implementing Google Test. We do not intend to implement a full-fledged
// string class here.
//
// Since the purpose of this class is to provide a substitute for
// std::string on platforms where it cannot be used, we define a copy
// constructor and assignment operators such that we don't need
// conditional compilation in a lot of places.
//
// In order to make the representation efficient, the d'tor of String
// is not virtual. Therefore DO NOT INHERIT FROM String.
class GTEST_API_ String { class GTEST_API_ String {
public: public:
// Static utility methods // Static utility methods
@ -128,7 +105,7 @@ class GTEST_API_ String {
// NULL will be converted to "(null)". If an error occurred during // NULL will be converted to "(null)". If an error occurred during
// the conversion, "(failed to convert from wide string)" is // the conversion, "(failed to convert from wide string)" is
// returned. // returned.
static String ShowWideCString(const wchar_t* wide_c_str); static std::string ShowWideCString(const wchar_t* wide_c_str);
// Compares two wide C strings. Returns true iff they have the same // Compares two wide C strings. Returns true iff they have the same
// content. // content.
@ -162,7 +139,12 @@ class GTEST_API_ String {
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs); const wchar_t* rhs);
// Formats a list of arguments to a String, using the same format // Returns true iff the given string ends with the given suffix, ignoring
// case. Any string is considered to end with an empty suffix.
static bool EndsWithCaseInsensitive(
const std::string& str, const std::string& suffix);
// Formats a list of arguments to an std::string, using the same format
// spec string as for printf. // spec string as for printf.
// //
// We do not use the StringPrintf class as it is not universally // We do not use the StringPrintf class as it is not universally
@ -171,156 +153,17 @@ class GTEST_API_ String {
// The result is limited to 4096 characters (including the tailing // The result is limited to 4096 characters (including the tailing
// 0). If 4096 characters are not enough to format the input, // 0). If 4096 characters are not enough to format the input,
// "<buffer exceeded>" is returned. // "<buffer exceeded>" is returned.
static String Format(const char* format, ...); static std::string Format(const char* format, ...);
// C'tors
// The default c'tor constructs a NULL string.
String() : c_str_(NULL), length_(0) {}
// Constructs a String by cloning a 0-terminated C string.
String(const char* a_c_str) { // NOLINT
if (a_c_str == NULL) {
c_str_ = NULL;
length_ = 0;
} else {
ConstructNonNull(a_c_str, strlen(a_c_str));
}
}
// Constructs a String by copying a given number of chars from a
// buffer. E.g. String("hello", 3) creates the string "hel",
// String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "",
// and String(NULL, 1) results in access violation.
String(const char* buffer, size_t a_length) {
ConstructNonNull(buffer, a_length);
}
// The copy c'tor creates a new copy of the string. The two
// String objects do not share content.
String(const String& str) : c_str_(NULL), length_(0) { *this = str; }
// D'tor. String is intended to be a final class, so the d'tor
// doesn't need to be virtual.
~String() { delete[] c_str_; }
// Allows a String to be implicitly converted to an ::std::string or
// ::string, and vice versa. Converting a String containing a NULL
// pointer to ::std::string or ::string is undefined behavior.
// Converting a ::std::string or ::string containing an embedded NUL
// character to a String will result in the prefix up to the first
// NUL character.
String(const ::std::string& str) { // NOLINT
ConstructNonNull(str.c_str(), str.length());
}
operator ::std::string() const { return ::std::string(c_str(), length()); }
#if GTEST_HAS_GLOBAL_STRING
String(const ::string& str) { // NOLINT
ConstructNonNull(str.c_str(), str.length());
}
operator ::string() const { return ::string(c_str(), length()); }
#endif // GTEST_HAS_GLOBAL_STRING
// Returns true iff this is an empty string (i.e. "").
bool empty() const { return (c_str() != NULL) && (length() == 0); }
// Compares this with another String.
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
// if this is greater than rhs.
int Compare(const String& rhs) const;
// Returns true iff this String equals the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; }
// Returns true iff this String is less than the given String. A
// NULL string is considered less than "".
bool operator<(const String& rhs) const { return Compare(rhs) < 0; }
// Returns true iff this String doesn't equal the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); }
// Returns true iff this String ends with the given suffix. *Any*
// String is considered to end with a NULL or empty suffix.
bool EndsWith(const char* suffix) const;
// Returns true iff this String ends with the given suffix, not considering
// case. Any String is considered to end with a NULL or empty suffix.
bool EndsWithCaseInsensitive(const char* suffix) const;
// Returns the length of the encapsulated string, or 0 if the
// string is NULL.
size_t length() const { return length_; }
// Gets the 0-terminated C string this String object represents.
// The String object still owns the string. Therefore the caller
// should NOT delete the return value.
const char* c_str() const { return c_str_; }
// Assigns a C string to this object. Self-assignment works.
const String& operator=(const char* a_c_str) {
return *this = String(a_c_str);
}
// Assigns a String object to this object. Self-assignment works.
const String& operator=(const String& rhs) {
if (this != &rhs) {
delete[] c_str_;
if (rhs.c_str() == NULL) {
c_str_ = NULL;
length_ = 0;
} else {
ConstructNonNull(rhs.c_str(), rhs.length());
}
}
return *this;
}
private: private:
// Constructs a non-NULL String from the given content. This String(); // Not meant to be instantiated.
// function can only be called when c_str_ has not been allocated.
// ConstructNonNull(NULL, 0) results in an empty string ("").
// ConstructNonNull(NULL, non_zero) is undefined behavior.
void ConstructNonNull(const char* buffer, size_t a_length) {
char* const str = new char[a_length + 1];
memcpy(str, buffer, a_length);
str[a_length] = '\0';
c_str_ = str;
length_ = a_length;
}
const char* c_str_;
size_t length_;
}; // class String }; // class String
// Streams a String to an ostream. Each '\0' character in the String // Gets the content of the stringstream's buffer as an std::string. Each '\0'
// is replaced with "\\0".
inline ::std::ostream& operator<<(::std::ostream& os, const String& str) {
if (str.c_str() == NULL) {
os << "(null)";
} else {
const char* const c_str = str.c_str();
for (size_t i = 0; i != str.length(); i++) {
if (c_str[i] == '\0') {
os << "\\0";
} else {
os << c_str[i];
}
}
}
return os;
}
// Gets the content of the stringstream's buffer as a String. Each '\0'
// character in the buffer is replaced with "\\0". // character in the buffer is replaced with "\\0".
GTEST_API_ String StringStreamToString(::std::stringstream* stream); GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
// Converts a streamable value to a String. A NULL pointer is // Converts a streamable value to an std::string. A NULL pointer is
// converted to "(null)". When the input value is a ::string, // converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL // ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0". // character in it is replaced with "\\0".
@ -329,7 +172,7 @@ GTEST_API_ String StringStreamToString(::std::stringstream* stream);
// to the definition of the Message class, required by the ARM // to the definition of the Message class, required by the ARM
// compiler. // compiler.
template <typename T> template <typename T>
String StreamableToString(const T& streamable); std::string StreamableToString(const T& streamable);
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing

View File

@ -62,7 +62,7 @@ namespace internal {
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
template <typename T> template <typename T>
String GetTypeName() { std::string GetTypeName() {
# if GTEST_HAS_RTTI # if GTEST_HAS_RTTI
const char* const name = typeid(T).name(); const char* const name = typeid(T).name();
@ -74,7 +74,7 @@ String GetTypeName() {
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // GTEST_HAS_CXXABI_H_ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, 0, 0, &status);
const String name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return name_str;
# else # else

View File

@ -60,7 +60,7 @@ namespace internal {
// NB: This function is also used in Google Mock, so don't move it inside of // NB: This function is also used in Google Mock, so don't move it inside of
// the typed-test-only section below. // the typed-test-only section below.
template <typename T> template <typename T>
String GetTypeName() { std::string GetTypeName() {
# if GTEST_HAS_RTTI # if GTEST_HAS_RTTI
const char* const name = typeid(T).name(); const char* const name = typeid(T).name();
@ -72,7 +72,7 @@ String GetTypeName() {
using abi::__cxa_demangle; using abi::__cxa_demangle;
# endif // GTEST_HAS_CXXABI_H_ # endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, 0, 0, &status); char* const readable_name = __cxa_demangle(name, 0, 0, &status);
const String name_str(status == 0 ? readable_name : name); const std::string name_str(status == 0 ? readable_name : name);
free(readable_name); free(readable_name);
return name_str; return name_str;
# else # else

View File

@ -179,7 +179,7 @@ namespace internal {
// Generates a textual description of a given exit code, in the format // Generates a textual description of a given exit code, in the format
// specified by wait(2). // specified by wait(2).
static String ExitSummary(int exit_code) { static std::string ExitSummary(int exit_code) {
Message m; Message m;
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
@ -214,7 +214,7 @@ bool ExitedUnsuccessfully(int exit_status) {
// one thread running, or cannot determine the number of threads, prior // one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the // to executing the given statement. It is the responsibility of the
// caller not to pass a thread_count of 1. // caller not to pass a thread_count of 1.
static String DeathTestThreadWarning(size_t thread_count) { static std::string DeathTestThreadWarning(size_t thread_count) {
Message msg; Message msg;
msg << "Death tests use fork(), which is unsafe particularly" msg << "Death tests use fork(), which is unsafe particularly"
<< " in a threaded context. For this test, " << GTEST_NAME_ << " "; << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
@ -248,7 +248,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
// message is propagated back to the parent process. Otherwise, the // message is propagated back to the parent process. Otherwise, the
// message is simply printed to stderr. In either case, the program // message is simply printed to stderr. In either case, the program
// then exits with status 1. // then exits with status 1.
void DeathTestAbort(const String& message) { void DeathTestAbort(const std::string& message) {
// On a POSIX system, this function may be called from a threadsafe-style // On a POSIX system, this function may be called from a threadsafe-style
// death test child process, which operates on a very small stack. Use // death test child process, which operates on a very small stack. Use
// the heap for any additional non-minuscule memory requirements. // the heap for any additional non-minuscule memory requirements.
@ -272,7 +272,7 @@ void DeathTestAbort(const String& message) {
# define GTEST_DEATH_TEST_CHECK_(expression) \ # define GTEST_DEATH_TEST_CHECK_(expression) \
do { \ do { \
if (!::testing::internal::IsTrue(expression)) { \ if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort(::testing::internal::String::Format( \ DeathTestAbort(::testing::internal::String::Format( \
"CHECK failed: File %s, line %d: %s", \ "CHECK failed: File %s, line %d: %s", \
__FILE__, __LINE__, #expression)); \ __FILE__, __LINE__, #expression)); \
} \ } \
@ -292,15 +292,15 @@ void DeathTestAbort(const String& message) {
gtest_retval = (expression); \ gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \ } while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \ if (gtest_retval == -1) { \
DeathTestAbort(::testing::internal::String::Format( \ DeathTestAbort(::testing::internal::String::Format( \
"CHECK failed: File %s, line %d: %s != -1", \ "CHECK failed: File %s, line %d: %s != -1", \
__FILE__, __LINE__, #expression)); \ __FILE__, __LINE__, #expression)); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno. // Returns the message describing the last system error in errno.
String GetLastErrnoDescription() { std::string GetLastErrnoDescription() {
return String(errno == 0 ? "" : posix::StrError(errno)); return errno == 0 ? "" : posix::StrError(errno);
} }
// This is called from a death test parent process to read a failure // This is called from a death test parent process to read a failure
@ -350,11 +350,11 @@ const char* DeathTest::LastMessage() {
return last_death_test_message_.c_str(); return last_death_test_message_.c_str();
} }
void DeathTest::set_last_death_test_message(const String& message) { void DeathTest::set_last_death_test_message(const std::string& message) {
last_death_test_message_ = message; last_death_test_message_ = message;
} }
String DeathTest::last_death_test_message_; std::string DeathTest::last_death_test_message_;
// Provides cross platform implementation for some death functionality. // Provides cross platform implementation for some death functionality.
class DeathTestImpl : public DeathTest { class DeathTestImpl : public DeathTest {
@ -529,7 +529,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned()) if (!spawned())
return false; return false;
const String error_message = GetCapturedStderr(); const std::string error_message = GetCapturedStderr();
bool success = false; bool success = false;
Message buffer; Message buffer;
@ -711,15 +711,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
FALSE, // The initial state is non-signalled. FALSE, // The initial state is non-signalled.
NULL)); // The even is unnamed. NULL)); // The even is unnamed.
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
const String filter_flag = String::Format("--%s%s=%s.%s", const std::string filter_flag =
GTEST_FLAG_PREFIX_, kFilterFlag, std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
info->test_case_name(), info->test_case_name() + "." + info->name();
info->name()); const std::string internal_flag =
const String internal_flag = String::Format( std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
"--%s%s=%s|%d|%d|%u|%Iu|%Iu", "=" + file_ + "|" + String::Format("%d|%d|%u|%Iu|%Iu", line_,
GTEST_FLAG_PREFIX_,
kInternalRunDeathTestFlag,
file_, line_,
death_test_index, death_test_index,
static_cast<unsigned int>(::GetCurrentProcessId()), static_cast<unsigned int>(::GetCurrentProcessId()),
// size_t has the same with as pointers on both 32-bit and 64-bit // size_t has the same with as pointers on both 32-bit and 64-bit
@ -734,10 +731,9 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
executable_path, executable_path,
_MAX_PATH)); _MAX_PATH));
String command_line = String::Format("%s %s \"%s\"", std::string command_line =
::GetCommandLineA(), std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
filter_flag.c_str(), internal_flag + "\"";
internal_flag.c_str());
DeathTest::set_last_death_test_message(""); DeathTest::set_last_death_test_message("");
@ -954,9 +950,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
original_dir, GetLastErrnoDescription());
GetLastErrnoDescription().c_str()));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -966,10 +961,9 @@ static int ExecDeathTestChildMain(void* child_arg) {
// invoke the test program via a valid path that contains at least // invoke the test program via a valid path that contains at least
// one path separator. // one path separator.
execve(args->argv[0], args->argv, GetEnviron()); execve(args->argv[0], args->argv, GetEnviron());
DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
args->argv[0], original_dir + " failed: " +
original_dir, GetLastErrnoDescription());
GetLastErrnoDescription().c_str()));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
# endif // !GTEST_OS_QNX # endif // !GTEST_OS_QNX
@ -1020,9 +1014,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
original_dir, GetLastErrnoDescription());
GetLastErrnoDescription().c_str()));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -1120,11 +1113,11 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// it be closed when the child process does an exec: // it be closed when the child process does an exec:
GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
const String filter_flag = const std::string filter_flag =
String::Format("--%s%s=%s.%s", String::Format("--%s%s=%s.%s",
GTEST_FLAG_PREFIX_, kFilterFlag, GTEST_FLAG_PREFIX_, kFilterFlag,
info->test_case_name(), info->name()); info->test_case_name(), info->name());
const String internal_flag = const std::string internal_flag =
String::Format("--%s%s=%s|%d|%d|%d", String::Format("--%s%s=%s|%d|%d|%d",
GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
file_, line_, death_test_index, pipe_fd[1]); file_, line_, death_test_index, pipe_fd[1]);

View File

@ -116,9 +116,10 @@ FilePath FilePath::GetCurrentDir() {
// FilePath("dir/file"). If a case-insensitive extension is not // FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath. // found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const { FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension)); const std::string dot_extension = std::string(".") + extension;
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); return FilePath(pathname_.substr(
0, pathname_.length() - dot_extension.length()));
} }
return *this; return *this;
} }
@ -147,7 +148,7 @@ const char* FilePath::FindLastPathSeparator() const {
// On Windows platform, '\' is the path separator, otherwise it is '/'. // On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const { FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = FindLastPathSeparator(); const char* const last_sep = FindLastPathSeparator();
return last_sep ? FilePath(String(last_sep + 1)) : *this; return last_sep ? FilePath(last_sep + 1) : *this;
} }
// RemoveFileName returns the directory path with the filename removed. // RemoveFileName returns the directory path with the filename removed.
@ -158,9 +159,9 @@ FilePath FilePath::RemoveDirectoryName() const {
// On Windows platform, '\' is the path separator, otherwise it is '/'. // On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const { FilePath FilePath::RemoveFileName() const {
const char* const last_sep = FindLastPathSeparator(); const char* const last_sep = FindLastPathSeparator();
String dir; std::string dir;
if (last_sep) { if (last_sep) {
dir = String(c_str(), last_sep + 1 - c_str()); dir = std::string(c_str(), last_sep + 1 - c_str());
} else { } else {
dir = kCurrentDirectoryString; dir = kCurrentDirectoryString;
} }
@ -177,11 +178,12 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name, const FilePath& base_name,
int number, int number,
const char* extension) { const char* extension) {
String file; std::string file;
if (number == 0) { if (number == 0) {
file = String::Format("%s.%s", base_name.c_str(), extension); file = base_name.string() + "." + extension;
} else { } else {
file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); file = base_name.string() + "_" + String::Format("%d", number).c_str()
+ "." + extension;
} }
return ConcatPaths(directory, FilePath(file)); return ConcatPaths(directory, FilePath(file));
} }
@ -193,8 +195,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory,
if (directory.IsEmpty()) if (directory.IsEmpty())
return relative_path; return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator()); const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, return FilePath(dir.string() + kPathSeparator + relative_path.string());
relative_path.c_str()));
} }
// Returns true if pathname describes something findable in the file-system, // Returns true if pathname describes something findable in the file-system,
@ -338,7 +339,7 @@ bool FilePath::CreateFolder() const {
// On Windows platform, uses \ as the separator, other platforms use /. // On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const { FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory() return IsDirectory()
? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) ? FilePath(pathname_.substr(0, pathname_.length() - 1))
: *this; : *this;
} }

View File

@ -202,20 +202,20 @@ class GTestFlagSaver {
bool also_run_disabled_tests_; bool also_run_disabled_tests_;
bool break_on_failure_; bool break_on_failure_;
bool catch_exceptions_; bool catch_exceptions_;
String color_; std::string color_;
String death_test_style_; std::string death_test_style_;
bool death_test_use_fork_; bool death_test_use_fork_;
String filter_; std::string filter_;
String internal_run_death_test_; std::string internal_run_death_test_;
bool list_tests_; bool list_tests_;
String output_; std::string output_;
bool print_time_; bool print_time_;
bool pretty_; bool pretty_;
internal::Int32 random_seed_; internal::Int32 random_seed_;
internal::Int32 repeat_; internal::Int32 repeat_;
bool shuffle_; bool shuffle_;
internal::Int32 stack_trace_depth_; internal::Int32 stack_trace_depth_;
String stream_result_to_; std::string stream_result_to_;
bool throw_on_failure_; bool throw_on_failure_;
} GTEST_ATTRIBUTE_UNUSED_; } GTEST_ATTRIBUTE_UNUSED_;
@ -242,7 +242,7 @@ GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs // and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane. // will be encoded as individual Unicode characters from Basic Normal Plane.
GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this // if the variable is present. If a file already exists at this location, this
@ -351,11 +351,11 @@ class TestPropertyKeyIs {
// Returns true iff the test name of test property matches on key_. // Returns true iff the test name of test property matches on key_.
bool operator()(const TestProperty& test_property) const { bool operator()(const TestProperty& test_property) const {
return String(test_property.key()).Compare(key_) == 0; return test_property.key() == key_;
} }
private: private:
String key_; std::string key_;
}; };
// Class UnitTestOptions. // Class UnitTestOptions.
@ -373,12 +373,12 @@ class GTEST_API_ UnitTestOptions {
// Functions for processing the gtest_output flag. // Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output. // Returns the output format, or "" for normal printed output.
static String GetOutputFormat(); static std::string GetOutputFormat();
// Returns the absolute path of the requested output file, or the // Returns the absolute path of the requested output file, or the
// default (test_detail.xml in the original working directory) if // default (test_detail.xml in the original working directory) if
// none was explicitly specified. // none was explicitly specified.
static String GetAbsolutePathToOutputFile(); static std::string GetAbsolutePathToOutputFile();
// Functions for processing the gtest_filter flag. // Functions for processing the gtest_filter flag.
@ -391,8 +391,8 @@ class GTEST_API_ UnitTestOptions {
// Returns true iff the user-specified filter matches the test case // Returns true iff the user-specified filter matches the test case
// name and the test name. // name and the test name.
static bool FilterMatchesTest(const String &test_case_name, static bool FilterMatchesTest(const std::string &test_case_name,
const String &test_name); const std::string &test_name);
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag. // Function for supporting the gtest_catch_exception flag.
@ -405,7 +405,7 @@ class GTEST_API_ UnitTestOptions {
// Returns true if "name" matches the ':' separated list of glob-style // Returns true if "name" matches the ':' separated list of glob-style
// filters in "filter". // filters in "filter".
static bool MatchesFilter(const String& name, const char* filter); static bool MatchesFilter(const std::string& name, const char* filter);
}; };
// Returns the current application's name, removing directory path if that // Returns the current application's name, removing directory path if that
@ -418,13 +418,13 @@ class OsStackTraceGetterInterface {
OsStackTraceGetterInterface() {} OsStackTraceGetterInterface() {}
virtual ~OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {}
// Returns the current OS stack trace as a String. Parameters: // Returns the current OS stack trace as an std::string. Parameters:
// //
// max_depth - the maximum number of stack frames to be included // max_depth - the maximum number of stack frames to be included
// in the trace. // in the trace.
// skip_count - the number of top frames to be skipped; doesn't count // skip_count - the number of top frames to be skipped; doesn't count
// against max_depth. // against max_depth.
virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
// UponLeavingGTest() should be called immediately before Google Test calls // UponLeavingGTest() should be called immediately before Google Test calls
// user code. It saves some information about the current stack that // user code. It saves some information about the current stack that
@ -440,7 +440,7 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
public: public:
OsStackTraceGetter() : caller_frame_(NULL) {} OsStackTraceGetter() : caller_frame_(NULL) {}
virtual String CurrentStackTrace(int max_depth, int skip_count) virtual string CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_); virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
@ -465,7 +465,7 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
struct TraceInfo { struct TraceInfo {
const char* file; const char* file;
int line; int line;
String message; std::string message;
}; };
// This is the default global test part result reporter used in UnitTestImpl. // This is the default global test part result reporter used in UnitTestImpl.
@ -610,7 +610,7 @@ class GTEST_API_ UnitTestImpl {
// getter, and returns it. // getter, and returns it.
OsStackTraceGetterInterface* os_stack_trace_getter(); OsStackTraceGetterInterface* os_stack_trace_getter();
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -620,7 +620,7 @@ class GTEST_API_ UnitTestImpl {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
String CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
// Finds and returns a TestCase with the given name. If one doesn't // Finds and returns a TestCase with the given name. If one doesn't
// exist, creates one and returns it. // exist, creates one and returns it.
@ -953,7 +953,7 @@ GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
// Returns the message describing the last system error, regardless of the // Returns the message describing the last system error, regardless of the
// platform. // platform.
GTEST_API_ String GetLastErrnoDescription(); GTEST_API_ std::string GetLastErrnoDescription();
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership. // Provides leak-safe Windows kernel handle ownership.

View File

@ -247,7 +247,7 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
} }
// Helper function used by ValidateRegex() to format error messages. // Helper function used by ValidateRegex() to format error messages.
String FormatRegexSyntaxError(const char* regex, int index) { std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index return (Message() << "Syntax error at index " << index
<< " in simple regular expression \"" << regex << "\": ").GetString(); << " in simple regular expression \"" << regex << "\": ").GetString();
} }
@ -513,7 +513,7 @@ GTestLog::~GTestLog() {
class CapturedStream { class CapturedStream {
public: public:
// The ctor redirects the stream to a temporary file. // The ctor redirects the stream to a temporary file.
CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
@ -565,7 +565,7 @@ class CapturedStream {
remove(filename_.c_str()); remove(filename_.c_str());
} }
String GetCapturedString() { std::string GetCapturedString() {
if (uncaptured_fd_ != -1) { if (uncaptured_fd_ != -1) {
// Restores the original stream. // Restores the original stream.
fflush(NULL); fflush(NULL);
@ -575,14 +575,14 @@ class CapturedStream {
} }
FILE* const file = posix::FOpen(filename_.c_str(), "r"); FILE* const file = posix::FOpen(filename_.c_str(), "r");
const String content = ReadEntireFile(file); const std::string content = ReadEntireFile(file);
posix::FClose(file); posix::FClose(file);
return content; return content;
} }
private: private:
// Reads the entire content of a file as a String. // Reads the entire content of a file as an std::string.
static String ReadEntireFile(FILE* file); static std::string ReadEntireFile(FILE* file);
// Returns the size (in bytes) of a file. // Returns the size (in bytes) of a file.
static size_t GetFileSize(FILE* file); static size_t GetFileSize(FILE* file);
@ -602,7 +602,7 @@ size_t CapturedStream::GetFileSize(FILE* file) {
} }
// Reads the entire content of a file as a string. // Reads the entire content of a file as a string.
String CapturedStream::ReadEntireFile(FILE* file) { std::string CapturedStream::ReadEntireFile(FILE* file) {
const size_t file_size = GetFileSize(file); const size_t file_size = GetFileSize(file);
char* const buffer = new char[file_size]; char* const buffer = new char[file_size];
@ -618,7 +618,7 @@ String CapturedStream::ReadEntireFile(FILE* file) {
bytes_read += bytes_last_read; bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size); } while (bytes_last_read > 0 && bytes_read < file_size);
const String content(buffer, bytes_read); const std::string content(buffer, bytes_read);
delete[] buffer; delete[] buffer;
return content; return content;
@ -641,8 +641,8 @@ void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
} }
// Stops capturing the output stream and returns the captured string. // Stops capturing the output stream and returns the captured string.
String GetCapturedStream(CapturedStream** captured_stream) { std::string GetCapturedStream(CapturedStream** captured_stream) {
const String content = (*captured_stream)->GetCapturedString(); const std::string content = (*captured_stream)->GetCapturedString();
delete *captured_stream; delete *captured_stream;
*captured_stream = NULL; *captured_stream = NULL;
@ -661,10 +661,14 @@ void CaptureStderr() {
} }
// Stops capturing stdout and returns the captured string. // Stops capturing stdout and returns the captured string.
String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } std::string GetCapturedStdout() {
return GetCapturedStream(&g_captured_stdout);
}
// Stops capturing stderr and returns the captured string. // Stops capturing stderr and returns the captured string.
String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } std::string GetCapturedStderr() {
return GetCapturedStream(&g_captured_stderr);
}
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
@ -702,8 +706,8 @@ void Abort() {
// Returns the name of the environment variable corresponding to the // Returns the name of the environment variable corresponding to the
// given flag. For example, FlagToEnvVar("foo") will return // given flag. For example, FlagToEnvVar("foo") will return
// "GTEST_FOO" in the open-source version. // "GTEST_FOO" in the open-source version.
static String FlagToEnvVar(const char* flag) { static std::string FlagToEnvVar(const char* flag) {
const String full_flag = const std::string full_flag =
(Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
Message env_var; Message env_var;
@ -760,7 +764,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
// //
// The value is considered true iff it's not "0". // The value is considered true iff it's not "0".
bool BoolFromGTestEnv(const char* flag, bool default_value) { bool BoolFromGTestEnv(const char* flag, bool default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
return string_value == NULL ? return string_value == NULL ?
default_value : strcmp(string_value, "0") != 0; default_value : strcmp(string_value, "0") != 0;
@ -770,7 +774,7 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) {
// variable corresponding to the given flag; if it isn't set or // variable corresponding to the given flag; if it isn't set or
// doesn't represent a valid 32-bit integer, returns default_value. // doesn't represent a valid 32-bit integer, returns default_value.
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
if (string_value == NULL) { if (string_value == NULL) {
// The environment variable is not set. // The environment variable is not set.
@ -792,7 +796,7 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
// Reads and returns the string environment variable corresponding to // Reads and returns the string environment variable corresponding to
// the given flag; if it's not set, returns default_value. // the given flag; if it's not set, returns default_value.
const char* StringFromGTestEnv(const char* flag, const char* default_value) { const char* StringFromGTestEnv(const char* flag, const char* default_value) {
const String env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const value = posix::GetEnv(env_var.c_str()); const char* const value = posix::GetEnv(env_var.c_str());
return value == NULL ? default_value : value; return value == NULL ? default_value : value;
} }

View File

@ -48,10 +48,10 @@ using internal::GetUnitTestImpl;
// Gets the summary of the failure message by omitting the stack trace // Gets the summary of the failure message by omitting the stack trace
// in it. // in it.
internal::String TestPartResult::ExtractSummary(const char* message) { std::string TestPartResult::ExtractSummary(const char* message) {
const char* const stack_trace = strstr(message, internal::kStackTraceMarker); const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
return stack_trace == NULL ? internal::String(message) : return stack_trace == NULL ? message :
internal::String(message, stack_trace - message); std::string(message, stack_trace);
} }
// Prints a TestPartResult object. // Prints a TestPartResult object.

View File

@ -58,10 +58,10 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
registered_tests = SkipSpaces(registered_tests); registered_tests = SkipSpaces(registered_tests);
Message errors; Message errors;
::std::set<String> tests; ::std::set<std::string> tests;
for (const char* names = registered_tests; names != NULL; for (const char* names = registered_tests; names != NULL;
names = SkipComma(names)) { names = SkipComma(names)) {
const String name = GetPrefixUntilComma(names); const std::string name = GetPrefixUntilComma(names);
if (tests.count(name) != 0) { if (tests.count(name) != 0) {
errors << "Test " << name << " is listed more than once.\n"; errors << "Test " << name << " is listed more than once.\n";
continue; continue;
@ -93,7 +93,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
} }
} }
const String& errors_str = errors.GetString(); const std::string& errors_str = errors.GetString();
if (errors_str != "") { if (errors_str != "") {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str()); errors_str.c_str());

View File

@ -364,7 +364,7 @@ void AssertHelper::operator=(const Message& message) const {
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
// Application pathname gotten in InitGoogleTest. // Application pathname gotten in InitGoogleTest.
String g_executable_path; std::string g_executable_path;
// Returns the current application's name, removing directory path if that // Returns the current application's name, removing directory path if that
// is present. // is present.
@ -383,29 +383,29 @@ FilePath GetCurrentExecutableName() {
// Functions for processing the gtest_output flag. // Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output. // Returns the output format, or "" for normal printed output.
String UnitTestOptions::GetOutputFormat() { std::string UnitTestOptions::GetOutputFormat() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
if (gtest_output_flag == NULL) return String(""); if (gtest_output_flag == NULL) return std::string("");
const char* const colon = strchr(gtest_output_flag, ':'); const char* const colon = strchr(gtest_output_flag, ':');
return (colon == NULL) ? return (colon == NULL) ?
String(gtest_output_flag) : std::string(gtest_output_flag) :
String(gtest_output_flag, colon - gtest_output_flag); std::string(gtest_output_flag, colon - gtest_output_flag);
} }
// Returns the name of the requested output file, or the default if none // Returns the name of the requested output file, or the default if none
// was explicitly specified. // was explicitly specified.
String UnitTestOptions::GetAbsolutePathToOutputFile() { std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
if (gtest_output_flag == NULL) if (gtest_output_flag == NULL)
return String(""); return "";
const char* const colon = strchr(gtest_output_flag, ':'); const char* const colon = strchr(gtest_output_flag, ':');
if (colon == NULL) if (colon == NULL)
return String(internal::FilePath::ConcatPaths( return internal::FilePath::ConcatPaths(
internal::FilePath( internal::FilePath(
UnitTest::GetInstance()->original_working_dir()), UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile)).ToString() ); internal::FilePath(kDefaultOutputFile)).string();
internal::FilePath output_name(colon + 1); internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath()) if (!output_name.IsAbsolutePath())
@ -418,12 +418,12 @@ String UnitTestOptions::GetAbsolutePathToOutputFile() {
internal::FilePath(colon + 1)); internal::FilePath(colon + 1));
if (!output_name.IsDirectory()) if (!output_name.IsDirectory())
return output_name.ToString(); return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName( internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(), output_name, internal::GetCurrentExecutableName(),
GetOutputFormat().c_str())); GetOutputFormat().c_str()));
return result.ToString(); return result.string();
} }
// Returns true iff the wildcard pattern matches the string. The // Returns true iff the wildcard pattern matches the string. The
@ -448,7 +448,8 @@ bool UnitTestOptions::PatternMatchesString(const char *pattern,
} }
} }
bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { bool UnitTestOptions::MatchesFilter(
const std::string& name, const char* filter) {
const char *cur_pattern = filter; const char *cur_pattern = filter;
for (;;) { for (;;) {
if (PatternMatchesString(cur_pattern, name.c_str())) { if (PatternMatchesString(cur_pattern, name.c_str())) {
@ -468,28 +469,24 @@ bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
} }
} }
// TODO(keithray): move String function implementations to gtest-string.cc.
// Returns true iff the user-specified filter matches the test case // Returns true iff the user-specified filter matches the test case
// name and the test name. // name and the test name.
bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
const String &test_name) { const std::string &test_name) {
const String& full_name = String::Format("%s.%s", const std::string& full_name = test_case_name + "." + test_name.c_str();
test_case_name.c_str(),
test_name.c_str());
// Split --gtest_filter at '-', if there is one, to separate into // Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions // positive filter and negative filter portions
const char* const p = GTEST_FLAG(filter).c_str(); const char* const p = GTEST_FLAG(filter).c_str();
const char* const dash = strchr(p, '-'); const char* const dash = strchr(p, '-');
String positive; std::string positive;
String negative; std::string negative;
if (dash == NULL) { if (dash == NULL) {
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
negative = String(""); negative = "";
} else { } else {
positive = String(p, dash - p); // Everything up to the dash positive = std::string(p, dash); // Everything up to the dash
negative = String(dash+1); // Everything after the dash negative = std::string(dash + 1); // Everything after the dash
if (positive.empty()) { if (positive.empty()) {
// Treat '-test1' as the same as '*-test1' // Treat '-test1' as the same as '*-test1'
positive = kUniversalFilter; positive = kUniversalFilter;
@ -609,7 +606,7 @@ AssertionResult HasOneFailure(const char* /* results_expr */,
const TestPartResultArray& results, const TestPartResultArray& results,
TestPartResult::Type type, TestPartResult::Type type,
const string& substr) { const string& substr) {
const String expected(type == TestPartResult::kFatalFailure ? const std::string expected(type == TestPartResult::kFatalFailure ?
"1 fatal failure" : "1 fatal failure" :
"1 non-fatal failure"); "1 non-fatal failure");
Message msg; Message msg;
@ -747,7 +744,7 @@ int UnitTestImpl::test_to_run_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
} }
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -757,9 +754,9 @@ int UnitTestImpl::test_to_run_count() const {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
(void)skip_count; (void)skip_count;
return String(""); return "";
} }
// Returns the current time in milliseconds. // Returns the current time in milliseconds.
@ -816,30 +813,7 @@ TimeInMillis GetTimeInMillis() {
// Utilities // Utilities
// class String // class String.
// Copies at most length characters from str into a newly-allocated
// piece of memory of size length+1. The memory is allocated with new[].
// A terminating null byte is written to the memory, and a pointer to it
// is returned. If str is NULL, NULL is returned.
static char* CloneString(const char* str, size_t length) {
if (str == NULL) {
return NULL;
} else {
char* const clone = new char[length + 1];
posix::StrNCpy(clone, str, length);
clone[length] = '\0';
return clone;
}
}
// Clones a 0-terminated C string, allocating memory using new. The
// caller is responsible for deleting[] the return value. Returns the
// cloned string, or NULL if the input is NULL.
const char * String::CloneCString(const char* c_str) {
return (c_str == NULL) ?
NULL : CloneString(c_str, strlen(c_str));
}
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
// Creates a UTF-16 wide string from the given ANSI string, allocating // Creates a UTF-16 wide string from the given ANSI string, allocating
@ -896,11 +870,6 @@ bool String::CStringEquals(const char * lhs, const char * rhs) {
// encoding, and streams the result to the given Message object. // encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) { Message* msg) {
// TODO(wan): consider allowing a testing::String object to
// contain '\0'. This will make it behave more like std::string,
// and will allow ToUtf8String() to return the correct encoding
// for '\0' s.t. we can get rid of the conditional here (and in
// several other places).
for (size_t i = 0; i != length; ) { // NOLINT for (size_t i = 0; i != length; ) { // NOLINT
if (wstr[i] != L'\0') { if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
@ -987,8 +956,8 @@ namespace internal {
// be inserted into the message. // be inserted into the message.
AssertionResult EqFailure(const char* expected_expression, AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression, const char* actual_expression,
const String& expected_value, const std::string& expected_value,
const String& actual_value, const std::string& actual_value,
bool ignoring_case) { bool ignoring_case) {
Message msg; Message msg;
msg << "Value of: " << actual_expression; msg << "Value of: " << actual_expression;
@ -1008,10 +977,11 @@ AssertionResult EqFailure(const char* expected_expression,
} }
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, std::string GetBoolAssertionFailureMessage(
const char* expression_text, const AssertionResult& assertion_result,
const char* actual_predicate_value, const char* expression_text,
const char* expected_predicate_value) { const char* actual_predicate_value,
const char* expected_predicate_value) {
const char* actual_message = assertion_result.message(); const char* actual_message = assertion_result.message();
Message msg; Message msg;
msg << "Value of: " << expression_text msg << "Value of: " << expression_text
@ -1357,7 +1327,7 @@ AssertionResult HRESULTFailureHelper(const char* expr,
# endif // GTEST_OS_WINDOWS_MOBILE # endif // GTEST_OS_WINDOWS_MOBILE
const String error_hex(String::Format("0x%08X ", hr)); const std::string error_hex(String::Format("0x%08X ", hr));
return ::testing::AssertionFailure() return ::testing::AssertionFailure()
<< "Expected: " << expr << " " << expected << ".\n" << "Expected: " << expr << " " << expected << ".\n"
<< " Actual: " << error_hex << error_text << "\n"; << " Actual: " << error_hex << error_text << "\n";
@ -1491,7 +1461,7 @@ inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs // and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane. // will be encoded as individual Unicode characters from Basic Normal Plane.
String WideStringToUtf8(const wchar_t* str, int num_chars) { std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (num_chars == -1) if (num_chars == -1)
num_chars = static_cast<int>(wcslen(str)); num_chars = static_cast<int>(wcslen(str));
@ -1515,12 +1485,12 @@ String WideStringToUtf8(const wchar_t* str, int num_chars) {
return StringStreamToString(&stream); return StringStreamToString(&stream);
} }
// Converts a wide C string to a String using the UTF-8 encoding. // Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)". // NULL will be converted to "(null)".
String String::ShowWideCString(const wchar_t * wide_c_str) { std::string String::ShowWideCString(const wchar_t * wide_c_str) {
if (wide_c_str == NULL) return String("(null)"); if (wide_c_str == NULL) return "(null)";
return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); return internal::WideStringToUtf8(wide_c_str, -1);
} }
// Compares two wide C strings. Returns true iff they have the same // Compares two wide C strings. Returns true iff they have the same
@ -1616,59 +1586,18 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
#endif // OS selector #endif // OS selector
} }
// Compares this with another String. // Returns true iff str ends with the given suffix, ignoring case.
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 // Any string is considered to end with an empty suffix.
// if this is greater than rhs. bool String::EndsWithCaseInsensitive(
int String::Compare(const String & rhs) const { const std::string& str, const std::string& suffix) {
const char* const lhs_c_str = c_str(); const size_t str_len = str.length();
const char* const rhs_c_str = rhs.c_str(); const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) &&
if (lhs_c_str == NULL) { CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL suffix.c_str());
} else if (rhs_c_str == NULL) {
return 1;
}
const size_t shorter_str_len =
length() <= rhs.length() ? length() : rhs.length();
for (size_t i = 0; i != shorter_str_len; i++) {
if (lhs_c_str[i] < rhs_c_str[i]) {
return -1;
} else if (lhs_c_str[i] > rhs_c_str[i]) {
return 1;
}
}
return (length() < rhs.length()) ? -1 :
(length() > rhs.length()) ? 1 : 0;
} }
// Returns true iff this String ends with the given suffix. *Any* // Formats a list of arguments to an std::string, using the same format
// String is considered to end with a NULL or empty suffix.
bool String::EndsWith(const char* suffix) const {
if (suffix == NULL || CStringEquals(suffix, "")) return true;
if (c_str() == NULL) return false;
const size_t this_len = strlen(c_str());
const size_t suffix_len = strlen(suffix);
return (this_len >= suffix_len) &&
CStringEquals(c_str() + this_len - suffix_len, suffix);
}
// Returns true iff this String ends with the given suffix, ignoring case.
// Any String is considered to end with a NULL or empty suffix.
bool String::EndsWithCaseInsensitive(const char* suffix) const {
if (suffix == NULL || CStringEquals(suffix, "")) return true;
if (c_str() == NULL) return false;
const size_t this_len = strlen(c_str());
const size_t suffix_len = strlen(suffix);
return (this_len >= suffix_len) &&
CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
}
// Formats a list of arguments to a String, using the same format
// spec string as for printf. // spec string as for printf.
// //
// We do not use the StringPrintf class as it is not universally // We do not use the StringPrintf class as it is not universally
@ -1678,7 +1607,7 @@ bool String::EndsWithCaseInsensitive(const char* suffix) const {
// If 4096 characters are not enough to format the input, or if // If 4096 characters are not enough to format the input, or if
// there's an error, "<formatting error or buffer exceeded>" is // there's an error, "<formatting error or buffer exceeded>" is
// returned. // returned.
String String::Format(const char * format, ...) { std::string String::Format(const char * format, ...) {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
@ -1705,46 +1634,42 @@ String String::Format(const char * format, ...) {
// always returns a negative value. For simplicity, we lump the two // always returns a negative value. For simplicity, we lump the two
// error cases together. // error cases together.
if (size < 0 || size >= kBufferSize) { if (size < 0 || size >= kBufferSize) {
return String("<formatting error or buffer exceeded>"); return "<formatting error or buffer exceeded>";
} else { } else {
return String(buffer, size); return std::string(buffer, size);
} }
} }
// Converts the buffer in a stringstream to a String, converting NUL // Converts the buffer in a stringstream to an std::string, converting NUL
// bytes to "\\0" along the way. // bytes to "\\0" along the way.
String StringStreamToString(::std::stringstream* ss) { std::string StringStreamToString(::std::stringstream* ss) {
const ::std::string& str = ss->str(); const ::std::string& str = ss->str();
const char* const start = str.c_str(); const char* const start = str.c_str();
const char* const end = start + str.length(); const char* const end = start + str.length();
// We need to use a helper stringstream to do this transformation std::string result;
// because String doesn't support push_back(). result.reserve(2 * (end - start));
::std::stringstream helper;
for (const char* ch = start; ch != end; ++ch) { for (const char* ch = start; ch != end; ++ch) {
if (*ch == '\0') { if (*ch == '\0') {
helper << "\\0"; // Replaces NUL with "\\0"; result += "\\0"; // Replaces NUL with "\\0";
} else { } else {
helper.put(*ch); result += *ch;
} }
} }
return String(helper.str().c_str()); return result;
} }
// Appends the user-supplied message to the Google-Test-generated message. // Appends the user-supplied message to the Google-Test-generated message.
String AppendUserMessage(const String& gtest_msg, std::string AppendUserMessage(const std::string& gtest_msg,
const Message& user_msg) { const Message& user_msg) {
// Appends the user message if it's non-empty. // Appends the user message if it's non-empty.
const String user_msg_string = user_msg.GetString(); const std::string user_msg_string = user_msg.GetString();
if (user_msg_string.empty()) { if (user_msg_string.empty()) {
return gtest_msg; return gtest_msg;
} }
Message msg; return gtest_msg + "\n" + user_msg_string;
msg << gtest_msg << "\n" << user_msg_string;
return msg.GetString();
} }
} // namespace internal } // namespace internal
@ -1810,7 +1735,7 @@ void TestResult::RecordProperty(const TestProperty& test_property) {
// Adds a failure if the key is a reserved attribute of Google Test // Adds a failure if the key is a reserved attribute of Google Test
// testcase tags. Returns true if the property is valid. // testcase tags. Returns true if the property is valid.
bool TestResult::ValidateTestProperty(const TestProperty& test_property) { bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
internal::String key(test_property.key()); const std::string& key = test_property.key();
if (key == "name" || key == "status" || key == "time" || key == "classname") { if (key == "name" || key == "status" || key == "time" || key == "classname") {
ADD_FAILURE() ADD_FAILURE()
<< "Reserved key used in RecordProperty(): " << "Reserved key used in RecordProperty(): "
@ -1911,7 +1836,7 @@ void Test::RecordProperty(const char* key, int value) {
namespace internal { namespace internal {
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const String& message) { const std::string& message) {
// This function is a friend of UnitTest and as such has access to // This function is a friend of UnitTest and as such has access to
// AddTestPartResult. // AddTestPartResult.
UnitTest::GetInstance()->AddTestPartResult( UnitTest::GetInstance()->AddTestPartResult(
@ -1919,7 +1844,7 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
NULL, // No info about the source file where the exception occurred. NULL, // No info about the source file where the exception occurred.
-1, // We have no info on which line caused the exception. -1, // We have no info on which line caused the exception.
message, message,
String()); // No stack trace, either. ""); // No stack trace, either.
} }
} // namespace internal } // namespace internal
@ -1996,13 +1921,13 @@ bool Test::HasSameFixtureClass() {
// function returns its result via an output parameter pointer because VC++ // function returns its result via an output parameter pointer because VC++
// prohibits creation of objects with destructors on stack in functions // prohibits creation of objects with destructors on stack in functions
// using __try (see error C2712). // using __try (see error C2712).
static internal::String* FormatSehExceptionMessage(DWORD exception_code, static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) { const char* location) {
Message message; Message message;
message << "SEH exception with code 0x" << std::setbase(16) << message << "SEH exception with code 0x" << std::setbase(16) <<
exception_code << std::setbase(10) << " thrown in " << location << "."; exception_code << std::setbase(10) << " thrown in " << location << ".";
return new internal::String(message.GetString()); return new std::string(message.GetString());
} }
#endif // GTEST_HAS_SEH #endif // GTEST_HAS_SEH
@ -2010,8 +1935,8 @@ static internal::String* FormatSehExceptionMessage(DWORD exception_code,
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
// Adds an "exception thrown" fatal failure to the current test. // Adds an "exception thrown" fatal failure to the current test.
static internal::String FormatCxxExceptionMessage(const char* description, static std::string FormatCxxExceptionMessage(const char* description,
const char* location) { const char* location) {
Message message; Message message;
if (description != NULL) { if (description != NULL) {
message << "C++ exception with description \"" << description << "\""; message << "C++ exception with description \"" << description << "\"";
@ -2023,7 +1948,7 @@ static internal::String FormatCxxExceptionMessage(const char* description,
return message.GetString(); return message.GetString();
} }
static internal::String PrintTestPartResultToString( static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result); const TestPartResult& test_part_result);
// A failed Google Test assertion will throw an exception of this type when // A failed Google Test assertion will throw an exception of this type when
@ -2059,7 +1984,7 @@ Result HandleSehExceptionsInMethodIfSupported(
// We create the exception message on the heap because VC++ prohibits // We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try // creation of objects with destructors on stack in functions using __try
// (see error C2712). // (see error C2712).
internal::String* exception_message = FormatSehExceptionMessage( std::string* exception_message = FormatSehExceptionMessage(
GetExceptionCode(), location); GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message); *exception_message);
@ -2263,11 +2188,11 @@ class TestNameIs {
// Returns true iff the test name of test_info matches name_. // Returns true iff the test name of test_info matches name_.
bool operator()(const TestInfo * test_info) const { bool operator()(const TestInfo * test_info) const {
return test_info && internal::String(test_info->name()).Compare(name_) == 0; return test_info && test_info->name() == name_;
} }
private: private:
internal::String name_; std::string name_;
}; };
} // namespace } // namespace
@ -2457,20 +2382,20 @@ void TestCase::UnshuffleTests() {
// //
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books". // FormatCountableNoun(5, "book", "books") returns "5 books".
static internal::String FormatCountableNoun(int count, static std::string FormatCountableNoun(int count,
const char * singular_form, const char * singular_form,
const char * plural_form) { const char * plural_form) {
return internal::String::Format("%d %s", count, return internal::String::Format("%d %s", count,
count == 1 ? singular_form : plural_form); count == 1 ? singular_form : plural_form);
} }
// Formats the count of tests. // Formats the count of tests.
static internal::String FormatTestCount(int test_count) { static std::string FormatTestCount(int test_count) {
return FormatCountableNoun(test_count, "test", "tests"); return FormatCountableNoun(test_count, "test", "tests");
} }
// Formats the count of test cases. // Formats the count of test cases.
static internal::String FormatTestCaseCount(int test_case_count) { static std::string FormatTestCaseCount(int test_case_count) {
return FormatCountableNoun(test_case_count, "test case", "test cases"); return FormatCountableNoun(test_case_count, "test case", "test cases");
} }
@ -2495,8 +2420,8 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) {
} }
} }
// Prints a TestPartResult to a String. // Prints a TestPartResult to an std::string.
static internal::String PrintTestPartResultToString( static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) { const TestPartResult& test_part_result) {
return (Message() return (Message()
<< internal::FormatFileLocation(test_part_result.file_name(), << internal::FormatFileLocation(test_part_result.file_name(),
@ -2507,7 +2432,7 @@ static internal::String PrintTestPartResultToString(
// Prints a TestPartResult. // Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) { static void PrintTestPartResult(const TestPartResult& test_part_result) {
const internal::String& result = const std::string& result =
PrintTestPartResultToString(test_part_result); PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str()); printf("%s\n", result.c_str());
fflush(stdout); fflush(stdout);
@ -2700,7 +2625,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
// Prints the filter if it's not *. This reminds the user that some // Prints the filter if it's not *. This reminds the user that some
// tests may be skipped. // tests may be skipped.
if (!internal::String::CStringEquals(filter, kUniversalFilter)) { if (!String::CStringEquals(filter, kUniversalFilter)) {
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(COLOR_YELLOW,
"Note: %s filter = %s\n", GTEST_NAME_, filter); "Note: %s filter = %s\n", GTEST_NAME_, filter);
} }
@ -2734,7 +2659,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
} }
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
const internal::String counts = const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s", counts.c_str(), test_case.name()); printf("%s from %s", counts.c_str(), test_case.name());
@ -2787,7 +2712,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
if (!GTEST_FLAG(print_time)) return; if (!GTEST_FLAG(print_time)) return;
const internal::String counts = const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s (%s ms total)\n\n", printf("%s from %s (%s ms total)\n\n",
@ -3006,18 +2931,20 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
// is_attribute is true, the text is meant to appear as an attribute // is_attribute is true, the text is meant to appear as an attribute
// value, and normalizable whitespace is preserved by replacing it // value, and normalizable whitespace is preserved by replacing it
// with character references. // with character references.
static String EscapeXml(const char* str, bool is_attribute); static std::string EscapeXml(const char* str, bool is_attribute);
// Returns the given string with all characters invalid in XML removed. // Returns the given string with all characters invalid in XML removed.
static string RemoveInvalidXmlCharacters(const string& str); static string RemoveInvalidXmlCharacters(const string& str);
// Convenience wrapper around EscapeXml when str is an attribute value. // Convenience wrapper around EscapeXml when str is an attribute value.
static String EscapeXmlAttribute(const char* str) { static std::string EscapeXmlAttribute(const char* str) {
return EscapeXml(str, true); return EscapeXml(str, true);
} }
// Convenience wrapper around EscapeXml when str is not an attribute value. // Convenience wrapper around EscapeXml when str is not an attribute value.
static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } static std::string EscapeXmlText(const char* str) {
return EscapeXml(str, false);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
static void OutputXmlCDataSection(::std::ostream* stream, const char* data); static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
@ -3035,12 +2962,12 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
// Produces a string representing the test properties in a result as space // Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs. // delimited XML attributes based on the property key="value" pairs.
// When the String is not empty, it includes a space at the beginning, // When the std::string is not empty, it includes a space at the beginning,
// to delimit this attribute from prior attributes. // to delimit this attribute from prior attributes.
static String TestPropertiesAsXmlAttributes(const TestResult& result); static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
// The output file. // The output file.
const String output_file_; const std::string output_file_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
}; };
@ -3098,7 +3025,8 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
// most invalid characters can be retained using character references. // most invalid characters can be retained using character references.
// TODO(wan): It might be nice to have a minimally invasive, human-readable // TODO(wan): It might be nice to have a minimally invasive, human-readable
// escaping scheme for invalid characters, rather than dropping them. // escaping scheme for invalid characters, rather than dropping them.
String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { std::string XmlUnitTestResultPrinter::EscapeXml(
const char* str, bool is_attribute) {
Message m; Message m;
if (str != NULL) { if (str != NULL) {
@ -3316,7 +3244,7 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
// Produces a string representing the test properties in a result as space // Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs. // delimited XML attributes based on the property key="value" pairs.
String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
const TestResult& result) { const TestResult& result) {
Message attributes; Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) { for (int i = 0; i < result.test_property_count(); ++i) {
@ -3528,17 +3456,17 @@ ScopedTrace::~ScopedTrace()
// class OsStackTraceGetter // class OsStackTraceGetter
// Returns the current OS stack trace as a String. Parameters: // Returns the current OS stack trace as an std::string. Parameters:
// //
// max_depth - the maximum number of stack frames to be included // max_depth - the maximum number of stack frames to be included
// in the trace. // in the trace.
// skip_count - the number of top frames to be skipped; doesn't count // skip_count - the number of top frames to be skipped; doesn't count
// against max_depth. // against max_depth.
// //
String OsStackTraceGetter::CurrentStackTrace(int /* max_depth */, string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
int /* skip_count */) int /* skip_count */)
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
return String(""); return "";
} }
void OsStackTraceGetter::UponLeavingGTest() void OsStackTraceGetter::UponLeavingGTest()
@ -3759,8 +3687,8 @@ void UnitTest::AddTestPartResult(
TestPartResult::Type result_type, TestPartResult::Type result_type,
const char* file_name, const char* file_name,
int line_number, int line_number,
const internal::String& message, const std::string& message,
const internal::String& os_stack_trace) const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg; Message msg;
msg << message; msg << message;
@ -4008,7 +3936,7 @@ void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
// Initializes event listeners performing XML output as specified by // Initializes event listeners performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest. // UnitTestOptions. Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureXmlOutput() { void UnitTestImpl::ConfigureXmlOutput() {
const String& output_format = UnitTestOptions::GetOutputFormat(); const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml") { if (output_format == "xml") {
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
@ -4020,13 +3948,13 @@ void UnitTestImpl::ConfigureXmlOutput() {
} }
#if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
// Initializes event listeners for streaming test results in String form. // Initializes event listeners for streaming test results in string form.
// Must not be called before InitGoogleTest. // Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureStreamingOutput() { void UnitTestImpl::ConfigureStreamingOutput() {
const string& target = GTEST_FLAG(stream_result_to); const std::string& target = GTEST_FLAG(stream_result_to);
if (!target.empty()) { if (!target.empty()) {
const size_t pos = target.find(':'); const size_t pos = target.find(':');
if (pos != string::npos) { if (pos != std::string::npos) {
listeners()->Append(new StreamingListener(target.substr(0, pos), listeners()->Append(new StreamingListener(target.substr(0, pos),
target.substr(pos+1))); target.substr(pos+1)));
} else { } else {
@ -4080,7 +4008,7 @@ void UnitTestImpl::PostFlagParsingInit() {
class TestCaseNameIs { class TestCaseNameIs {
public: public:
// Constructor. // Constructor.
explicit TestCaseNameIs(const String& name) explicit TestCaseNameIs(const std::string& name)
: name_(name) {} : name_(name) {}
// Returns true iff the name of test_case matches name_. // Returns true iff the name of test_case matches name_.
@ -4089,7 +4017,7 @@ class TestCaseNameIs {
} }
private: private:
String name_; std::string name_;
}; };
// Finds and returns a TestCase with the given name. If one doesn't // Finds and returns a TestCase with the given name. If one doesn't
@ -4121,7 +4049,7 @@ TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
// Is this a death test case? // Is this a death test case?
if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), if (internal::UnitTestOptions::MatchesFilter(test_case_name,
kDeathTestCaseFilter)) { kDeathTestCaseFilter)) {
// Yes. Inserts the test case after the last death test case // Yes. Inserts the test case after the last death test case
// defined so far. This only works when the test cases haven't // defined so far. This only works when the test cases haven't
@ -4400,12 +4328,12 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
int num_selected_tests = 0; int num_selected_tests = 0;
for (size_t i = 0; i < test_cases_.size(); i++) { for (size_t i = 0; i < test_cases_.size(); i++) {
TestCase* const test_case = test_cases_[i]; TestCase* const test_case = test_cases_[i];
const String &test_case_name = test_case->name(); const std::string &test_case_name = test_case->name();
test_case->set_should_run(false); test_case->set_should_run(false);
for (size_t j = 0; j < test_case->test_info_list().size(); j++) { for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
TestInfo* const test_info = test_case->test_info_list()[j]; TestInfo* const test_info = test_case->test_info_list()[j];
const String test_name(test_info->name()); const std::string test_name(test_info->name());
// A test is disabled if test case name or test name matches // A test is disabled if test case name or test name matches
// kDisableTestFilter. // kDisableTestFilter.
const bool is_disabled = const bool is_disabled =
@ -4517,7 +4445,7 @@ void UnitTestImpl::UnshuffleTests() {
} }
} }
// Returns the current OS stack trace as a String. // Returns the current OS stack trace as an std::string.
// //
// The maximum number of stack frames to be included is specified by // The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter // the gtest_stack_trace_depth flag. The skip_count parameter
@ -4527,8 +4455,8 @@ void UnitTestImpl::UnshuffleTests() {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
int skip_count) { int skip_count) {
// We pass skip_count + 1 to skip this wrapper function in addition // We pass skip_count + 1 to skip this wrapper function in addition
// to what the user really wants to skip. // to what the user really wants to skip.
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
@ -4576,7 +4504,7 @@ const char* ParseFlagValue(const char* str,
if (str == NULL || flag == NULL) return NULL; if (str == NULL || flag == NULL) return NULL;
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
const size_t flag_len = flag_str.length(); const size_t flag_len = flag_str.length();
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
@ -4641,7 +4569,7 @@ bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
// //
// On success, stores the value of the flag in *value, and returns // On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value. // true. On failure, returns false without changing *value.
bool ParseStringFlag(const char* str, const char* flag, String* value) { bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
// Gets the value of the flag as a string. // Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, false); const char* const value_str = ParseFlagValue(str, flag, false);
@ -4693,7 +4621,7 @@ static void PrintColorEncoded(const char* str) {
return; return;
} }
ColoredPrintf(color, "%s", String(str, p - str).c_str()); ColoredPrintf(color, "%s", std::string(str, p).c_str());
const char ch = p[1]; const char ch = p[1];
str = p + 2; str = p + 2;
@ -4783,7 +4711,7 @@ static const char kColorEncodedHelpMessage[] =
template <typename CharType> template <typename CharType>
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
for (int i = 1; i < *argc; i++) { for (int i = 1; i < *argc; i++) {
const String arg_string = StreamableToString(argv[i]); const std::string arg_string = StreamableToString(argv[i]);
const char* const arg = arg_string.c_str(); const char* const arg = arg_string.c_str();
using internal::ParseBoolFlag; using internal::ParseBoolFlag;

View File

@ -77,7 +77,6 @@ using testing::internal::GetLastErrnoDescription;
using testing::internal::GetUnitTestImpl; using testing::internal::GetUnitTestImpl;
using testing::internal::InDeathTestChild; using testing::internal::InDeathTestChild;
using testing::internal::ParseNaturalNumber; using testing::internal::ParseNaturalNumber;
using testing::internal::String;
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -1139,26 +1138,26 @@ TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
BiggestParsable result = 0; BiggestParsable result = 0;
// Rejects non-numbers. // Rejects non-numbers.
EXPECT_FALSE(ParseNaturalNumber(String("non-number string"), &result)); EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
// Rejects numbers with whitespace prefix. // Rejects numbers with whitespace prefix.
EXPECT_FALSE(ParseNaturalNumber(String(" 123"), &result)); EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
// Rejects negative numbers. // Rejects negative numbers.
EXPECT_FALSE(ParseNaturalNumber(String("-123"), &result)); EXPECT_FALSE(ParseNaturalNumber("-123", &result));
// Rejects numbers starting with a plus sign. // Rejects numbers starting with a plus sign.
EXPECT_FALSE(ParseNaturalNumber(String("+123"), &result)); EXPECT_FALSE(ParseNaturalNumber("+123", &result));
errno = 0; errno = 0;
} }
TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) { TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
BiggestParsable result = 0; BiggestParsable result = 0;
EXPECT_FALSE(ParseNaturalNumber(String("99999999999999999999999"), &result)); EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
signed char char_result = 0; signed char char_result = 0;
EXPECT_FALSE(ParseNaturalNumber(String("200"), &char_result)); EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
errno = 0; errno = 0;
} }
@ -1166,16 +1165,16 @@ TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
BiggestParsable result = 0; BiggestParsable result = 0;
result = 0; result = 0;
ASSERT_TRUE(ParseNaturalNumber(String("123"), &result)); ASSERT_TRUE(ParseNaturalNumber("123", &result));
EXPECT_EQ(123U, result); EXPECT_EQ(123U, result);
// Check 0 as an edge case. // Check 0 as an edge case.
result = 1; result = 1;
ASSERT_TRUE(ParseNaturalNumber(String("0"), &result)); ASSERT_TRUE(ParseNaturalNumber("0", &result));
EXPECT_EQ(0U, result); EXPECT_EQ(0U, result);
result = 1; result = 1;
ASSERT_TRUE(ParseNaturalNumber(String("00000"), &result)); ASSERT_TRUE(ParseNaturalNumber("00000", &result));
EXPECT_EQ(0U, result); EXPECT_EQ(0U, result);
} }
@ -1211,11 +1210,11 @@ TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
short short_result = 0; short short_result = 0;
ASSERT_TRUE(ParseNaturalNumber(String("123"), &short_result)); ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
EXPECT_EQ(123, short_result); EXPECT_EQ(123, short_result);
signed char char_result = 0; signed char char_result = 0;
ASSERT_TRUE(ParseNaturalNumber(String("123"), &char_result)); ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
EXPECT_EQ(123, char_result); EXPECT_EQ(123, char_result);
} }
@ -1245,7 +1244,6 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
using testing::internal::CaptureStderr; using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr; using testing::internal::GetCapturedStderr;
using testing::internal::String;
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
// defined but do not trigger failures when death tests are not available on // defined but do not trigger failures when death tests are not available on
@ -1255,7 +1253,7 @@ TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
// when death tests are not supported. // when death tests are not supported.
CaptureStderr(); CaptureStderr();
EXPECT_DEATH_IF_SUPPORTED(;, ""); EXPECT_DEATH_IF_SUPPORTED(;, "");
String output = GetCapturedStderr(); std::string output = GetCapturedStderr();
ASSERT_TRUE(NULL != strstr(output.c_str(), ASSERT_TRUE(NULL != strstr(output.c_str(),
"Death tests are not supported on this platform")); "Death tests are not supported on this platform"));
ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));

View File

@ -100,7 +100,7 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
# else # else
EXPECT_STREQ(GTEST_PATH_SEP_, cwd.c_str()); EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
# endif # endif
} }
@ -109,7 +109,6 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
TEST(IsEmptyTest, ReturnsTrueForEmptyPath) { TEST(IsEmptyTest, ReturnsTrueForEmptyPath) {
EXPECT_TRUE(FilePath("").IsEmpty()); EXPECT_TRUE(FilePath("").IsEmpty());
EXPECT_TRUE(FilePath(NULL).IsEmpty());
} }
TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) { TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {
@ -121,38 +120,38 @@ TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {
// RemoveDirectoryName "" -> "" // RemoveDirectoryName "" -> ""
TEST(RemoveDirectoryNameTest, WhenEmptyName) { TEST(RemoveDirectoryNameTest, WhenEmptyName) {
EXPECT_STREQ("", FilePath("").RemoveDirectoryName().c_str()); EXPECT_EQ("", FilePath("").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "afile" -> "afile" // RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) { TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_STREQ("afile", EXPECT_EQ("afile",
FilePath("afile").RemoveDirectoryName().c_str()); FilePath("afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "/afile" -> "afile" // RemoveDirectoryName "/afile" -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
EXPECT_STREQ("afile", EXPECT_EQ("afile",
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().c_str()); FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/" -> "" // RemoveDirectoryName "adir/" -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
EXPECT_STREQ("", EXPECT_EQ("",
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().c_str()); FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/afile" -> "afile" // RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_STREQ("afile", EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().c_str()); FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/subdir/afile" -> "afile" // RemoveDirectoryName "adir/subdir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_STREQ("afile", EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveDirectoryName().c_str()); .RemoveDirectoryName().string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
@ -162,26 +161,23 @@ TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
// RemoveDirectoryName("/afile") -> "afile" // RemoveDirectoryName("/afile") -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) { TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) {
EXPECT_STREQ("afile", EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string());
FilePath("/afile").RemoveDirectoryName().c_str());
} }
// RemoveDirectoryName("adir/") -> "" // RemoveDirectoryName("adir/") -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) { TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) {
EXPECT_STREQ("", EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string());
FilePath("adir/").RemoveDirectoryName().c_str());
} }
// RemoveDirectoryName("adir/afile") -> "afile" // RemoveDirectoryName("adir/afile") -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) { TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) {
EXPECT_STREQ("afile", EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string());
FilePath("adir/afile").RemoveDirectoryName().c_str());
} }
// RemoveDirectoryName("adir/subdir/afile") -> "afile" // RemoveDirectoryName("adir/subdir/afile") -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) { TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
EXPECT_STREQ("afile", EXPECT_EQ("afile",
FilePath("adir/subdir/afile").RemoveDirectoryName().c_str()); FilePath("adir/subdir/afile").RemoveDirectoryName().string());
} }
#endif #endif
@ -190,38 +186,35 @@ TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
TEST(RemoveFileNameTest, EmptyName) { TEST(RemoveFileNameTest, EmptyName) {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
// On Windows CE, we use the root as the current directory. // On Windows CE, we use the root as the current directory.
EXPECT_STREQ(GTEST_PATH_SEP_, EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
FilePath("").RemoveFileName().c_str());
#else #else
EXPECT_STREQ("." GTEST_PATH_SEP_, EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
FilePath("").RemoveFileName().c_str());
#endif #endif
} }
// RemoveFileName "adir/" -> "adir/" // RemoveFileName "adir/" -> "adir/"
TEST(RemoveFileNameTest, ButNoFile) { TEST(RemoveFileNameTest, ButNoFile) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().c_str()); FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
} }
// RemoveFileName "adir/afile" -> "adir/" // RemoveFileName "adir/afile" -> "adir/"
TEST(RemoveFileNameTest, GivesDirName) { TEST(RemoveFileNameTest, GivesDirName) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string());
.RemoveFileName().c_str());
} }
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" // RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirName) { TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveFileName().c_str()); .RemoveFileName().string());
} }
// RemoveFileName "/afile" -> "/" // RemoveFileName "/afile" -> "/"
TEST(RemoveFileNameTest, GivesRootDir) { TEST(RemoveFileNameTest, GivesRootDir) {
EXPECT_STREQ(GTEST_PATH_SEP_, EXPECT_EQ(GTEST_PATH_SEP_,
FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().c_str()); FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
@ -231,26 +224,25 @@ TEST(RemoveFileNameTest, GivesRootDir) {
// RemoveFileName("adir/") -> "adir/" // RemoveFileName("adir/") -> "adir/"
TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) { TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir/").RemoveFileName().c_str()); FilePath("adir/").RemoveFileName().string());
} }
// RemoveFileName("adir/afile") -> "adir/" // RemoveFileName("adir/afile") -> "adir/"
TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) { TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir/afile").RemoveFileName().c_str()); FilePath("adir/afile").RemoveFileName().string());
} }
// RemoveFileName("adir/subdir/afile") -> "adir/subdir/" // RemoveFileName("adir/subdir/afile") -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) { TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) {
EXPECT_STREQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir/subdir/afile").RemoveFileName().c_str()); FilePath("adir/subdir/afile").RemoveFileName().string());
} }
// RemoveFileName("/afile") -> "\" // RemoveFileName("/afile") -> "\"
TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
EXPECT_STREQ(GTEST_PATH_SEP_, EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string());
FilePath("/afile").RemoveFileName().c_str());
} }
#endif #endif
@ -258,125 +250,120 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
0, "xml"); 0, "xml");
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
12, "xml"); 12, "xml");
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 0, "xml"); FilePath("bar"), 0, "xml");
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 12, "xml"); FilePath("bar"), 12, "xml");
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
0, "xml"); 0, "xml");
EXPECT_STREQ("bar.xml", actual.c_str()); EXPECT_EQ("bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
14, "xml"); 14, "xml");
EXPECT_STREQ("bar_14.xml", actual.c_str()); EXPECT_EQ("bar_14.xml", actual.string());
} }
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
FilePath("bar.xml")); FilePath("bar.xml"));
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar.xml")); FilePath("bar.xml"));
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(ConcatPathsTest, Path1BeingEmpty) { TEST(ConcatPathsTest, Path1BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""),
FilePath("bar.xml")); FilePath("bar.xml"));
EXPECT_STREQ("bar.xml", actual.c_str()); EXPECT_EQ("bar.xml", actual.string());
} }
TEST(ConcatPathsTest, Path2BeingEmpty) { TEST(ConcatPathsTest, Path2BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath(""));
FilePath("")); EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_, actual.c_str());
} }
TEST(ConcatPathsTest, BothPathBeingEmpty) { TEST(ConcatPathsTest, BothPathBeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""),
FilePath("")); FilePath(""));
EXPECT_STREQ("", actual.c_str()); EXPECT_EQ("", actual.string());
} }
TEST(ConcatPathsTest, Path1ContainsPathSep) { TEST(ConcatPathsTest, Path1ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"), FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"),
FilePath("foobar.xml")); FilePath("foobar.xml"));
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml",
actual.c_str()); actual.string());
} }
TEST(ConcatPathsTest, Path2ContainsPathSep) { TEST(ConcatPathsTest, Path2ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths( FilePath actual = FilePath::ConcatPaths(
FilePath("foo" GTEST_PATH_SEP_), FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
actual.c_str()); actual.string());
} }
TEST(ConcatPathsTest, Path2EndsWithPathSep) { TEST(ConcatPathsTest, Path2EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
FilePath("bar" GTEST_PATH_SEP_)); FilePath("bar" GTEST_PATH_SEP_));
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.c_str()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
} }
// RemoveTrailingPathSeparator "" -> "" // RemoveTrailingPathSeparator "" -> ""
TEST(RemoveTrailingPathSeparatorTest, EmptyString) { TEST(RemoveTrailingPathSeparatorTest, EmptyString) {
EXPECT_STREQ("", EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string());
FilePath("").RemoveTrailingPathSeparator().c_str());
} }
// RemoveTrailingPathSeparator "foo" -> "foo" // RemoveTrailingPathSeparator "foo" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
EXPECT_STREQ("foo", EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string());
FilePath("foo").RemoveTrailingPathSeparator().c_str());
} }
// RemoveTrailingPathSeparator "foo/" -> "foo" // RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_STREQ( EXPECT_EQ("foo",
"foo", FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().c_str());
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
EXPECT_STREQ("foo", EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
FilePath("foo/").RemoveTrailingPathSeparator().c_str());
#endif #endif
} }
// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/" // RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
.RemoveTrailingPathSeparator().c_str()); .RemoveTrailingPathSeparator().string());
} }
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar") FilePath("foo" GTEST_PATH_SEP_ "bar")
.RemoveTrailingPathSeparator().c_str()); .RemoveTrailingPathSeparator().string());
} }
TEST(DirectoryTest, RootDirectoryExists) { TEST(DirectoryTest, RootDirectoryExists) {
@ -431,40 +418,35 @@ TEST(DirectoryTest, CurrentDirectoryExists) {
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} }
TEST(NormalizeTest, NullStringsEqualEmptyDirectory) {
EXPECT_STREQ("", FilePath(NULL).c_str());
EXPECT_STREQ("", FilePath(String(NULL)).c_str());
}
// "foo/bar" == foo//bar" == "foo///bar" // "foo/bar" == foo//bar" == "foo///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar").c_str()); FilePath("foo" GTEST_PATH_SEP_ "bar").string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").c_str()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
GTEST_PATH_SEP_ "bar").c_str()); GTEST_PATH_SEP_ "bar").string());
} }
// "/bar" == //bar" == "///bar" // "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
EXPECT_STREQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ "bar").c_str()); FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_STREQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").c_str()); FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_STREQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").c_str()); FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
} }
// "foo/" == foo//" == "foo///" // "foo/" == foo//" == "foo///"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_).c_str()); FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).c_str()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).c_str()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
@ -473,12 +455,12 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
// regardless of their combination (e.g. "foo\" =="foo/\" == // regardless of their combination (e.g. "foo\" =="foo/\" ==
// "foo\\/"). // "foo\\/").
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo/").c_str()); FilePath("foo/").string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ "/").c_str()); FilePath("foo" GTEST_PATH_SEP_ "/").string());
EXPECT_STREQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo//" GTEST_PATH_SEP_).c_str()); FilePath("foo//" GTEST_PATH_SEP_).string());
} }
#endif #endif
@ -487,31 +469,31 @@ TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) {
FilePath default_path; FilePath default_path;
FilePath non_default_path("path"); FilePath non_default_path("path");
non_default_path = default_path; non_default_path = default_path;
EXPECT_STREQ("", non_default_path.c_str()); EXPECT_EQ("", non_default_path.string());
EXPECT_STREQ("", default_path.c_str()); // RHS var is unchanged. EXPECT_EQ("", default_path.string()); // RHS var is unchanged.
} }
TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) { TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) {
FilePath non_default_path("path"); FilePath non_default_path("path");
FilePath default_path; FilePath default_path;
default_path = non_default_path; default_path = non_default_path;
EXPECT_STREQ("path", default_path.c_str()); EXPECT_EQ("path", default_path.string());
EXPECT_STREQ("path", non_default_path.c_str()); // RHS var is unchanged. EXPECT_EQ("path", non_default_path.string()); // RHS var is unchanged.
} }
TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
const FilePath const_default_path("const_path"); const FilePath const_default_path("const_path");
FilePath non_default_path("path"); FilePath non_default_path("path");
non_default_path = const_default_path; non_default_path = const_default_path;
EXPECT_STREQ("const_path", non_default_path.c_str()); EXPECT_EQ("const_path", non_default_path.string());
} }
class DirectoryCreationTest : public Test { class DirectoryCreationTest : public Test {
protected: protected:
virtual void SetUp() { virtual void SetUp() {
testdata_path_.Set(FilePath(String::Format("%s%s%s", testdata_path_.Set(FilePath(
TempDir().c_str(), GetCurrentExecutableName().c_str(), TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_))); "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
@ -532,21 +514,21 @@ class DirectoryCreationTest : public Test {
posix::RmDir(testdata_path_.c_str()); posix::RmDir(testdata_path_.c_str());
} }
String TempDir() const { std::string TempDir() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
return String("\\temp\\"); return "\\temp\\";
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
const char* temp_dir = posix::GetEnv("TEMP"); const char* temp_dir = posix::GetEnv("TEMP");
if (temp_dir == NULL || temp_dir[0] == '\0') if (temp_dir == NULL || temp_dir[0] == '\0')
return String("\\temp\\"); return "\\temp\\";
else if (String(temp_dir).EndsWith("\\")) else if (temp_dir[strlen(temp_dir) - 1] == '\\')
return String(temp_dir); return temp_dir;
else else
return String::Format("%s\\", temp_dir); return std::string(temp_dir) + "\\";
#elif GTEST_OS_LINUX_ANDROID #elif GTEST_OS_LINUX_ANDROID
return String("/sdcard/"); return "/sdcard/";
#else #else
return String("/tmp/"); return "/tmp/";
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} }
@ -566,13 +548,13 @@ class DirectoryCreationTest : public Test {
}; };
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.c_str(); EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
EXPECT_TRUE(testdata_path_.DirectoryExists()); EXPECT_TRUE(testdata_path_.DirectoryExists());
} }
TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.c_str(); EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
// Call 'create' again... should still succeed. // Call 'create' again... should still succeed.
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
@ -581,7 +563,7 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt")); FilePath("unique"), "txt"));
EXPECT_STREQ(unique_file0_.c_str(), file_path.c_str()); EXPECT_EQ(unique_file0_.string(), file_path.string());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
testdata_path_.CreateDirectoriesRecursively(); testdata_path_.CreateDirectoriesRecursively();
@ -591,7 +573,7 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt")); FilePath("unique"), "txt"));
EXPECT_STREQ(unique_file1_.c_str(), file_path2.c_str()); EXPECT_EQ(unique_file1_.string(), file_path2.string());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str()); CreateTextFile(file_path2.c_str());
EXPECT_TRUE(file_path2.FileOrDirectoryExists()); EXPECT_TRUE(file_path2.FileOrDirectoryExists());
@ -612,43 +594,43 @@ TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {
TEST(FilePathTest, DefaultConstructor) { TEST(FilePathTest, DefaultConstructor) {
FilePath fp; FilePath fp;
EXPECT_STREQ("", fp.c_str()); EXPECT_EQ("", fp.string());
} }
TEST(FilePathTest, CharAndCopyConstructors) { TEST(FilePathTest, CharAndCopyConstructors) {
const FilePath fp("spicy"); const FilePath fp("spicy");
EXPECT_STREQ("spicy", fp.c_str()); EXPECT_EQ("spicy", fp.string());
const FilePath fp_copy(fp); const FilePath fp_copy(fp);
EXPECT_STREQ("spicy", fp_copy.c_str()); EXPECT_EQ("spicy", fp_copy.string());
} }
TEST(FilePathTest, StringConstructor) { TEST(FilePathTest, StringConstructor) {
const FilePath fp(String("cider")); const FilePath fp(std::string("cider"));
EXPECT_STREQ("cider", fp.c_str()); EXPECT_EQ("cider", fp.string());
} }
TEST(FilePathTest, Set) { TEST(FilePathTest, Set) {
const FilePath apple("apple"); const FilePath apple("apple");
FilePath mac("mac"); FilePath mac("mac");
mac.Set(apple); // Implement Set() since overloading operator= is forbidden. mac.Set(apple); // Implement Set() since overloading operator= is forbidden.
EXPECT_STREQ("apple", mac.c_str()); EXPECT_EQ("apple", mac.string());
EXPECT_STREQ("apple", apple.c_str()); EXPECT_EQ("apple", apple.string());
} }
TEST(FilePathTest, ToString) { TEST(FilePathTest, ToString) {
const FilePath file("drink"); const FilePath file("drink");
String str(file.ToString()); EXPECT_EQ("drink", file.string());
EXPECT_STREQ("drink", str.c_str());
} }
TEST(FilePathTest, RemoveExtension) { TEST(FilePathTest, RemoveExtension) {
EXPECT_STREQ("app", FilePath("app.exe").RemoveExtension("exe").c_str()); EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string());
EXPECT_STREQ("APP", FilePath("APP.EXE").RemoveExtension("exe").c_str()); EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string());
EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string());
} }
TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) { TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {
EXPECT_STREQ("app", FilePath("app").RemoveExtension("exe").c_str()); EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string());
} }
TEST(FilePathTest, IsDirectory) { TEST(FilePathTest, IsDirectory) {

View File

@ -45,10 +45,9 @@ using ::testing::TestEventListener;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::UnitTest; using ::testing::UnitTest;
using ::testing::internal::String;
// Used by tests to register their events. // Used by tests to register their events.
std::vector<String>* g_events = NULL; std::vector<std::string>* g_events = NULL;
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -119,54 +118,52 @@ class EventRecordingListener : public TestEventListener {
} }
private: private:
String GetFullMethodName(const char* name) { std::string GetFullMethodName(const char* name) {
Message message; return name_ + "." + name;
message << name_ << "." << name;
return message.GetString();
} }
String name_; std::string name_;
}; };
class EnvironmentInvocationCatcher : public Environment { class EnvironmentInvocationCatcher : public Environment {
protected: protected:
virtual void SetUp() { virtual void SetUp() {
g_events->push_back(String("Environment::SetUp")); g_events->push_back("Environment::SetUp");
} }
virtual void TearDown() { virtual void TearDown() {
g_events->push_back(String("Environment::TearDown")); g_events->push_back("Environment::TearDown");
} }
}; };
class ListenerTest : public Test { class ListenerTest : public Test {
protected: protected:
static void SetUpTestCase() { static void SetUpTestCase() {
g_events->push_back(String("ListenerTest::SetUpTestCase")); g_events->push_back("ListenerTest::SetUpTestCase");
} }
static void TearDownTestCase() { static void TearDownTestCase() {
g_events->push_back(String("ListenerTest::TearDownTestCase")); g_events->push_back("ListenerTest::TearDownTestCase");
} }
virtual void SetUp() { virtual void SetUp() {
g_events->push_back(String("ListenerTest::SetUp")); g_events->push_back("ListenerTest::SetUp");
} }
virtual void TearDown() { virtual void TearDown() {
g_events->push_back(String("ListenerTest::TearDown")); g_events->push_back("ListenerTest::TearDown");
} }
}; };
TEST_F(ListenerTest, DoesFoo) { TEST_F(ListenerTest, DoesFoo) {
// Test execution order within a test case is not guaranteed so we are not // Test execution order within a test case is not guaranteed so we are not
// recording the test name. // recording the test name.
g_events->push_back(String("ListenerTest::* Test Body")); g_events->push_back("ListenerTest::* Test Body");
SUCCEED(); // Triggers OnTestPartResult. SUCCEED(); // Triggers OnTestPartResult.
} }
TEST_F(ListenerTest, DoesBar) { TEST_F(ListenerTest, DoesBar) {
g_events->push_back(String("ListenerTest::* Test Body")); g_events->push_back("ListenerTest::* Test Body");
SUCCEED(); // Triggers OnTestPartResult. SUCCEED(); // Triggers OnTestPartResult.
} }
@ -177,7 +174,7 @@ TEST_F(ListenerTest, DoesBar) {
using ::testing::internal::EnvironmentInvocationCatcher; using ::testing::internal::EnvironmentInvocationCatcher;
using ::testing::internal::EventRecordingListener; using ::testing::internal::EventRecordingListener;
void VerifyResults(const std::vector<String>& data, void VerifyResults(const std::vector<std::string>& data,
const char* const* expected_data, const char* const* expected_data,
int expected_data_size) { int expected_data_size) {
const int actual_size = data.size(); const int actual_size = data.size();
@ -201,7 +198,7 @@ void VerifyResults(const std::vector<String>& data,
} }
int main(int argc, char **argv) { int main(int argc, char **argv) {
std::vector<String> events; std::vector<std::string> events;
g_events = &events; g_events = &events;
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);

View File

@ -39,79 +39,72 @@ namespace {
using ::testing::Message; using ::testing::Message;
// A helper function that turns a Message into a C string.
const char* ToCString(const Message& msg) {
static testing::internal::String result;
result = msg.GetString();
return result.c_str();
}
// Tests the testing::Message class // Tests the testing::Message class
// Tests the default constructor. // Tests the default constructor.
TEST(MessageTest, DefaultConstructor) { TEST(MessageTest, DefaultConstructor) {
const Message msg; const Message msg;
EXPECT_STREQ("", ToCString(msg)); EXPECT_EQ("", msg.GetString());
} }
// Tests the copy constructor. // Tests the copy constructor.
TEST(MessageTest, CopyConstructor) { TEST(MessageTest, CopyConstructor) {
const Message msg1("Hello"); const Message msg1("Hello");
const Message msg2(msg1); const Message msg2(msg1);
EXPECT_STREQ("Hello", ToCString(msg2)); EXPECT_EQ("Hello", msg2.GetString());
} }
// Tests constructing a Message from a C-string. // Tests constructing a Message from a C-string.
TEST(MessageTest, ConstructsFromCString) { TEST(MessageTest, ConstructsFromCString) {
Message msg("Hello"); Message msg("Hello");
EXPECT_STREQ("Hello", ToCString(msg)); EXPECT_EQ("Hello", msg.GetString());
} }
// Tests streaming a float. // Tests streaming a float.
TEST(MessageTest, StreamsFloat) { TEST(MessageTest, StreamsFloat) {
const char* const s = ToCString(Message() << 1.23456F << " " << 2.34567F); const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString();
// Both numbers should be printed with enough precision. // Both numbers should be printed with enough precision.
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s); EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str());
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str());
} }
// Tests streaming a double. // Tests streaming a double.
TEST(MessageTest, StreamsDouble) { TEST(MessageTest, StreamsDouble) {
const char* const s = ToCString(Message() << 1260570880.4555497 << " " const std::string s = (Message() << 1260570880.4555497 << " "
<< 1260572265.1954534); << 1260572265.1954534).GetString();
// Both numbers should be printed with enough precision. // Both numbers should be printed with enough precision.
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s); EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
} }
// Tests streaming a non-char pointer. // Tests streaming a non-char pointer.
TEST(MessageTest, StreamsPointer) { TEST(MessageTest, StreamsPointer) {
int n = 0; int n = 0;
int* p = &n; int* p = &n;
EXPECT_STRNE("(null)", ToCString(Message() << p)); EXPECT_NE("(null)", (Message() << p).GetString());
} }
// Tests streaming a NULL non-char pointer. // Tests streaming a NULL non-char pointer.
TEST(MessageTest, StreamsNullPointer) { TEST(MessageTest, StreamsNullPointer) {
int* p = NULL; int* p = NULL;
EXPECT_STREQ("(null)", ToCString(Message() << p)); EXPECT_EQ("(null)", (Message() << p).GetString());
} }
// Tests streaming a C string. // Tests streaming a C string.
TEST(MessageTest, StreamsCString) { TEST(MessageTest, StreamsCString) {
EXPECT_STREQ("Foo", ToCString(Message() << "Foo")); EXPECT_EQ("Foo", (Message() << "Foo").GetString());
} }
// Tests streaming a NULL C string. // Tests streaming a NULL C string.
TEST(MessageTest, StreamsNullCString) { TEST(MessageTest, StreamsNullCString) {
char* p = NULL; char* p = NULL;
EXPECT_STREQ("(null)", ToCString(Message() << p)); EXPECT_EQ("(null)", (Message() << p).GetString());
} }
// Tests streaming std::string. // Tests streaming std::string.
TEST(MessageTest, StreamsString) { TEST(MessageTest, StreamsString) {
const ::std::string str("Hello"); const ::std::string str("Hello");
EXPECT_STREQ("Hello", ToCString(Message() << str)); EXPECT_EQ("Hello", (Message() << str).GetString());
} }
// Tests that we can output strings containing embedded NULs. // Tests that we can output strings containing embedded NULs.
@ -120,34 +113,34 @@ TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
"Here's a NUL\0 and some more string"; "Here's a NUL\0 and some more string";
const ::std::string string_with_nul(char_array_with_nul, const ::std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul) - 1); sizeof(char_array_with_nul) - 1);
EXPECT_STREQ("Here's a NUL\\0 and some more string", EXPECT_EQ("Here's a NUL\\0 and some more string",
ToCString(Message() << string_with_nul)); (Message() << string_with_nul).GetString());
} }
// Tests streaming a NUL char. // Tests streaming a NUL char.
TEST(MessageTest, StreamsNULChar) { TEST(MessageTest, StreamsNULChar) {
EXPECT_STREQ("\\0", ToCString(Message() << '\0')); EXPECT_EQ("\\0", (Message() << '\0').GetString());
} }
// Tests streaming int. // Tests streaming int.
TEST(MessageTest, StreamsInt) { TEST(MessageTest, StreamsInt) {
EXPECT_STREQ("123", ToCString(Message() << 123)); EXPECT_EQ("123", (Message() << 123).GetString());
} }
// Tests that basic IO manipulators (endl, ends, and flush) can be // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message. // streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) { TEST(MessageTest, StreamsBasicIoManip) {
EXPECT_STREQ("Line 1.\nA NUL char \\0 in line 2.", EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.",
ToCString(Message() << "Line 1." << std::endl (Message() << "Line 1." << std::endl
<< "A NUL char " << std::ends << std::flush << "A NUL char " << std::ends << std::flush
<< " in line 2.")); << " in line 2.").GetString());
} }
// Tests Message::GetString() // Tests Message::GetString()
TEST(MessageTest, GetString) { TEST(MessageTest, GetString) {
Message msg; Message msg;
msg << 1 << " lamb"; msg << 1 << " lamb";
EXPECT_STREQ("1 lamb", msg.GetString().c_str()); EXPECT_EQ("1 lamb", msg.GetString());
} }
// Tests streaming a Message object to an ostream. // Tests streaming a Message object to an ostream.
@ -155,7 +148,7 @@ TEST(MessageTest, StreamsToOStream) {
Message msg("Hello"); Message msg("Hello");
::std::stringstream ss; ::std::stringstream ss;
ss << msg; ss << msg;
EXPECT_STREQ("Hello", testing::internal::StringStreamToString(&ss).c_str()); EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss));
} }
// Tests that a Message object doesn't take up too much stack space. // Tests that a Message object doesn't take up too much stack space.

View File

@ -78,14 +78,14 @@ TEST(XmlOutputTest, GetOutputFormat) {
TEST(XmlOutputTest, GetOutputFileDefault) { TEST(XmlOutputTest, GetOutputFileDefault) {
GTEST_FLAG(output) = ""; GTEST_FLAG(output) = "";
EXPECT_STREQ(GetAbsolutePathOf(FilePath("test_detail.xml")).c_str(), EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST(XmlOutputTest, GetOutputFileSingleFile) { TEST(XmlOutputTest, GetOutputFileSingleFile) {
GTEST_FLAG(output) = "xml:filename.abc"; GTEST_FLAG(output) = "xml:filename.abc";
EXPECT_STREQ(GetAbsolutePathOf(FilePath("filename.abc")).c_str(), EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
@ -93,8 +93,9 @@ TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
const std::string expected_output_file = const std::string expected_output_file =
GetAbsolutePathOf( GetAbsolutePathOf(
FilePath(std::string("path") + GTEST_PATH_SEP_ + FilePath(std::string("path") + GTEST_PATH_SEP_ +
GetCurrentExecutableName().c_str() + ".xml")).c_str(); GetCurrentExecutableName().string() + ".xml")).string();
const String& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else #else
@ -103,7 +104,7 @@ TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
} }
TEST(OutputFileHelpersTest, GetCurrentExecutableName) { TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const std::string exe_str = GetCurrentExecutableName().c_str(); const std::string exe_str = GetCurrentExecutableName().string();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
const bool success = const bool success =
_strcmpi("gtest-options_test", exe_str.c_str()) == 0 || _strcmpi("gtest-options_test", exe_str.c_str()) == 0 ||
@ -129,12 +130,12 @@ class XmlOutputChangeDirTest : public Test {
original_working_dir_ = FilePath::GetCurrentDir(); original_working_dir_ = FilePath::GetCurrentDir();
posix::ChDir(".."); posix::ChDir("..");
// This will make the test fail if run from the root directory. // This will make the test fail if run from the root directory.
EXPECT_STRNE(original_working_dir_.c_str(), EXPECT_NE(original_working_dir_.string(),
FilePath::GetCurrentDir().c_str()); FilePath::GetCurrentDir().string());
} }
virtual void TearDown() { virtual void TearDown() {
posix::ChDir(original_working_dir_.c_str()); posix::ChDir(original_working_dir_.string().c_str());
} }
FilePath original_working_dir_; FilePath original_working_dir_;
@ -142,23 +143,23 @@ class XmlOutputChangeDirTest : public Test {
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
GTEST_FLAG(output) = ""; GTEST_FLAG(output) = "";
EXPECT_STREQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
FilePath("test_detail.xml")).c_str(), FilePath("test_detail.xml")).string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
GTEST_FLAG(output) = "xml"; GTEST_FLAG(output) = "xml";
EXPECT_STREQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
FilePath("test_detail.xml")).c_str(), FilePath("test_detail.xml")).string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
GTEST_FLAG(output) = "xml:filename.abc"; GTEST_FLAG(output) = "xml:filename.abc";
EXPECT_STREQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
FilePath("filename.abc")).c_str(), FilePath("filename.abc")).string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
@ -167,8 +168,9 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
FilePath::ConcatPaths( FilePath::ConcatPaths(
original_working_dir_, original_working_dir_,
FilePath(std::string("path") + GTEST_PATH_SEP_ + FilePath(std::string("path") + GTEST_PATH_SEP_ +
GetCurrentExecutableName().c_str() + ".xml")).c_str(); GetCurrentExecutableName().string() + ".xml")).string();
const String& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else #else
@ -179,12 +181,12 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc";
EXPECT_STREQ(FilePath("c:\\tmp\\filename.abc").c_str(), EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
#else #else
GTEST_FLAG(output) ="xml:/tmp/filename.abc"; GTEST_FLAG(output) ="xml:/tmp/filename.abc";
EXPECT_STREQ(FilePath("/tmp/filename.abc").c_str(), EXPECT_EQ(FilePath("/tmp/filename.abc").string(),
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); UnitTestOptions::GetAbsolutePathToOutputFile());
#endif #endif
} }
@ -197,8 +199,9 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
GTEST_FLAG(output) = "xml:" + path; GTEST_FLAG(output) = "xml:" + path;
const std::string expected_output_file = const std::string expected_output_file =
path + GetCurrentExecutableName().c_str() + ".xml"; path + GetCurrentExecutableName().string() + ".xml";
const String& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());

View File

@ -280,10 +280,10 @@ class DogAdder {
bool operator<(const DogAdder& other) const { bool operator<(const DogAdder& other) const {
return value_ < other.value_; return value_ < other.value_;
} }
const ::testing::internal::String& value() const { return value_; } const std::string& value() const { return value_; }
private: private:
::testing::internal::String value_; std::string value_;
}; };
TEST(RangeTest, WorksWithACustomType) { TEST(RangeTest, WorksWithACustomType) {

View File

@ -1005,7 +1005,7 @@ TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
} }
TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
ThreadLocal<String> thread_local_string; ThreadLocal<std::string> thread_local_string;
EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
@ -1015,8 +1015,9 @@ TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
} }
TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
ThreadLocal<String> thread_local_string; ThreadLocal<std::string> thread_local_string;
const ThreadLocal<String>& const_thread_local_string = thread_local_string; const ThreadLocal<std::string>& const_thread_local_string =
thread_local_string;
EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
@ -1126,18 +1127,19 @@ void RunFromThread(void (func)(T), T param) {
thread.Join(); thread.Join();
} }
void RetrieveThreadLocalValue(pair<ThreadLocal<String>*, String*> param) { void RetrieveThreadLocalValue(
pair<ThreadLocal<std::string>*, std::string*> param) {
*param.second = param.first->get(); *param.second = param.first->get();
} }
TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
ThreadLocal<String> thread_local_string("foo"); ThreadLocal<std::string> thread_local_string("foo");
EXPECT_STREQ("foo", thread_local_string.get().c_str()); EXPECT_STREQ("foo", thread_local_string.get().c_str());
thread_local_string.set("bar"); thread_local_string.set("bar");
EXPECT_STREQ("bar", thread_local_string.get().c_str()); EXPECT_STREQ("bar", thread_local_string.get().c_str());
String result; std::string result;
RunFromThread(&RetrieveThreadLocalValue, RunFromThread(&RetrieveThreadLocalValue,
make_pair(&thread_local_string, &result)); make_pair(&thread_local_string, &result));
EXPECT_STREQ("foo", result.c_str()); EXPECT_STREQ("foo", result.c_str());
@ -1235,14 +1237,14 @@ TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
} }
TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
ThreadLocal<String> thread_local_string; ThreadLocal<std::string> thread_local_string;
thread_local_string.set("Foo"); thread_local_string.set("Foo");
EXPECT_STREQ("Foo", thread_local_string.get().c_str()); EXPECT_STREQ("Foo", thread_local_string.get().c_str());
String result; std::string result;
RunFromThread(&RetrieveThreadLocalValue, RunFromThread(&RetrieveThreadLocalValue,
make_pair(&thread_local_string, &result)); make_pair(&thread_local_string, &result));
EXPECT_TRUE(result.c_str() == NULL); EXPECT_TRUE(result.empty());
} }
#endif // GTEST_IS_THREADSAFE #endif // GTEST_IS_THREADSAFE

View File

@ -58,7 +58,6 @@ using testing::internal::ThreadWithParam;
#endif #endif
namespace posix = ::testing::internal::posix; namespace posix = ::testing::internal::posix;
using testing::internal::String;
using testing::internal::scoped_ptr; using testing::internal::scoped_ptr;
// Tests catching fatal failures. // Tests catching fatal failures.
@ -1005,7 +1004,8 @@ int main(int argc, char **argv) {
// for it. // for it.
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
if (argc >= 2 && if (argc >= 2 &&
String(argv[1]) == "--gtest_internal_skip_environment_and_ad_hoc_tests") (std::string(argv[1]) ==
"--gtest_internal_skip_environment_and_ad_hoc_tests"))
GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true; GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true;
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST

View File

@ -42,7 +42,6 @@ using ::testing::Test;
using ::testing::TestEventListeners; using ::testing::TestEventListeners;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::UnitTest; using ::testing::UnitTest;
using ::testing::internal::String;
using ::testing::internal::scoped_ptr; using ::testing::internal::scoped_ptr;
// The test methods are empty, as the sole purpose of this program is // The test methods are empty, as the sole purpose of this program is

View File

@ -50,7 +50,6 @@ namespace testing {
namespace { namespace {
using internal::Notification; using internal::Notification;
using internal::String;
using internal::TestPropertyKeyIs; using internal::TestPropertyKeyIs;
using internal::ThreadWithParam; using internal::ThreadWithParam;
using internal::scoped_ptr; using internal::scoped_ptr;
@ -62,13 +61,13 @@ using internal::scoped_ptr;
// How many threads to create? // How many threads to create?
const int kThreadCount = 50; const int kThreadCount = 50;
String IdToKey(int id, const char* suffix) { std::string IdToKey(int id, const char* suffix) {
Message key; Message key;
key << "key_" << id << "_" << suffix; key << "key_" << id << "_" << suffix;
return key.GetString(); return key.GetString();
} }
String IdToString(int id) { std::string IdToString(int id) {
Message id_message; Message id_message;
id_message << id; id_message << id;
return id_message.GetString(); return id_message.GetString();

View File

@ -931,259 +931,16 @@ TEST(AssertHelperTest, AssertHelperIsSmall) {
EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
} }
// Tests the String class.
// Tests String's constructors.
TEST(StringTest, Constructors) {
// Default ctor.
String s1;
// We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
// pointers with NULL isn't supported on all platforms.
EXPECT_EQ(0U, s1.length());
EXPECT_TRUE(NULL == s1.c_str());
// Implicitly constructs from a C-string.
String s2 = "Hi";
EXPECT_EQ(2U, s2.length());
EXPECT_STREQ("Hi", s2.c_str());
// Constructs from a C-string and a length.
String s3("hello", 3);
EXPECT_EQ(3U, s3.length());
EXPECT_STREQ("hel", s3.c_str());
// The empty String should be created when String is constructed with
// a NULL pointer and length 0.
EXPECT_EQ(0U, String(NULL, 0).length());
EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
// Constructs a String that contains '\0'.
String s4("a\0bcd", 4);
EXPECT_EQ(4U, s4.length());
EXPECT_EQ('a', s4.c_str()[0]);
EXPECT_EQ('\0', s4.c_str()[1]);
EXPECT_EQ('b', s4.c_str()[2]);
EXPECT_EQ('c', s4.c_str()[3]);
// Copy ctor where the source is NULL.
const String null_str;
String s5 = null_str;
EXPECT_TRUE(s5.c_str() == NULL);
// Copy ctor where the source isn't NULL.
String s6 = s3;
EXPECT_EQ(3U, s6.length());
EXPECT_STREQ("hel", s6.c_str());
// Copy ctor where the source contains '\0'.
String s7 = s4;
EXPECT_EQ(4U, s7.length());
EXPECT_EQ('a', s7.c_str()[0]);
EXPECT_EQ('\0', s7.c_str()[1]);
EXPECT_EQ('b', s7.c_str()[2]);
EXPECT_EQ('c', s7.c_str()[3]);
}
TEST(StringTest, ConvertsFromStdString) {
// An empty std::string.
const std::string src1("");
const String dest1 = src1;
EXPECT_EQ(0U, dest1.length());
EXPECT_STREQ("", dest1.c_str());
// A normal std::string.
const std::string src2("Hi");
const String dest2 = src2;
EXPECT_EQ(2U, dest2.length());
EXPECT_STREQ("Hi", dest2.c_str());
// An std::string with an embedded NUL character.
const char src3[] = "a\0b";
const String dest3 = std::string(src3, sizeof(src3));
EXPECT_EQ(sizeof(src3), dest3.length());
EXPECT_EQ('a', dest3.c_str()[0]);
EXPECT_EQ('\0', dest3.c_str()[1]);
EXPECT_EQ('b', dest3.c_str()[2]);
}
TEST(StringTest, ConvertsToStdString) {
// An empty String.
const String src1("");
const std::string dest1 = src1;
EXPECT_EQ("", dest1);
// A normal String.
const String src2("Hi");
const std::string dest2 = src2;
EXPECT_EQ("Hi", dest2);
// A String containing a '\0'.
const String src3("x\0y", 3);
const std::string dest3 = src3;
EXPECT_EQ(std::string("x\0y", 3), dest3);
}
#if GTEST_HAS_GLOBAL_STRING
TEST(StringTest, ConvertsFromGlobalString) {
// An empty ::string.
const ::string src1("");
const String dest1 = src1;
EXPECT_EQ(0U, dest1.length());
EXPECT_STREQ("", dest1.c_str());
// A normal ::string.
const ::string src2("Hi");
const String dest2 = src2;
EXPECT_EQ(2U, dest2.length());
EXPECT_STREQ("Hi", dest2.c_str());
// An ::string with an embedded NUL character.
const char src3[] = "x\0y";
const String dest3 = ::string(src3, sizeof(src3));
EXPECT_EQ(sizeof(src3), dest3.length());
EXPECT_EQ('x', dest3.c_str()[0]);
EXPECT_EQ('\0', dest3.c_str()[1]);
EXPECT_EQ('y', dest3.c_str()[2]);
}
TEST(StringTest, ConvertsToGlobalString) {
// An empty String.
const String src1("");
const ::string dest1 = src1;
EXPECT_EQ("", dest1);
// A normal String.
const String src2("Hi");
const ::string dest2 = src2;
EXPECT_EQ("Hi", dest2);
const String src3("x\0y", 3);
const ::string dest3 = src3;
EXPECT_EQ(::string("x\0y", 3), dest3);
}
#endif // GTEST_HAS_GLOBAL_STRING
// Tests String::empty().
TEST(StringTest, Empty) {
EXPECT_TRUE(String("").empty());
EXPECT_FALSE(String().empty());
EXPECT_FALSE(String(NULL).empty());
EXPECT_FALSE(String("a").empty());
EXPECT_FALSE(String("\0", 1).empty());
}
// Tests String::Compare().
TEST(StringTest, Compare) {
// NULL vs NULL.
EXPECT_EQ(0, String().Compare(String()));
// NULL vs non-NULL.
EXPECT_EQ(-1, String().Compare(String("")));
// Non-NULL vs NULL.
EXPECT_EQ(1, String("").Compare(String()));
// The following covers non-NULL vs non-NULL.
// "" vs "".
EXPECT_EQ(0, String("").Compare(String("")));
// "" vs non-"".
EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
EXPECT_EQ(-1, String("").Compare(" "));
// Non-"" vs "".
EXPECT_EQ(1, String("a").Compare(String("")));
// The following covers non-"" vs non-"".
// Same length and equal.
EXPECT_EQ(0, String("a").Compare(String("a")));
// Same length and different.
EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
EXPECT_EQ(1, String("b").Compare(String("a")));
// Different lengths.
EXPECT_EQ(-1, String("a").Compare(String("ab")));
EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
EXPECT_EQ(1, String("abc").Compare(String("aacd")));
}
// Tests String::operator==().
TEST(StringTest, Equals) {
const String null(NULL);
EXPECT_TRUE(null == NULL); // NOLINT
EXPECT_FALSE(null == ""); // NOLINT
EXPECT_FALSE(null == "bar"); // NOLINT
const String empty("");
EXPECT_FALSE(empty == NULL); // NOLINT
EXPECT_TRUE(empty == ""); // NOLINT
EXPECT_FALSE(empty == "bar"); // NOLINT
const String foo("foo");
EXPECT_FALSE(foo == NULL); // NOLINT
EXPECT_FALSE(foo == ""); // NOLINT
EXPECT_FALSE(foo == "bar"); // NOLINT
EXPECT_TRUE(foo == "foo"); // NOLINT
const String bar("x\0y", 3);
EXPECT_NE(bar, "x");
}
// Tests String::operator!=().
TEST(StringTest, NotEquals) {
const String null(NULL);
EXPECT_FALSE(null != NULL); // NOLINT
EXPECT_TRUE(null != ""); // NOLINT
EXPECT_TRUE(null != "bar"); // NOLINT
const String empty("");
EXPECT_TRUE(empty != NULL); // NOLINT
EXPECT_FALSE(empty != ""); // NOLINT
EXPECT_TRUE(empty != "bar"); // NOLINT
const String foo("foo");
EXPECT_TRUE(foo != NULL); // NOLINT
EXPECT_TRUE(foo != ""); // NOLINT
EXPECT_TRUE(foo != "bar"); // NOLINT
EXPECT_FALSE(foo != "foo"); // NOLINT
const String bar("x\0y", 3);
EXPECT_NE(bar, "x");
}
// Tests String::length().
TEST(StringTest, Length) {
EXPECT_EQ(0U, String().length());
EXPECT_EQ(0U, String("").length());
EXPECT_EQ(2U, String("ab").length());
EXPECT_EQ(3U, String("a\0b", 3).length());
}
// Tests String::EndsWith().
TEST(StringTest, EndsWith) {
EXPECT_TRUE(String("foobar").EndsWith("bar"));
EXPECT_TRUE(String("foobar").EndsWith(""));
EXPECT_TRUE(String("").EndsWith(""));
EXPECT_FALSE(String("foobar").EndsWith("foo"));
EXPECT_FALSE(String("").EndsWith("foo"));
}
// Tests String::EndsWithCaseInsensitive(). // Tests String::EndsWithCaseInsensitive().
TEST(StringTest, EndsWithCaseInsensitive) { TEST(StringTest, EndsWithCaseInsensitive) {
EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
EXPECT_TRUE(String("").EndsWithCaseInsensitive("")); EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
} }
// C++Builder's preprocessor is buggy; it fails to expand macros that // C++Builder's preprocessor is buggy; it fails to expand macros that
@ -1203,61 +960,6 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) {
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
} }
// Tests that NULL can be assigned to a String.
TEST(StringTest, CanBeAssignedNULL) {
const String src(NULL);
String dest;
dest = src;
EXPECT_STREQ(NULL, dest.c_str());
}
// Tests that the empty string "" can be assigned to a String.
TEST(StringTest, CanBeAssignedEmpty) {
const String src("");
String dest;
dest = src;
EXPECT_STREQ("", dest.c_str());
}
// Tests that a non-empty string can be assigned to a String.
TEST(StringTest, CanBeAssignedNonEmpty) {
const String src("hello");
String dest;
dest = src;
EXPECT_EQ(5U, dest.length());
EXPECT_STREQ("hello", dest.c_str());
const String src2("x\0y", 3);
String dest2;
dest2 = src2;
EXPECT_EQ(3U, dest2.length());
EXPECT_EQ('x', dest2.c_str()[0]);
EXPECT_EQ('\0', dest2.c_str()[1]);
EXPECT_EQ('y', dest2.c_str()[2]);
}
// Tests that a String can be assigned to itself.
TEST(StringTest, CanBeAssignedSelf) {
String dest("hello");
// Use explicit function call notation here to suppress self-assign warning.
dest.operator=(dest);
EXPECT_STREQ("hello", dest.c_str());
}
// Sun Studio < 12 incorrectly rejects this code due to an overloading
// ambiguity.
#if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
// Tests streaming a String.
TEST(StringTest, Streams) {
EXPECT_EQ(StreamableToString(String()), "(null)");
EXPECT_EQ(StreamableToString(String("")), "");
EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
}
#endif
// Tests that String::Format() works. // Tests that String::Format() works.
TEST(StringTest, FormatWorks) { TEST(StringTest, FormatWorks) {
// Normal case: the format spec is valid, the arguments match the // Normal case: the format spec is valid, the arguments match the
@ -1269,19 +971,19 @@ TEST(StringTest, FormatWorks) {
const size_t kSize = sizeof(buffer); const size_t kSize = sizeof(buffer);
memset(buffer, 'a', kSize - 1); memset(buffer, 'a', kSize - 1);
buffer[kSize - 1] = '\0'; buffer[kSize - 1] = '\0';
EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str()); EXPECT_EQ(buffer, String::Format("%s", buffer));
// The result needs to be 4096 characters, exceeding Format()'s limit. // The result needs to be 4096 characters, exceeding Format()'s limit.
EXPECT_STREQ("<formatting error or buffer exceeded>", EXPECT_EQ("<formatting error or buffer exceeded>",
String::Format("x%s", buffer).c_str()); String::Format("x%s", buffer));
#if GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID #if GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
// On Linux, invalid format spec should lead to an error message. // On Linux, invalid format spec should lead to an error message.
// In other environment (e.g. MSVC on Windows), String::Format() may // In other environment (e.g. MSVC on Windows), String::Format() may
// simply ignore a bad format spec, so this assertion is run on // simply ignore a bad format spec, so this assertion is run on
// Linux only. // Linux only.
EXPECT_STREQ("<formatting error or buffer exceeded>", EXPECT_EQ("<formatting error or buffer exceeded>",
String::Format("%").c_str()); String::Format("%"));
#endif #endif
} }
@ -1915,15 +1617,16 @@ static void SetEnv(const char* name, const char* value) {
// C++Builder's putenv only stores a pointer to its parameter; we have to // C++Builder's putenv only stores a pointer to its parameter; we have to
// ensure that the string remains valid as long as it might be needed. // ensure that the string remains valid as long as it might be needed.
// We use an std::map to do so. // We use an std::map to do so.
static std::map<String, String*> added_env; static std::map<std::string, std::string*> added_env;
// Because putenv stores a pointer to the string buffer, we can't delete the // Because putenv stores a pointer to the string buffer, we can't delete the
// previous string (if present) until after it's replaced. // previous string (if present) until after it's replaced.
String *prev_env = NULL; std::string *prev_env = NULL;
if (added_env.find(name) != added_env.end()) { if (added_env.find(name) != added_env.end()) {
prev_env = added_env[name]; prev_env = added_env[name];
} }
added_env[name] = new String((Message() << name << "=" << value).GetString()); added_env[name] = new std::string(
(Message() << name << "=" << value).GetString());
// The standard signature of putenv accepts a 'char*' argument. Other // The standard signature of putenv accepts a 'char*' argument. Other
// implementations, like C++Builder's, accept a 'const char*'. // implementations, like C++Builder's, accept a 'const char*'.
@ -3568,8 +3271,8 @@ TEST_F(NoFatalFailureTest, MessageIsStreamable) {
// Tests EqFailure(), used for implementing *EQ* assertions. // Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) { TEST(AssertionTest, EqFailure) {
const String foo_val("5"), bar_val("6"); const std::string foo_val("5"), bar_val("6");
const String msg1( const std::string msg1(
EqFailure("foo", "bar", foo_val, bar_val, false) EqFailure("foo", "bar", foo_val, bar_val, false)
.failure_message()); .failure_message());
EXPECT_STREQ( EXPECT_STREQ(
@ -3579,7 +3282,7 @@ TEST(AssertionTest, EqFailure) {
"Which is: 5", "Which is: 5",
msg1.c_str()); msg1.c_str());
const String msg2( const std::string msg2(
EqFailure("foo", "6", foo_val, bar_val, false) EqFailure("foo", "6", foo_val, bar_val, false)
.failure_message()); .failure_message());
EXPECT_STREQ( EXPECT_STREQ(
@ -3588,7 +3291,7 @@ TEST(AssertionTest, EqFailure) {
"Which is: 5", "Which is: 5",
msg2.c_str()); msg2.c_str());
const String msg3( const std::string msg3(
EqFailure("5", "bar", foo_val, bar_val, false) EqFailure("5", "bar", foo_val, bar_val, false)
.failure_message()); .failure_message());
EXPECT_STREQ( EXPECT_STREQ(
@ -3597,16 +3300,16 @@ TEST(AssertionTest, EqFailure) {
"Expected: 5", "Expected: 5",
msg3.c_str()); msg3.c_str());
const String msg4( const std::string msg4(
EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EqFailure("5", "6", foo_val, bar_val, false).failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Value of: 6\n" "Value of: 6\n"
"Expected: 5", "Expected: 5",
msg4.c_str()); msg4.c_str());
const String msg5( const std::string msg5(
EqFailure("foo", "bar", EqFailure("foo", "bar",
String("\"x\""), String("\"y\""), std::string("\"x\""), std::string("\"y\""),
true).failure_message()); true).failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Value of: bar\n" "Value of: bar\n"
@ -3618,7 +3321,7 @@ TEST(AssertionTest, EqFailure) {
// Tests AppendUserMessage(), used for implementing the *EQ* macros. // Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) { TEST(AssertionTest, AppendUserMessage) {
const String foo("foo"); const std::string foo("foo");
Message msg; Message msg;
EXPECT_STREQ("foo", EXPECT_STREQ("foo",
@ -4199,7 +3902,7 @@ TEST(AssertionSyntaxTest, WorksWithSwitch) {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
void ThrowAString() { void ThrowAString() {
throw "String"; throw "std::string";
} }
// Test that the exception assertion macros compile and work with const // Test that the exception assertion macros compile and work with const
@ -5619,7 +5322,7 @@ class InitGoogleTestTest : public Test {
internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
const String captured_stdout = GetCapturedStdout(); const std::string captured_stdout = GetCapturedStdout();
#endif #endif
// Verifies the flag values. // Verifies the flag values.
@ -6891,7 +6594,7 @@ TEST(TestEventListenersTest, Append) {
// order. // order.
class SequenceTestingListener : public EmptyTestEventListener { class SequenceTestingListener : public EmptyTestEventListener {
public: public:
SequenceTestingListener(std::vector<String>* vector, const char* id) SequenceTestingListener(std::vector<std::string>* vector, const char* id)
: vector_(vector), id_(id) {} : vector_(vector), id_(id) {}
protected: protected:
@ -6914,20 +6617,20 @@ class SequenceTestingListener : public EmptyTestEventListener {
} }
private: private:
String GetEventDescription(const char* method) { std::string GetEventDescription(const char* method) {
Message message; Message message;
message << id_ << "." << method; message << id_ << "." << method;
return message.GetString(); return message.GetString();
} }
std::vector<String>* vector_; std::vector<std::string>* vector_;
const char* const id_; const char* const id_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
}; };
TEST(EventListenerTest, AppendKeepsOrder) { TEST(EventListenerTest, AppendKeepsOrder) {
std::vector<String> vec; std::vector<std::string> vec;
TestEventListeners listeners; TestEventListeners listeners;
listeners.Append(new SequenceTestingListener(&vec, "1st")); listeners.Append(new SequenceTestingListener(&vec, "1st"));
listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "2nd"));
@ -7313,7 +7016,7 @@ TEST(GTestReferenceToConstTest, Works) {
TestGTestReferenceToConst<const char&, char>(); TestGTestReferenceToConst<const char&, char>();
TestGTestReferenceToConst<const int&, const int>(); TestGTestReferenceToConst<const int&, const int>();
TestGTestReferenceToConst<const double&, double>(); TestGTestReferenceToConst<const double&, double>();
TestGTestReferenceToConst<const String&, const String&>(); TestGTestReferenceToConst<const std::string&, const std::string&>();
} }
// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant. // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.