diff options
author | Benjamin Kramer <benny.kra@googlemail.com> | 2010-06-02 22:02:30 +0000 |
---|---|---|
committer | Benjamin Kramer <benny.kra@googlemail.com> | 2010-06-02 22:02:30 +0000 |
commit | 57240ff6e2252f8986f6e47e4010bc52fbae25d1 (patch) | |
tree | dacdd66eb30eedab81795672528b6888def253f7 /utils/unittest | |
parent | 190f8ee25a6977ac6eb71b816498df42f17ad9a7 (diff) |
Merge gtest-1.5.0.
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@105354 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'utils/unittest')
24 files changed, 1497 insertions, 989 deletions
diff --git a/utils/unittest/googletest/gtest-death-test.cc b/utils/unittest/googletest/gtest-death-test.cc index e2bb8e6b43..e4199de3dc 100644 --- a/utils/unittest/googletest/gtest-death-test.cc +++ b/utils/unittest/googletest/gtest-death-test.cc @@ -308,9 +308,9 @@ String DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { protected: - DeathTestImpl(const char* statement, const RE* regex) - : statement_(statement), - regex_(regex), + DeathTestImpl(const char* a_statement, const RE* a_regex) + : statement_(a_statement), + regex_(a_regex), spawned_(false), status_(-1), outcome_(IN_PROGRESS), @@ -326,11 +326,11 @@ class DeathTestImpl : public DeathTest { const char* statement() const { return statement_; } const RE* regex() const { return regex_; } bool spawned() const { return spawned_; } - void set_spawned(bool spawned) { spawned_ = spawned; } + void set_spawned(bool is_spawned) { spawned_ = is_spawned; } int status() const { return status_; } - void set_status(int status) { status_ = status; } + void set_status(int a_status) { status_ = a_status; } DeathTestOutcome outcome() const { return outcome_; } - void set_outcome(DeathTestOutcome outcome) { outcome_ = outcome; } + void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } int read_fd() const { return read_fd_; } void set_read_fd(int fd) { read_fd_ = fd; } int write_fd() const { return write_fd_; } @@ -705,8 +705,8 @@ class ForkingDeathTest : public DeathTestImpl { }; // Constructs a ForkingDeathTest. -ForkingDeathTest::ForkingDeathTest(const char* statement, const RE* regex) - : DeathTestImpl(statement, regex), +ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) + : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit @@ -718,18 +718,18 @@ int ForkingDeathTest::Wait() { ReadAndInterpretStatusByte(); - int status; - GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status, 0)); - set_status(status); - return status; + int status_value; + GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); + set_status(status_value); + return status_value; } // A concrete death test class that forks, then immediately runs the test // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: - NoExecDeathTest(const char* statement, const RE* regex) : - ForkingDeathTest(statement, regex) { } + NoExecDeathTest(const char* a_statement, const RE* a_regex) : + ForkingDeathTest(a_statement, a_regex) { } virtual TestRole AssumeRole(); }; @@ -782,9 +782,9 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() { // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: - ExecDeathTest(const char* statement, const RE* regex, + ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : - ForkingDeathTest(statement, regex), file_(file), line_(line) { } + ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. @@ -1037,8 +1037,6 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, // Splits a given string on a given delimiter, populating a given // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have // ::std::string, so we can use it here. -// TODO(vladl@google.com): Get rid of std::vector to be able to build on -// Visual C++ 7.1 with exceptions disabled. static void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; diff --git a/utils/unittest/googletest/gtest-filepath.cc b/utils/unittest/googletest/gtest-filepath.cc index 515d61c783..c1ef9188ad 100644 --- a/utils/unittest/googletest/gtest-filepath.cc +++ b/utils/unittest/googletest/gtest-filepath.cc @@ -63,8 +63,14 @@ namespace testing { namespace internal { #if GTEST_OS_WINDOWS +// On Windows, '\\' is the standard path separator, but many tools and the +// Windows API also accept '/' as an alternate path separator. Unless otherwise +// noted, a file path can contain either kind of path separators, or a mixture +// of them. const char kPathSeparator = '\\'; +const char kAlternatePathSeparator = '/'; const char kPathSeparatorString[] = "\\"; +const char kAlternatePathSeparatorString[] = "/"; #if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least @@ -81,6 +87,15 @@ const char kPathSeparatorString[] = "/"; const char kCurrentDirectoryString[] = "./"; #endif // GTEST_OS_WINDOWS +// Returns whether the given character is a valid path separator. +static bool IsPathSeparator(char c) { +#if GTEST_HAS_ALT_PATH_SEP_ + return (c == kPathSeparator) || (c == kAlternatePathSeparator); +#else + return c == kPathSeparator; +#endif +} + // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE @@ -108,6 +123,22 @@ FilePath FilePath::RemoveExtension(const char* extension) const { return *this; } +// Returns a pointer to the last occurence of a valid path separator in +// the FilePath. On Windows, for example, both '/' and '\' are valid path +// separators. Returns NULL if no path separator was found. +const char* FilePath::FindLastPathSeparator() const { + const char* const last_sep = strrchr(c_str(), kPathSeparator); +#if GTEST_HAS_ALT_PATH_SEP_ + const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); + // Comparing two pointers of which only one is NULL is undefined. + if (last_alt_sep != NULL && + (last_sep == NULL || last_alt_sep > last_sep)) { + return last_alt_sep; + } +#endif + return last_sep; +} + // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns @@ -115,7 +146,7 @@ FilePath FilePath::RemoveExtension(const char* extension) const { // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveDirectoryName() const { - const char* const last_sep = strrchr(c_str(), kPathSeparator); + const char* const last_sep = FindLastPathSeparator(); return last_sep ? FilePath(String(last_sep + 1)) : *this; } @@ -126,7 +157,7 @@ FilePath FilePath::RemoveDirectoryName() const { // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveFileName() const { - const char* const last_sep = strrchr(c_str(), kPathSeparator); + const char* const last_sep = FindLastPathSeparator(); String dir; if (last_sep) { dir = String(c_str(), last_sep + 1 - c_str()); @@ -219,7 +250,7 @@ bool FilePath::IsRootDirectory() const { // current directory. Handle this properly. return pathname_.length() == 3 && IsAbsolutePath(); #else - return pathname_ == kPathSeparatorString; + return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); #endif } @@ -231,9 +262,9 @@ bool FilePath::IsAbsolutePath() const { ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) && name[1] == ':' && - name[2] == kPathSeparator; + IsPathSeparator(name[2]); #else - return name[0] == kPathSeparator; + return IsPathSeparator(name[0]); #endif } @@ -260,7 +291,8 @@ FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool FilePath::IsDirectory() const { - return pathname_.EndsWith(kPathSeparatorString); + return !pathname_.empty() && + IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); } // Create directories so that path exists. Returns true if successful or if @@ -305,14 +337,15 @@ bool FilePath::CreateFolder() const { // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { - return pathname_.EndsWith(kPathSeparatorString) + return IsDirectory() ? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) : *this; } -// Normalize removes any redundant separators that might be in the pathname. +// Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". +// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). void FilePath::Normalize() { if (pathname_.c_str() == NULL) { pathname_ = ""; @@ -324,12 +357,19 @@ void FilePath::Normalize() { memset(dest_ptr, 0, pathname_.length() + 1); while (*src != '\0') { - *dest_ptr++ = *src; - if (*src != kPathSeparator) + *dest_ptr = *src; + if (!IsPathSeparator(*src)) { src++; - else - while (*src == kPathSeparator) + } else { +#if GTEST_HAS_ALT_PATH_SEP_ + if (*dest_ptr == kAlternatePathSeparator) { + *dest_ptr = kPathSeparator; + } +#endif + while (IsPathSeparator(*src)) src++; + } + dest_ptr++; } *dest_ptr = '\0'; pathname_ = dest; diff --git a/utils/unittest/googletest/gtest-port.cc b/utils/unittest/googletest/gtest-port.cc index 675efe89a4..56095994cd 100644 --- a/utils/unittest/googletest/gtest-port.cc +++ b/utils/unittest/googletest/gtest-port.cc @@ -68,8 +68,10 @@ namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. +const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else +const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER @@ -109,8 +111,14 @@ size_t GetThreadCount() { // Implements RE. Currently only needed for death tests. RE::~RE() { - regfree(&partial_regex_); - regfree(&full_regex_); + if (is_valid_) { + // regfree'ing an invalid regex might crash because the content + // of the regex is undefined. Since the regex's are essentially + // the same, one cannot be valid (or invalid) without the other + // being so too. + regfree(&partial_regex_); + regfree(&full_regex_); + } free(const_cast<char*>(pattern_)); } @@ -150,9 +158,10 @@ void RE::Init(const char* regex) { // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. - const char* const partial_regex = (*regex == '\0') ? "()" : regex; - is_valid_ = (regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0) - && is_valid_; + if (is_valid_) { + const char* const partial_regex = (*regex == '\0') ? "()" : regex; + is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; @@ -439,81 +448,83 @@ GTestLog::~GTestLog() { #pragma warning(disable: 4996) #endif // _MSC_VER -// Defines the stderr capturer. +#if GTEST_HAS_STREAM_REDIRECTION_ -class CapturedStderr { +// Object that captures an output stream (stdout/stderr). +class CapturedStream { public: - // The ctor redirects stderr to a temporary file. - CapturedStderr() { -#if GTEST_OS_WINDOWS_MOBILE - // Not supported on Windows CE. - posix::Abort(); -#else - uncaptured_fd_ = dup(kStdErrFileno); - + // The ctor redirects the stream to a temporary file. + CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { #if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, temp_file_path); + const UINT success = ::GetTempFileNameA(temp_dir_path, + "gtest_redir", + 0, // Generate unique file name. + temp_file_path); + GTEST_CHECK_(success != 0) + << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); + GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " + << temp_file_path; filename_ = temp_file_path; #else // There's no guarantee that a test has write access to the // current directory, so we create the temporary file in the /tmp // directory instead. - char name_template[] = "/tmp/captured_stderr.XXXXXX"; + char name_template[] = "/tmp/captured_stream.XXXXXX"; const int captured_fd = mkstemp(name_template); filename_ = name_template; #endif // GTEST_OS_WINDOWS fflush(NULL); - dup2(captured_fd, kStdErrFileno); + dup2(captured_fd, fd_); close(captured_fd); -#endif // GTEST_OS_WINDOWS_MOBILE } - ~CapturedStderr() { -#if !GTEST_OS_WINDOWS_MOBILE + ~CapturedStream() { remove(filename_.c_str()); -#endif // !GTEST_OS_WINDOWS_MOBILE } - // Stops redirecting stderr. - void StopCapture() { -#if !GTEST_OS_WINDOWS_MOBILE - // Restores the original stream. - fflush(NULL); - dup2(uncaptured_fd_, kStdErrFileno); - close(uncaptured_fd_); - uncaptured_fd_ = -1; -#endif // !GTEST_OS_WINDOWS_MOBILE - } + String GetCapturedString() { + if (uncaptured_fd_ != -1) { + // Restores the original stream. + fflush(NULL); + dup2(uncaptured_fd_, fd_); + close(uncaptured_fd_); + uncaptured_fd_ = -1; + } - // Returns the name of the temporary file holding the stderr output. - // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we - // can use it here. - ::std::string filename() const { return filename_; } + FILE* const file = posix::FOpen(filename_.c_str(), "r"); + const String content = ReadEntireFile(file); + posix::FClose(file); + return content; + } private: + // Reads the entire content of a file as a String. + static String ReadEntireFile(FILE* file); + + // Returns the size (in bytes) of a file. + static size_t GetFileSize(FILE* file); + + const int fd_; // A stream to capture. int uncaptured_fd_; + // Name of the temporary file holding the stderr output. ::std::string filename_; -}; -#ifdef _MSC_VER -#pragma warning(pop) -#endif // _MSC_VER - -static CapturedStderr* g_captured_stderr = NULL; + GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); +}; // Returns the size (in bytes) of a file. -static size_t GetFileSize(FILE * file) { +size_t CapturedStream::GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast<size_t>(ftell(file)); } // Reads the entire content of a file as a string. -static String ReadEntireFile(FILE * file) { +String CapturedStream::ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; @@ -535,30 +546,50 @@ static String ReadEntireFile(FILE * file) { return content; } -// Starts capturing stderr. -void CaptureStderr() { - if (g_captured_stderr != NULL) { - GTEST_LOG_(FATAL) << "Only one stderr capturer can exist at one time."; +#ifdef _MSC_VER +#pragma warning(pop) +#endif // _MSC_VER + +static CapturedStream* g_captured_stderr = NULL; +static CapturedStream* g_captured_stdout = NULL; + +// Starts capturing an output stream (stdout/stderr). +void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { + if (*stream != NULL) { + GTEST_LOG_(FATAL) << "Only one " << stream_name + << " capturer can exist at a time."; } - g_captured_stderr = new CapturedStderr; + *stream = new CapturedStream(fd); } -// Stops capturing stderr and returns the captured string. -// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can -// use it here. -String GetCapturedStderr() { - g_captured_stderr->StopCapture(); +// Stops capturing the output stream and returns the captured string. +String GetCapturedStream(CapturedStream** captured_stream) { + const String content = (*captured_stream)->GetCapturedString(); - FILE* const file = posix::FOpen(g_captured_stderr->filename().c_str(), "r"); - const String content = ReadEntireFile(file); - posix::FClose(file); - - delete g_captured_stderr; - g_captured_stderr = NULL; + delete *captured_stream; + *captured_stream = NULL; return content; } +// Starts capturing stdout. +void CaptureStdout() { + CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); +} + +// Starts capturing stderr. +void CaptureStderr() { + CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); +} + +// Stops capturing stdout and returns the captured string. +String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } + +// Stops capturing stderr and returns the captured string. +String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } + +#endif // GTEST_HAS_STREAM_REDIRECTION_ + #if GTEST_HAS_DEATH_TEST // A copy of all command line arguments. Set by InitGoogleTest(). diff --git a/utils/unittest/googletest/gtest-test-part.cc b/utils/unittest/googletest/gtest-test-part.cc index 2d4cc2bd1e..8249afeb4c 100644 --- a/utils/unittest/googletest/gtest-test-part.cc +++ b/utils/unittest/googletest/gtest-test-part.cc @@ -64,19 +64,9 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { << result.message() << std::endl; } -// Constructs an empty TestPartResultArray. -TestPartResultArray::TestPartResultArray() - : array_(new internal::Vector<TestPartResult>) { -} - -// Destructs a TestPartResultArray. -TestPartResultArray::~TestPartResultArray() { - delete array_; -} - // Appends a TestPartResult to the array. void TestPartResultArray::Append(const TestPartResult& result) { - array_->PushBack(result); + array_.push_back(result); } // Returns the TestPartResult at the given index (0-based). @@ -86,12 +76,12 @@ const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { internal::posix::Abort(); } - return array_->GetElement(index); + return array_[index]; } // Returns the number of TestPartResult objects in the array. int TestPartResultArray::size() const { - return array_->size(); + return static_cast<int>(array_.size()); } namespace internal { diff --git a/utils/unittest/googletest/gtest-typed-test.cc b/utils/unittest/googletest/gtest-typed-test.cc index 4a0f657d79..3cc4b5de2a 100644 --- a/utils/unittest/googletest/gtest-typed-test.cc +++ b/utils/unittest/googletest/gtest-typed-test.cc @@ -37,6 +37,14 @@ namespace internal { #if GTEST_HAS_TYPED_TEST_P +// Skips to the first non-space char in str. Returns an empty string if str +// contains only whitespace characters. +static const char* SkipSpaces(const char* str) { + while (isspace(*str)) + str++; + return str; +} + // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. @@ -45,6 +53,10 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( typedef ::std::set<const char*>::const_iterator DefinedTestIter; registered_ = true; + // Skip initial whitespace in registered_tests since some + // preprocessors prefix stringizied literals with whitespace. + registered_tests = SkipSpaces(registered_tests); + Message errors; ::std::set<String> tests; for (const char* names = registered_tests; names != NULL; diff --git a/utils/unittest/googletest/gtest.cc b/utils/unittest/googletest/gtest.cc index 8657a8aa02..74427af361 100644 --- a/utils/unittest/googletest/gtest.cc +++ b/utils/unittest/googletest/gtest.cc @@ -42,7 +42,10 @@ #include <wchar.h> #include <wctype.h> +#include <algorithm> #include <ostream> +#include <sstream> +#include <vector> #if GTEST_OS_LINUX @@ -131,6 +134,11 @@ namespace testing { +using internal::CountIf; +using internal::ForEach; +using internal::GetElementOr; +using internal::Shuffle; + // Constants. // A test whose test case name or test name matches this filter is @@ -161,6 +169,10 @@ namespace internal { // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +bool g_help_flag = false; + } // namespace internal GTEST_DEFINE_bool_( @@ -242,7 +254,7 @@ GTEST_DEFINE_bool_( GTEST_DEFINE_int32_( stack_trace_depth, - internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); @@ -274,10 +286,6 @@ UInt32 Random::Generate(UInt32 range) { return state_ % range; } -// g_help_flag is true iff the --help flag or an equivalent form is -// specified on the command line. -static bool g_help_flag = false; - // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). @@ -292,11 +300,11 @@ static bool GTestIsInitialized() { return g_init_gtest_count != 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. -static int SumOverTestCaseList(const internal::Vector<TestCase*>& case_list, +static int SumOverTestCaseList(const std::vector<TestCase*>& case_list, int (TestCase::*method)() const) { int sum = 0; - for (int i = 0; i < case_list.size(); i++) { - sum += (case_list.GetElement(i)->*method)(); + for (size_t i = 0; i < case_list.size(); i++) { + sum += (case_list[i]->*method)(); } return sum; } @@ -341,7 +349,7 @@ void AssertHelper::operator=(const Message& message) const { } // Mutex for linked pointers. -Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX); +GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); // Application pathname gotten in InitGoogleTest. String g_executable_path; @@ -672,23 +680,23 @@ void UnitTestImpl::SetTestPartResultReporterForCurrentThread( // Gets the number of successful test cases. int UnitTestImpl::successful_test_case_count() const { - return test_cases_.CountIf(TestCasePassed); + return CountIf(test_cases_, TestCasePassed); } // Gets the number of failed test cases. int UnitTestImpl::failed_test_case_count() const { - return test_cases_.CountIf(TestCaseFailed); + return CountIf(test_cases_, TestCaseFailed); } // Gets the number of all test cases. int UnitTestImpl::total_test_case_count() const { - return test_cases_.size(); + return static_cast<int>(test_cases_.size()); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTestImpl::test_case_to_run_count() const { - return test_cases_.CountIf(ShouldRunTestCase); + return CountIf(test_cases_, ShouldRunTestCase); } // Gets the number of successful tests. @@ -952,21 +960,37 @@ String FormatForFailureMessage(wchar_t wchar) { } // namespace internal -// AssertionResult constructor. -AssertionResult::AssertionResult(const internal::String& failure_message) - : failure_message_(failure_message) { +// AssertionResult constructors. +// Used in EXPECT_TRUE/FALSE(assertion_result). +AssertionResult::AssertionResult(const AssertionResult& other) + : success_(other.success_), + message_(other.message_.get() != NULL ? + new internal::String(*other.message_) : + static_cast<internal::String*>(NULL)) { } +// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. +AssertionResult AssertionResult::operator!() const { + AssertionResult negation(!success_); + if (message_.get() != NULL) + negation << *message_; + return negation; +} // Makes a successful assertion result. AssertionResult AssertionSuccess() { - return AssertionResult(); + return AssertionResult(true); } +// Makes a failed assertion result. +AssertionResult AssertionFailure() { + return AssertionResult(false); +} // Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << message. AssertionResult AssertionFailure(const Message& message) { - return AssertionResult(message.GetString()); + return AssertionFailure() << message; } namespace internal { @@ -1008,6 +1032,20 @@ AssertionResult EqFailure(const char* expected_expression, return AssertionFailure(msg); } +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value) { + const char* actual_message = assertion_result.message(); + Message msg; + msg << "Value of: " << expression_text + << "\n Actual: " << actual_predicate_value; + if (actual_message[0] != '\0') + msg << " (" << actual_message << ")"; + msg << "\nExpected: " << expected_predicate_value; + return msg.GetString(); +} // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, @@ -1286,7 +1324,6 @@ AssertionResult IsNotSubstring( return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -#if GTEST_HAS_STD_STRING AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { @@ -1298,7 +1335,6 @@ AssertionResult IsNotSubstring( const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring( @@ -1718,14 +1754,9 @@ String String::Format(const char * format, ...) { // Converts the buffer in a StrStream to a String, converting NUL // bytes to "\\0" along the way. String StrStreamToString(StrStream* ss) { -#if GTEST_HAS_STD_STRING const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); -#else - const char* const start = ss->str(); - const char* const end = start + ss->pcount(); -#endif // GTEST_HAS_STD_STRING // We need to use a helper StrStream to do this transformation // because String doesn't support push_back(). @@ -1738,14 +1769,7 @@ String StrStreamToString(StrStream* ss) { } } -#if GTEST_HAS_STD_STRING return String(helper.str().c_str()); -#else - const String str(helper.str(), helper.pcount()); - helper.freeze(false); - ss->freeze(false); - return str; -#endif // GTEST_HAS_STD_STRING } // Appends the user-supplied message to the Google-Test-generated message. @@ -1769,9 +1793,7 @@ String AppendUserMessage(const String& gtest_msg, // Creates an empty TestResult. TestResult::TestResult() - : test_part_results_(new internal::Vector<TestPartResult>), - test_properties_(new internal::Vector<TestProperty>), - death_test_count_(0), + : death_test_count_(0), elapsed_time_(0) { } @@ -1783,24 +1805,28 @@ TestResult::~TestResult() { // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { - return test_part_results_->GetElement(i); + if (i < 0 || i >= total_part_count()) + internal::posix::Abort(); + return test_part_results_.at(i); } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { - return test_properties_->GetElement(i); + if (i < 0 || i >= test_property_count()) + internal::posix::Abort(); + return test_properties_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { - test_part_results_->Clear(); + test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { - test_part_results_->PushBack(test_part_result); + test_part_results_.push_back(test_part_result); } // Adds a test property to the list. If a property with the same key as the @@ -1811,11 +1837,11 @@ void TestResult::RecordProperty(const TestProperty& test_property) { return; } internal::MutexLock lock(&test_properites_mutex_); - TestProperty* const property_with_matching_key = - test_properties_->FindIf( - internal::TestPropertyKeyIs(test_property.key())); - if (property_with_matching_key == NULL) { - test_properties_->PushBack(test_property); + const std::vector<TestProperty>::iterator property_with_matching_key = + std::find_if(test_properties_.begin(), test_properties_.end(), + internal::TestPropertyKeyIs(test_property.key())); + if (property_with_matching_key == test_properties_.end()) { + test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); @@ -1838,8 +1864,8 @@ bool TestResult::ValidateTestProperty(const TestProperty& test_property) { // Clears the object. void TestResult::Clear() { - test_part_results_->Clear(); - test_properties_->Clear(); + test_part_results_.clear(); + test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } @@ -1860,7 +1886,7 @@ static bool TestPartFatallyFailed(const TestPartResult& result) { // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { - return test_part_results_->CountIf(TestPartFatallyFailed) > 0; + return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. @@ -1870,18 +1896,18 @@ static bool TestPartNonfatallyFailed(const TestPartResult& result) { // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { - return test_part_results_->CountIf(TestPartNonfatallyFailed) > 0; + return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { - return test_part_results_->size(); + return static_cast<int>(test_part_results_.size()); } // Returns the number of the test properties. int TestResult::test_property_count() const { - return test_properties_->size(); + return static_cast<int>(test_properties_.size()); } // class Test @@ -1965,7 +1991,7 @@ bool Test::HasSameFixtureClass() { // Info about the first test in the current test case. const internal::TestInfoImpl* const first_test_info = - test_case->test_info_list().GetElement(0)->impl(); + test_case->test_info_list()[0]->impl(); const internal::TypeId first_fixture_id = first_test_info->fixture_class_id(); const char* const first_test_name = first_test_info->name(); @@ -2093,14 +2119,14 @@ bool Test::HasNonfatalFailure() { // Constructs a TestInfo object. It assumes ownership of the test factory // object via impl_. -TestInfo::TestInfo(const char* test_case_name, - const char* name, - const char* test_case_comment, - const char* comment, +TestInfo::TestInfo(const char* a_test_case_name, + const char* a_name, + const char* a_test_case_comment, + const char* a_comment, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) { - impl_ = new internal::TestInfoImpl(this, test_case_name, name, - test_case_comment, comment, + impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name, + a_test_case_comment, a_comment, fixture_class_id, factory); } @@ -2309,26 +2335,26 @@ void TestInfoImpl::Run() { // Gets the number of successful tests in this test case. int TestCase::successful_test_count() const { - return test_info_list_->CountIf(TestPassed); + return CountIf(test_info_list_, TestPassed); } // Gets the number of failed tests in this test case. int TestCase::failed_test_count() const { - return test_info_list_->CountIf(TestFailed); + return CountIf(test_info_list_, TestFailed); } int TestCase::disabled_test_count() const { - return test_info_list_->CountIf(TestDisabled); + return CountIf(test_info_list_, TestDisabled); } // Get the number of tests in this test case that should run. int TestCase::test_to_run_count() const { - return test_info_list_->CountIf(ShouldRunTest); + return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. int TestCase::total_test_count() const { - return test_info_list_->size(); + return static_cast<int>(test_info_list_.size()); } // Creates a TestCase with the given name. @@ -2338,13 +2364,11 @@ int TestCase::total_test_count() const { // name: name of the test case // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case -TestCase::TestCase(const char* name, const char* comment, +TestCase::TestCase(const char* a_name, const char* a_comment, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) - : name_(name), - comment_(comment), - test_info_list_(new internal::Vector<TestInfo*>), - test_indices_(new internal::Vector<int>), + : name_(a_name), + comment_(a_comment), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), @@ -2354,28 +2378,28 @@ TestCase::TestCase(const char* name, const char* comment, // Destructor of TestCase. TestCase::~TestCase() { // Deletes every Test in the collection. - test_info_list_->ForEach(internal::Delete<TestInfo>); + ForEach(test_info_list_, internal::Delete<TestInfo>); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestCase::GetTestInfo(int i) const { - const int index = test_indices_->GetElementOr(i, -1); - return index < 0 ? NULL : test_info_list_->GetElement(index); + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestCase::GetMutableTestInfo(int i) { - const int index = test_indices_->GetElementOr(i, -1); - return index < 0 ? NULL : test_info_list_->GetElement(index); + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; } // Adds a test to this test case. Will delete the test upon // destruction of the TestCase object. void TestCase::AddTestInfo(TestInfo * test_info) { - test_info_list_->PushBack(test_info); - test_indices_->PushBack(test_indices_->size()); + test_info_list_.push_back(test_info); + test_indices_.push_back(static_cast<int>(test_indices_.size())); } // Runs every test in this TestCase. @@ -2405,7 +2429,7 @@ void TestCase::Run() { // Clears the results of all tests in this test case. void TestCase::ClearResult() { - test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult); + ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult); } // Returns true iff test passed. @@ -2432,13 +2456,13 @@ bool TestCase::ShouldRunTest(const TestInfo *test_info) { // Shuffles the tests in this test case. void TestCase::ShuffleTests(internal::Random* random) { - test_indices_->Shuffle(random); + Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestCase::UnshuffleTests() { - for (int i = 0; i < test_indices_->size(); i++) { - test_indices_->GetMutableElement(i) = i; + for (size_t i = 0; i < test_indices_.size(); i++) { + test_indices_[i] = static_cast<int>(i); } } @@ -2614,10 +2638,15 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + fflush(stdout); SetConsoleTextAttribute(stdout_handle, GetColorAttribute(color) | FOREGROUND_INTENSITY); vprintf(fmt, args); + fflush(stdout); // Restores the text color. SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else @@ -2880,26 +2909,24 @@ class TestEventRepeater : public TestEventListener { // in death test child processes. bool forwarding_enabled_; // The list of listeners that receive events. - Vector<TestEventListener*> listeners_; + std::vector<TestEventListener*> listeners_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; TestEventRepeater::~TestEventRepeater() { - for (int i = 0; i < listeners_.size(); i++) { - delete listeners_.GetElement(i); - } + ForEach(listeners_, Delete<TestEventListener>); } void TestEventRepeater::Append(TestEventListener *listener) { - listeners_.PushBack(listener); + listeners_.push_back(listener); } // TODO(vladl@google.com): Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { - for (int i = 0; i < listeners_.size(); ++i) { - if (listeners_.GetElement(i) == listener) { - listeners_.Erase(i); + for (size_t i = 0; i < listeners_.size(); ++i) { + if (listeners_[i] == listener) { + listeners_.erase(listeners_.begin() + i); return listener; } } @@ -2912,8 +2939,8 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ - for (int i = 0; i < listeners_.size(); i++) { \ - listeners_.GetElement(i)->Name(parameter); \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ } \ } \ } @@ -2923,7 +2950,7 @@ void TestEventRepeater::Name(const Type& parameter) { \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ - listeners_.GetElement(i)->Name(parameter); \ + listeners_[i]->Name(parameter); \ } \ } \ } @@ -2946,8 +2973,8 @@ GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { - for (int i = 0; i < listeners_.size(); i++) { - listeners_.GetElement(i)->OnTestIterationStart(unit_test, iteration); + for (size_t i = 0; i < listeners_.size(); i++) { + listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } @@ -2956,7 +2983,7 @@ void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { - listeners_.GetElement(i)->OnTestIterationEnd(unit_test, iteration); + listeners_[i]->OnTestIterationEnd(unit_test, iteration); } } } @@ -3152,14 +3179,11 @@ String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) { // </testsuite> // </testsuites> -// Formats the given time in milliseconds as seconds. The returned -// C-string is owned by this function and cannot be released by the -// caller. Calling the function again invalidates the previous -// result. -const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) { - static String str; - str = (Message() << (ms/1000.0)).GetString(); - return str.c_str(); +// Formats the given time in milliseconds as seconds. +std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { + ::std::stringstream ss; + ss << ms/1000.0; + return ss.str(); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. @@ -3170,7 +3194,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != NULL) { - stream->write(segment, next_segment - segment); + stream->write( + segment, static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]><![CDATA["; segment = next_segment + strlen("]]>"); } else { @@ -3232,7 +3257,7 @@ void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, test_case.disabled_test_count()); fprintf(out, "errors=\"0\" time=\"%s\">\n", - FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); for (int i = 0; i < test_case.total_test_count(); ++i) { StrStream stream; OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); @@ -3251,7 +3276,7 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, unit_test.total_test_count(), unit_test.failed_test_count(), unit_test.disabled_test_count(), - FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str()); if (GTEST_FLAG(shuffle)) { fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed()); } @@ -3512,8 +3537,7 @@ Environment* UnitTest::AddEnvironment(Environment* env) { return NULL; } - impl_->environments()->PushBack(env); - impl_->environments_in_reverse_order()->PushFront(env); + impl_->environments().push_back(env); return env; } @@ -3544,12 +3568,12 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, msg << message; internal::MutexLock lock(&mutex_); - if (impl_->gtest_trace_stack()->size() > 0) { + if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; - for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) { - const internal::TraceInfo& trace = - impl_->gtest_trace_stack()->GetElement(i); + for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); + i > 0; --i) { + const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } @@ -3714,14 +3738,14 @@ UnitTest::~UnitTest() { // L < mutex_ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack()->PushFront(trace); + impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. // L < mutex_ void UnitTest::PopGTestTrace() { internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack()->PopFront(NULL); + impl_->gtest_trace_stack().pop_back(); } namespace internal { @@ -3767,10 +3791,10 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) UnitTestImpl::~UnitTestImpl() { // Deletes every TestCase. - test_cases_.ForEach(internal::Delete<TestCase>); + ForEach(test_cases_, internal::Delete<TestCase>); // Deletes every Environment. - environments_.ForEach(internal::Delete<Environment>); + ForEach(environments_, internal::Delete<Environment>); delete os_stack_trace_getter_; } @@ -3862,9 +3886,11 @@ TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? - TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name)); + const std::vector<TestCase*>::const_iterator test_case = + std::find_if(test_cases_.begin(), test_cases_.end(), + TestCaseNameIs(test_case_name)); - if (test_case != NULL) + if (test_case != test_cases_.end()) return *test_case; // No. Let's create one. @@ -3878,18 +3904,20 @@ TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, // defined so far. This only works when the test cases haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. - test_cases_.Insert(new_test_case, ++last_death_test_case_); + ++last_death_test_case_; + test_cases_.insert(test_cases_.begin() + last_death_test_case_, + new_test_case); } else { // No. Appends to the end of the list. - test_cases_.PushBack(new_test_case); + test_cases_.push_back(new_test_case); } - test_case_indices_.PushBack(test_case_indices_.size()); + test_case_indices_.push_back(static_cast<int>(test_case_indices_.size())); return new_test_case; } // Helpers for setting up / tearing down the given environment. They -// are for use in the Vector::ForEach() method. +// are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } @@ -3985,20 +4013,22 @@ int UnitTestImpl::RunAllTests() { if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); - environments_.ForEach(SetUpEnvironment); + ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { - for (int i = 0; i < total_test_case_count(); i++) { - GetMutableTestCase(i)->Run(); + for (int test_index = 0; test_index < total_test_case_count(); + test_index++) { + GetMutableTestCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); - environments_in_reverse_order_.ForEach(TearDownEnvironment); + std::for_each(environments_.rbegin(), environments_.rend(), + TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } @@ -4144,13 +4174,13 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; - for (int i = 0; i < test_cases_.size(); i++) { - TestCase* const test_case = test_cases_.GetElement(i); + for (size_t i = 0; i < test_cases_.size(); i++) { + TestCase* const test_case = test_cases_[i]; const String &test_case_name = test_case->name(); test_case->set_should_run(false); - for (int j = 0; j < test_case->test_info_list().size(); j++) { - TestInfo* const test_info = test_case->test_info_list().GetElement(j); + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + TestInfo* const test_info = test_case->test_info_list()[j]; const String test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. @@ -4187,13 +4217,13 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { - for (int i = 0; i < test_cases_.size(); i++) { - const TestCase* const test_case = test_cases_.GetElement(i); + for (size_t i = 0; i < test_cases_.size(); i++) { + const TestCase* const test_case = test_cases_[i]; bool printed_test_case_name = false; - for (int j = 0; j < test_case->test_info_list().size(); j++) { + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { const TestInfo* const test_info = - test_case->test_info_list().GetElement(j); + test_case->test_info_list()[j]; if (test_info->matches_filter()) { if (!printed_test_case_name) { printed_test_case_name = true; @@ -4241,43 +4271,43 @@ TestResult* UnitTestImpl::current_test_result() { // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { // Shuffles the death test cases. - test_case_indices_.ShuffleRange(random(), 0, last_death_test_case_ + 1); + ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); // Shuffles the non-death test cases. - test_case_indices_.ShuffleRange(random(), last_death_test_case_ + 1, - test_cases_.size()); + ShuffleRange(random(), last_death_test_case_ + 1, + static_cast<int>(test_cases_.size()), &test_case_indices_); // Shuffles the tests inside each test case. - for (int i = 0; i < test_cases_.size(); i++) { - test_cases_.GetElement(i)->ShuffleTests(random()); + for (size_t i = 0; i < test_cases_.size(); i++) { + test_cases_[i]->ShuffleTests(random()); } } // Restores the test cases and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { - for (int i = 0; i < test_cases_.size(); i++) { + for (size_t i = 0; i < test_cases_.size(); i++) { // Unshuffles the tests in each test case. - test_cases_.GetElement(i)->UnshuffleTests(); + test_cases_[i]->UnshuffleTests(); // Resets the index of each test case. - test_case_indices_.GetMutableElement(i) = i; + test_case_indices_[i] = static_cast<int>(i); } } // TestInfoImpl constructor. The new instance assumes ownership of the test // factory object. TestInfoImpl::TestInfoImpl(TestInfo* parent, - const char* test_case_name, - const char* name, - const char* test_case_comment, - const char* comment, - TypeId fixture_class_id, + const char* a_test_case_name, + const char* a_name, + const char* a_test_case_comment, + const char* a_comment, + TypeId a_fixture_class_id, internal::TestFactoryBase* factory) : parent_(parent), - test_case_name_(String(test_case_name)), - name_(String(name)), - test_case_comment_(String(test_case_comment)), - comment_(String(comment)), - fixture_class_id_(fixture_class_id), + test_case_name_(String(a_test_case_name)), + name_(String(a_name)), + test_case_comment_(String(a_test_case_comment)), + comment_(String(a_comment)), + fixture_class_id_(a_fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), @@ -4324,6 +4354,18 @@ bool AlwaysTrue() { return true; } +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +bool SkipPrefix(const char* prefix, const char** pstr) { + const size_t prefix_len = strlen(prefix); + if (strncmp(*pstr, prefix, prefix_len) == 0) { + *pstr += prefix_len; + return true; + } + return false; +} + // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. @@ -4413,6 +4455,21 @@ bool ParseStringFlag(const char* str, const char* flag, String* value) { return true; } +// Determines whether a string has a prefix that Google Test uses for its +// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. +// If Google Test detects that a command line flag has its prefix but is not +// recognized, it will print its help message. Flags starting with +// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test +// internal flags and do not trigger the help message. +static bool HasGoogleTestFlagPrefix(const char* str) { + return (SkipPrefix("--", &str) || + SkipPrefix("-", &str) || + SkipPrefix("/", &str)) && + !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && + (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || + SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); +} + // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // @@ -4553,6 +4610,8 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, + >EST_FLAG(stack_trace_depth)) || ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)) ) { // Yes. Shift the remainder of the argv list left by one. Note @@ -4570,7 +4629,10 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { // an element. i--; } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?") { + arg_string == "-?" || arg_string == "/?" || + HasGoogleTestFlagPrefix(arg)) { + // Both help flag and unrecognized Google Test flags (excluding + // internal ones) trigger help display. g_help_flag = true; } } diff --git a/utils/unittest/googletest/include/gtest/gtest-death-test.h b/utils/unittest/googletest/include/gtest/gtest-death-test.h index fdb497f4bc..121dc1fb5a 100644 --- a/utils/unittest/googletest/include/gtest/gtest-death-test.h +++ b/utils/unittest/googletest/include/gtest/gtest-death-test.h @@ -176,7 +176,7 @@ GTEST_DECLARE_string_(death_test_style); // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Tests that an exit code describes a normal exit with a given exit code. -class ExitedWithCode { +class GTEST_API_ ExitedWithCode { public: explicit ExitedWithCode(int exit_code); bool operator()(int exit_status) const; @@ -190,7 +190,7 @@ class ExitedWithCode { #if !GTEST_OS_WINDOWS // Tests that an exit code describes an exit due to termination by a // given signal. -class KilledBySignal { +class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; diff --git a/utils/unittest/googletest/include/gtest/gtest-message.h b/utils/unittest/googletest/include/gtest/gtest-message.h index 6398712e2c..f135b69427 100644 --- a/utils/unittest/googletest/include/gtest/gtest-message.h +++ b/utils/unittest/googletest/include/gtest/gtest-message.h @@ -46,6 +46,8 @@ #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ +#include <limits> + #include <gtest/internal/gtest-string.h> #include <gtest/internal/gtest-internal.h> @@ -77,7 +79,7 @@ namespace testing { // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as // "(null)". -class Message { +class GTEST_API_ Message { private: // The type of basic IO manipulators (endl, ends, and flush) for // narrow streams. @@ -89,7 +91,11 @@ class Message { // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. - Message() : ss_(new internal::StrStream) {} + Message() : ss_(new internal::StrStream) { + // By default, we want there to be enough precision when printing + // a double to a Message. + *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); + } // Copy constructor. Message(const Message& msg) : ss_(new internal::StrStream) { // NOLINT diff --git a/utils/unittest/googletest/include/gtest/gtest-param-test.h b/utils/unittest/googletest/include/gtest/gtest-param-test.h index 032885d315..3184d07ba0 100644 --- a/utils/unittest/googletest/include/gtest/gtest-param-test.h +++ b/utils/unittest/googletest/include/gtest/gtest-param-test.h @@ -133,9 +133,12 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // in the given test case, whether their definitions come before or // AFTER the INSTANTIATE_TEST_CASE_P statement. // -// Please also note that generator expressions are evaluated in -// RUN_ALL_TESTS(), after main() has started. This allows evaluation of -// parameter list based on command line parameters. +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. // // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc // for more examples. @@ -152,11 +155,14 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); #include <utility> #endif -#if GTEST_HAS_PARAM_TEST - +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. #include <gtest/internal/gtest-internal.h> #include <gtest/internal/gtest-param-util.h> +#if GTEST_HAS_PARAM_TEST + namespace testing { // Functions producing parameter generators. diff --git a/utils/unittest/googletest/include/gtest/gtest-spi.h b/utils/unittest/googletest/include/gtest/gtest-spi.h index 2953411ba9..c41da48447 100644 --- a/utils/unittest/googletest/include/gtest/gtest-spi.h +++ b/utils/unittest/googletest/include/gtest/gtest-spi.h @@ -48,7 +48,7 @@ namespace testing { // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. -class ScopedFakeTestPartResultReporter +class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. @@ -93,7 +93,7 @@ namespace internal { // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. -class SingleFailureChecker { +class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, diff --git a/utils/unittest/googletest/include/gtest/gtest-test-part.h b/utils/unittest/googletest/include/gtest/gtest-test-part.h index 58e7df9eb4..f714759067 100644 --- a/utils/unittest/googletest/include/gtest/gtest-test-part.h +++ b/utils/unittest/googletest/include/gtest/gtest-test-part.h @@ -34,6 +34,7 @@ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #include <iosfwd> +#include <vector> #include <gtest/internal/gtest-internal.h> #include <gtest/internal/gtest-string.h> @@ -43,7 +44,7 @@ namespace testing { // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). // // Don't inherit from TestPartResult as its destructor is not virtual. -class TestPartResult { +class GTEST_API_ TestPartResult { public: // The possible outcomes of a test part (i.e. an assertion or an // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). @@ -56,15 +57,15 @@ class TestPartResult { // C'tor. TestPartResult does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestPartResult object. - TestPartResult(Type type, - const char* file_name, - int line_number, - const char* message) - : type_(type), - file_name_(file_name), - line_number_(line_number), - summary_(ExtractSummary(message)), - message_(message) { + TestPartResult(Type a_type, + const char* a_file_name, + int a_line_number, + const char* a_message) + : type_(a_type), + file_name_(a_file_name), + line_number_(a_line_number), + summary_(ExtractSummary(a_message)), + message_(a_message) { } // Gets the outcome of the test part. @@ -117,15 +118,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result); // An array of TestPartResult objects. // -// We define this class as we cannot use STL containers when compiling -// Google Test with MSVC 7.1 and exceptions disabled. -// // Don't inherit from TestPartResultArray as its destructor is not // virtual. -class TestPartResultArray { +class GTEST_API_ TestPartResultArray { public: - TestPartResultArray(); - ~TestPartResultArray(); + TestPartResultArray() {} // Appends the given TestPartResult to the array. void Append(const TestPartResult& result); @@ -135,9 +132,9 @@ class TestPartResultArray { // Returns the number of TestPartResult objects in the array. int size() const; + private: - // Internally we use a Vector to implement the array. - internal::Vector<TestPartResult>* const array_; + std::vector<TestPartResult> array_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); }; @@ -158,7 +155,8 @@ namespace internal { // reported, it only delegates the reporting to the former result reporter. // The original result reporter is restored in the destructor. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -class HasNewFatalFailureHelper : public TestPartResultReporterInterface { +class GTEST_API_ HasNewFatalFailureHelper + : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); virtual ~HasNewFatalFailureHelper(); diff --git a/utils/unittest/googletest/include/gtest/gtest-typed-test.h b/utils/unittest/googletest/include/gtest/gtest-typed-test.h index 519edfe920..1ec8eb8d30 100644 --- a/utils/unittest/googletest/include/gtest/gtest-typed-test.h +++ b/utils/unittest/googletest/include/gtest/gtest-typed-test.h @@ -159,8 +159,11 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // given test case. #define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types<int>) #define TYPED_TEST_CASE(CaseName, Types) \ - typedef ::testing::internal::TypeList<Types>::type \ + typedef ::testing::internal::TypeList< Types >::type \ GTEST_TYPE_PARAMS_(CaseName) #define TYPED_TEST(CaseName, TestName) \ @@ -241,11 +244,14 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ __FILE__, __LINE__, #__VA_ARGS__) +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types<int>) #define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ bool gtest_##Prefix##_##CaseName = \ ::testing::internal::TypeParameterizedTestCase<CaseName, \ GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ - ::testing::internal::TypeList<Types>::type>::Register(\ + ::testing::internal::TypeList< Types >::type>::Register(\ #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) #endif // GTEST_HAS_TYPED_TEST_P diff --git a/utils/unittest/googletest/include/gtest/gtest.h b/utils/unittest/googletest/include/gtest/gtest.h index 9be15fbeab..921fad11fc 100644 --- a/utils/unittest/googletest/include/gtest/gtest.h +++ b/utils/unittest/googletest/include/gtest/gtest.h @@ -52,6 +52,8 @@ #define GTEST_INCLUDE_GTEST_GTEST_H_ #include <limits> +#include <vector> + #include <gtest/internal/gtest-internal.h> #include <gtest/internal/gtest-string.h> #include <gtest/gtest-death-test.h> @@ -62,24 +64,19 @@ #include <gtest/gtest-typed-test.h> // Depending on the platform, different string classes are available. -// On Windows, ::std::string compiles only when exceptions are -// enabled. On Linux, in addition to ::std::string, Google also makes -// use of class ::string, which has the same interface as -// ::std::string, but has a different implementation. -// -// The user can tell us whether ::std::string is available in his -// environment by defining the macro GTEST_HAS_STD_STRING to either 1 -// or 0 on the compiler command line. He can also define -// GTEST_HAS_GLOBAL_STRING to 1 to indicate that ::string is available -// AND is a distinct type to ::std::string, or define it to 0 to -// indicate otherwise. +// On Linux, in addition to ::std::string, Google also makes use of +// class ::string, which has the same interface as ::std::string, but +// has a different implementation. +// +// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that +// ::string is available AND is a distinct type to ::std::string, or +// define it to 0 to indicate otherwise. // // If the user's ::std::string and ::string are the same class due to -// aliasing, he should define GTEST_HAS_STD_STRING to 1 and -// GTEST_HAS_GLOBAL_STRING to 0. +// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. // -// If the user doesn't define GTEST_HAS_STD_STRING and/or -// GTEST_HAS_GLOBAL_STRING, they are defined heuristically. +// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined +// heuristically. namespace testing { @@ -177,64 +174,146 @@ String StreamableToString(const T& streamable) { // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object -// remembers a non-empty message that described how it failed. -// -// This class is useful for defining predicate-format functions to be -// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). +// remembers a non-empty message that describes how it failed. // -// The constructor of AssertionResult is private. To create an -// instance of this class, use one of the factory functions +// To create an instance of this class, use one of the factory functions // (AssertionSuccess() and AssertionFailure()). // -// For example, in order to be able to write: +// This class is useful for two purposes: +// 1. Defining predicate functions to be used with Boolean test assertions +// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts +// 2. Defining predicate-format functions to be +// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). +// +// For example, if you define IsEven predicate: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) +// will print the message +// +// Value of: IsEven(Fib(5)) +// Actual: false (5 is odd) +// Expected: true +// +// instead of a more opaque +// +// Value of: IsEven(Fib(5)) +// Actual: false +// Expected: true +// +// in case IsEven is a simple Boolean predicate. +// +// If you expect your predicate to be reused and want to support informative +// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up +// about half as often as positive ones in our tests), supply messages for +// both success and failure cases: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess() << n << " is even"; +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print +// +// Value of: IsEven(Fib(6)) +// Actual: true (8 is even) +// Expected: false +// +// NB: Predicates that support negative Boolean assertions have reduced +// performance in positive ones so be careful not to use them in tests +// that have lots (tens of thousands) of positive Boolean assertions. +// +// To use this class with EXPECT_PRED_FORMAT assertions such as: // // // Verifies that Foo() returns an even number. // EXPECT_PRED_FORMAT1(IsEven, Foo()); // -// you just need to define: +// you need to define: // // testing::AssertionResult IsEven(const char* expr, int n) { -// if ((n % 2) == 0) return testing::AssertionSuccess(); -// -// Message msg; -// msg << "Expected: " << expr << " is even\n" -// << " Actual: it's " << n; -// return testing::AssertionFailure(msg); +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() +// << "Expected: " << expr << " is even\n Actual: it's " << n; // } // // If Foo() returns 5, you will see the following message: // // Expected: Foo() is even // Actual: it's 5 -class AssertionResult { +// +class GTEST_API_ AssertionResult { public: - // Declares factory functions for making successful and failed - // assertion results as friends. - friend AssertionResult AssertionSuccess(); - friend AssertionResult AssertionFailure(const Message&); + // Copy constructor. + // Used in EXPECT_TRUE/FALSE(assertion_result). + AssertionResult(const AssertionResult& other); + // Used in the EXPECT_TRUE/FALSE(bool_expression). + explicit AssertionResult(bool success) : success_(success) {} // Returns true iff the assertion succeeded. - operator bool() const { return failure_message_.c_str() == NULL; } // NOLINT + operator bool() const { return success_; } // NOLINT + + // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. + AssertionResult operator!() const; + + // Returns the text streamed into this AssertionResult. Test assertions + // use it when they fail (i.e., the predicate's outcome doesn't match the + // assertion's expectation). When nothing has been streamed into the + // object, returns an empty string. + const char* message() const { + return message_.get() != NULL && message_->c_str() != NULL ? + message_->c_str() : ""; + } + // TODO(vladl@google.com): Remove this after making sure no clients use it. + // Deprecated; please use message() instead. + const char* failure_message() const { return message(); } - // Returns the assertion's failure message. - const char* failure_message() const { return failure_message_.c_str(); } + // Streams a custom failure message into this object. + template <typename T> AssertionResult& operator<<(const T& value); private: - // The default constructor. It is used when the assertion succeeded. - AssertionResult() {} - - // The constructor used when the assertion failed. - explicit AssertionResult(const internal::String& failure_message); - - // Stores the assertion's failure message. - internal::String failure_message_; -}; + // No implementation - we want AssertionResult to be + // copy-constructible but not assignable. + void operator=(const AssertionResult& other); + + // Stores result of the assertion predicate. + bool success_; + // Stores the message describing the condition in case the expectation + // construct is not satisfied with the predicate's outcome. + // Referenced via a pointer to avoid taking too much stack frame space + // with test assertions. + internal::scoped_ptr<internal::String> message_; +}; // class AssertionResult + +// Streams a custom failure message into this object. +template <typename T> +AssertionResult& AssertionResult::operator<<(const T& value) { + Message msg; + if (message_.get() != NULL) + msg << *message_; + msg << value; + message_.reset(new internal::String(msg.GetString())); + return *this; +} // Makes a successful assertion result. -AssertionResult AssertionSuccess(); +GTEST_API_ AssertionResult AssertionSuccess(); + +// Makes a failed assertion result. +GTEST_API_ AssertionResult AssertionFailure(); // Makes a failed assertion result with the given failure message. -AssertionResult AssertionFailure(const Message& msg); +// Deprecated; use AssertionFailure() << msg. +GTEST_API_ AssertionResult AssertionFailure(const Message& msg); // The abstract class that all tests inherit from. // @@ -259,7 +338,7 @@ AssertionResult AssertionFailure(const Message& msg); // TEST_F(FooTest, Baz) { ... } // // Test is not copyable. -class Test { +class GTEST_API_ Test { public: friend class internal::TestInfoImpl; @@ -375,8 +454,8 @@ class TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const char* key, const char* value) : - key_(key), value_(value) { + TestProperty(const char* a_key, const char* a_value) : + key_(a_key), value_(a_value) { } // Gets the user supplied key. @@ -407,7 +486,7 @@ class TestProperty { // the Test. // // TestResult is not copyable. -class TestResult { +class GTEST_API_ TestResult { public: // Creates an empty TestResult. TestResult(); @@ -458,13 +537,13 @@ class TestResult { friend class internal::WindowsDeathTest; // Gets the vector of TestPartResults. - const internal::Vector<TestPartResult>& test_part_results() const { - return *test_part_results_; + const std::vector<TestPartResult>& test_part_results() const { + return test_part_results_; } // Gets the vector of TestProperties. - const internal::Vector<TestProperty>& test_properties() const { - return *test_properties_; + const std::vector<TestProperty>& test_properties() const { + return test_properties_; } // Sets the elapsed time. @@ -502,9 +581,9 @@ class TestResult { internal::Mutex test_properites_mutex_; // The vector of TestPartResults - internal::scoped_ptr<internal::Vector<TestPartResult> > test_part_results_; + std::vector<TestPartResult> test_part_results_; // The vector of TestProperties - internal::scoped_ptr<internal::Vector<TestProperty> > test_properties_; + std::vector<TestProperty> test_properties_; // Running count of death tests. int death_test_count_; // The elapsed time, in milliseconds. @@ -525,7 +604,7 @@ class TestResult { // The constructor of TestInfo registers itself with the UnitTest // singleton such that the RUN_ALL_TESTS() macro knows which tests to // run. -class TestInfo { +class GTEST_API_ TestInfo { public: // Destructs a TestInfo object. This function is not virtual, so // don't inherit from TestInfo. @@ -607,7 +686,7 @@ class TestInfo { // A test case, which consists of a vector of TestInfos. // // TestCase is not copyable. -class TestCase { +class GTEST_API_ TestCase { public: // Creates a TestCase with the given name. // @@ -668,11 +747,11 @@ class TestCase { friend class internal::UnitTestImpl; // Gets the (mutable) vector of TestInfos in this TestCase. - internal::Vector<TestInfo*>& test_info_list() { return *test_info_list_; } + std::vector<TestInfo*>& test_info_list() { return test_info_list_; } // Gets the (immutable) vector of TestInfos in this TestCase. - const internal::Vector<TestInfo *> & test_info_list() const { - return *test_info_list_; + const std::vector<TestInfo*>& test_info_list() const { + return test_info_list_; } // Returns the i-th test among all the tests. i can range from 0 to @@ -721,11 +800,11 @@ class TestCase { internal::String comment_; // The vector of TestInfos in their original order. It owns the // elements in the vector. - const internal::scoped_ptr<internal::Vector<TestInfo*> > test_info_list_; + std::vector<TestInfo*> test_info_list_; // Provides a level of indirection for the test list to allow easy // shuffling and restoring the test order. The i-th element in this // vector is the index of the i-th test in the shuffled test list. - const internal::scoped_ptr<internal::Vector<int> > test_indices_; + std::vector<int> test_indices_; // Pointer to the function that sets up the test case. Test::SetUpTestCaseFunc set_up_tc_; // Pointer to the function that tears down the test case. @@ -845,7 +924,7 @@ class EmptyTestEventListener : public TestEventListener { }; // TestEventListeners lets users add listeners to track events in Google Test. -class TestEventListeners { +class GTEST_API_ TestEventListeners { public: TestEventListeners(); ~TestEventListeners(); @@ -932,7 +1011,7 @@ class TestEventListeners { // // This class is thread-safe as long as the methods are called // according to their specification. -class UnitTest { +class GTEST_API_ UnitTest { public: // Gets the singleton UnitTest object. The first time this method // is called, a UnitTest object is constructed and returned. @@ -1119,36 +1198,34 @@ inline Environment* AddGlobalTestEnvironment(Environment* env) { // updated. // // Calling the function for the second time has no user-visible effect. -void InitGoogleTest(int* argc, char** argv); +GTEST_API_ void InitGoogleTest(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. -void InitGoogleTest(int* argc, wchar_t** argv); +GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { // These overloaded versions handle ::std::string and ::std::wstring. -#if GTEST_HAS_STD_STRING -inline String FormatForFailureMessage(const ::std::string& str) { +GTEST_API_ inline String FormatForFailureMessage(const ::std::string& str) { return (Message() << '"' << str << '"').GetString(); } -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_STD_WSTRING -inline String FormatForFailureMessage(const ::std::wstring& wstr) { +GTEST_API_ inline String FormatForFailureMessage(const ::std::wstring& wstr) { return (Message() << "L\"" << wstr << '"').GetString(); } #endif // GTEST_HAS_STD_WSTRING // These overloaded versions handle ::string and ::wstring. #if GTEST_HAS_GLOBAL_STRING -inline String FormatForFailureMessage(const ::string& str) { +GTEST_API_ inline String FormatForFailureMessage(const ::string& str) { return (Message() << '"' << str << '"').GetString(); } #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING -inline String FormatForFailureMessage(const ::wstring& wstr) { +GTEST_API_ inline String FormatForFailureMessage(const ::wstring& wstr) { return (Message() << "L\"" << wstr << '"').GetString(); } #endif // GTEST_HAS_GLOBAL_WSTRING @@ -1201,10 +1278,10 @@ AssertionResult CmpHelperEQ(const char* expected_expression, // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual); +GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual); // The helper class for {ASSERT|EXPECT}_EQ. The template argument // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() @@ -1293,72 +1370,72 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ return AssertionFailure(msg);\ }\ }\ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - BiggestInt val1, BiggestInt val2); +GTEST_API_ AssertionResult CmpHelper##op_name(\ + const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // Implements the helper function for {ASSERT|EXPECT}_NE -GTEST_IMPL_CMP_HELPER_(NE, !=) +GTEST_IMPL_CMP_HELPER_(NE, !=); // Implements the helper function for {ASSERT|EXPECT}_LE -GTEST_IMPL_CMP_HELPER_(LE, <=) +GTEST_IMPL_CMP_HELPER_(LE, <=); // Implements the helper function for {ASSERT|EXPECT}_LT -GTEST_IMPL_CMP_HELPER_(LT, < ) +GTEST_IMPL_CMP_HELPER_(LT, < ); // Implements the helper function for {ASSERT|EXPECT}_GE -GTEST_IMPL_CMP_HELPER_(GE, >=) +GTEST_IMPL_CMP_HELPER_(GE, >=); // Implements the helper function for {ASSERT|EXPECT}_GT -GTEST_IMPL_CMP_HELPER_(GT, > ) +GTEST_IMPL_CMP_HELPER_(GT, > ); #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); +GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual); +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const wchar_t* expected, + const wchar_t* actual); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); } // namespace internal @@ -1370,32 +1447,30 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. -AssertionResult IsSubstring( +GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); -AssertionResult IsSubstring( +GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); -AssertionResult IsNotSubstring( +GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); -AssertionResult IsNotSubstring( +GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); -#if GTEST_HAS_STD_STRING -AssertionResult IsSubstring( +GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); -AssertionResult IsNotSubstring( +GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( +GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); -AssertionResult IsNotSubstring( +GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING @@ -1438,16 +1513,16 @@ AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, // Helper function for implementing ASSERT_NEAR. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error); +GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // A class that enables one to stream messages to assertion macros -class AssertHelper { +class GTEST_API_ AssertHelper { public: // Constructor. AssertHelper(TestPartResult::Type type, @@ -1576,10 +1651,22 @@ const T* TestWithParam<T>::parameter_ = NULL; #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") // Generates a fatal failure with a generic message. -#define FAIL() GTEST_FATAL_FAILURE_("Failed") +#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") + +// Define this macro to 1 to omit the definition of FAIL(), which is a +// generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_FAIL +#define FAIL() GTEST_FAIL() +#endif // Generates a success with a generic message. -#define SUCCEED() GTEST_SUCCESS_("Succeeded") +#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") + +// Define this macro to 1 to omit the definition of SUCCEED(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_SUCCEED +#define SUCCEED() GTEST_SUCCEED() +#endif // Macros for testing exceptions. // @@ -1603,7 +1690,9 @@ const T* TestWithParam<T>::parameter_ = NULL; #define ASSERT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) -// Boolean assertions. +// Boolean assertions. Condition can be either a Boolean expression or an +// AssertionResult. For more information on how to use AssertionResult with +// these macros see comments on that class. #define EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_NONFATAL_FAILURE_) @@ -1776,10 +1865,10 @@ const T* TestWithParam<T>::parameter_ = NULL; // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2); -AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2); +GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2); +GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2); #if GTEST_OS_WINDOWS @@ -1909,10 +1998,15 @@ bool StaticAssertTypeEq() { // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. -#define TEST(test_case_name, test_name)\ +#define GTEST_TEST(test_case_name, test_name)\ GTEST_TEST_(test_case_name, test_name, \ ::testing::Test, ::testing::internal::GetTestTypeId()) +// Define this macro to 1 to omit the definition of TEST(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_TEST +#define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#endif // Defines a test that uses a test fixture. // diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h b/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h index 5aba1a0d68..e4330848d4 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -64,7 +64,7 @@ const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; // by wait(2) // exit code: The integer code passed to exit(3), _exit(2), or // returned from main() -class DeathTest { +class GTEST_API_ DeathTest { public: // Create returns false if there was an error determining the // appropriate action to take for the current death test; for example, @@ -147,7 +147,7 @@ class DefaultDeathTestFactory : public DeathTestFactory { // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. -bool ExitedUnsuccessfully(int exit_status); +GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. @@ -189,11 +189,12 @@ bool ExitedUnsuccessfully(int exit_status); // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: - InternalRunDeathTestFlag(const String& file, - int line, - int index, - int write_fd) - : file_(file), line_(line), index_(index), write_fd_(write_fd) {} + InternalRunDeathTestFlag(const String& a_file, + int a_line, + int an_index, + int a_write_fd) + : file_(a_file), line_(a_line), index_(an_index), + write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { if (write_fd_ >= 0) diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h b/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h index 1b2f586937..4b76d79506 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h @@ -56,7 +56,7 @@ namespace internal { // Names are NOT checked for syntax correctness -- no checking for illegal // characters, malformed paths, etc. -class FilePath { +class GTEST_API_ FilePath { public: FilePath() : pathname_("") { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } @@ -189,9 +189,18 @@ class FilePath { // particular, RemoveTrailingPathSeparator() only removes one separator, and // it is called in CreateDirectoriesRecursively() assuming that it will change // a pathname from directory syntax (trailing separator) to filename syntax. + // + // On Windows this method also replaces the alternate path separator '/' with + // the primary path separator '\\', so that for example "bar\\/\\foo" becomes + // "bar\\foo". void Normalize(); + // Returns a pointer to the last occurence of a valid path separator in + // the FilePath. On Windows, for example, both '/' and '\' are valid path + // separators. Returns NULL if no path separator was found. + const char* FindLastPathSeparator() const; + String pathname_; }; // class FilePath diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-internal-inl.h b/utils/unittest/googletest/include/gtest/internal/gtest-internal-inl.h index 47aec22d16..855b21554a 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-internal-inl.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-internal-inl.h @@ -52,7 +52,9 @@ #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <string.h> // For memmove. +#include <algorithm> #include <string> +#include <vector> #include <gtest/internal/gtest-port.h> @@ -60,7 +62,7 @@ #include <windows.h> // For DWORD. #endif // GTEST_OS_WINDOWS -#include <gtest/gtest.h> +#include <gtest/gtest.h> // NOLINT #include <gtest/gtest-spi.h> namespace testing { @@ -76,7 +78,7 @@ namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). -extern const TypeId kTestTypeIdInGoogleTest; +GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; @@ -90,13 +92,31 @@ const char kPrintTimeFlag[] = "print_time"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; +const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kThrowOnFailureFlag[] = "throw_on_failure"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +GTEST_API_ extern bool g_help_flag; + // Returns the current time in milliseconds. -TimeInMillis GetTimeInMillis(); +GTEST_API_ TimeInMillis GetTimeInMillis(); + +// Returns true iff Google Test should use colors in the output. +GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); + +// Formats the given time in milliseconds as seconds. +GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +GTEST_API_ bool ParseInt32Flag( + const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. @@ -144,6 +164,7 @@ class GTestFlagSaver { random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); + stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } @@ -163,6 +184,7 @@ class GTestFlagSaver { GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; + GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: @@ -182,6 +204,7 @@ class GTestFlagSaver { internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; + internal::Int32 stack_trace_depth_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; @@ -193,7 +216,7 @@ class GTestFlagSaver { // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output // as '(Invalid Unicode 0xXXXXXXXX)'. -char* CodePointToUtf8(UInt32 code_point, char* str); +GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: @@ -208,10 +231,7 @@ char* CodePointToUtf8(UInt32 code_point, char* str); // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. -String WideStringToUtf8(const wchar_t* str, int num_chars); - -// Returns the number of active threads, or 0 when there is an error. -size_t GetThreadCount(); +GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); // 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 @@ -225,269 +245,78 @@ void WriteToShardStatusFileIfNeeded(); // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_str, const char* shard_index_str, - bool in_subprocess_for_death_test); +GTEST_API_ bool ShouldShard(const char* total_shards_str, + const char* shard_index_str, + bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. -Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); +GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. -bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id); - -// Vector is an ordered container that supports random access to the -// elements. -// -// We cannot use std::vector, as Visual C++ 7.1's implementation of -// STL has problems compiling when exceptions are disabled. There is -// a hack to work around the problems, but we've seen cases where the -// hack fails to work. -// -// The element type must support copy constructor and operator=. -template <typename E> // E is the element type. -class Vector { - public: - // Creates an empty Vector. - Vector() : elements_(NULL), capacity_(0), size_(0) {} - - // D'tor. - virtual ~Vector() { Clear(); } - - // Clears the Vector. - void Clear() { - if (elements_ != NULL) { - for (int i = 0; i < size_; i++) { - delete elements_[i]; - } - - free(elements_); - elements_ = NULL; - capacity_ = size_ = 0; - } - } - - // Gets the number of elements. - int size() const { return size_; } - - // Adds an element to the end of the Vector. A copy of the element - // is created using the copy constructor, and then stored in the - // Vector. Changes made to the element in the Vector doesn't affect - // the source object, and vice versa. - void PushBack(const E& element) { Insert(element, size_); } - - // Adds an element to the beginning of this Vector. - void PushFront(const E& element) { Insert(element, 0); } - - // Removes an element from the beginning of this Vector. If the - // result argument is not NULL, the removed element is stored in the - // memory it points to. Otherwise the element is thrown away. - // Returns true iff the vector wasn't empty before the operation. - bool PopFront(E* result) { - if (size_ == 0) - return false; - - if (result != NULL) - *result = GetElement(0); - - Erase(0); - return true; - } - - // Inserts an element at the given index. It's the caller's - // responsibility to ensure that the given index is in the range [0, - // size()]. - void Insert(const E& element, int index) { - GrowIfNeeded(); - MoveElements(index, size_ - index, index + 1); - elements_[index] = new E(element); - size_++; - } - - // Erases the element at the specified index, or aborts the program if the - // index is not in range [0, size()). - void Erase(int index) { - GTEST_CHECK_(0 <= index && index < size_) - << "Invalid Vector index " << index << ": must be in range [0, " - << (size_ - 1) << "]."; - - delete elements_[index]; - MoveElements(index + 1, size_ - index - 1, index); - size_--; - } - - // Returns the number of elements that satisfy a given predicate. - // The parameter 'predicate' is a Boolean function or functor that - // accepts a 'const E &', where E is the element type. - template <typename P> // P is the type of the predicate function/functor - int CountIf(P predicate) const { - int count = 0; - for (int i = 0; i < size_; i++) { - if (predicate(*(elements_[i]))) { - count++; - } - } - - return count; - } - - // Applies a function/functor to each element in the Vector. The - // parameter 'functor' is a function/functor that accepts a 'const - // E &', where E is the element type. This method does not change - // the elements. - template <typename F> // F is the type of the function/functor - void ForEach(F functor) const { - for (int i = 0; i < size_; i++) { - functor(*(elements_[i])); - } - } - - // Returns the first node whose element satisfies a given predicate, - // or NULL if none is found. The parameter 'predicate' is a - // function/functor that accepts a 'const E &', where E is the - // element type. This method does not change the elements. - template <typename P> // P is the type of the predicate function/functor. - const E* FindIf(P predicate) const { - for (int i = 0; i < size_; i++) { - if (predicate(*elements_[i])) { - return elements_[i]; - } - } - return NULL; - } - - template <typename P> - E* FindIf(P predicate) { - for (int i = 0; i < size_; i++) { - if (predicate(*elements_[i])) { - return elements_[i]; - } - } - return NULL; - } - - // Returns the i-th element of the Vector, or aborts the program if i - // is not in range [0, size()). - const E& GetElement(int i) const { - GTEST_CHECK_(0 <= i && i < size_) - << "Invalid Vector index " << i << ": must be in range [0, " - << (size_ - 1) << "]."; - - return *(elements_[i]); - } - - // Returns a mutable reference to the i-th element of the Vector, or - // aborts the program if i is not in range [0, size()). - E& GetMutableElement(int i) { - GTEST_CHECK_(0 <= i && i < size_) - << "Invalid Vector index " << i << ": must be in range [0, " - << (size_ - 1) << "]."; +GTEST_API_ bool ShouldRunTestOnShard( + int total_shards, int shard_index, int test_id); - return *(elements_[i]); - } - - // Returns the i-th element of the Vector, or default_value if i is not - // in range [0, size()). - E GetElementOr(int i, E default_value) const { - return (i < 0 || i >= size_) ? default_value : *(elements_[i]); - } - - // Swaps the i-th and j-th elements of the Vector. Crashes if i or - // j is invalid. - void Swap(int i, int j) { - GTEST_CHECK_(0 <= i && i < size_) - << "Invalid first swap element " << i << ": must be in range [0, " - << (size_ - 1) << "]."; - GTEST_CHECK_(0 <= j && j < size_) - << "Invalid second swap element " << j << ": must be in range [0, " - << (size_ - 1) << "]."; - - E* const temp = elements_[i]; - elements_[i] = elements_[j]; - elements_[j] = temp; - } - - // Performs an in-place shuffle of a range of this Vector's nodes. - // 'begin' and 'end' are element indices as an STL-style range; - // i.e. [begin, end) are shuffled, where 'end' == size() means to - // shuffle to the end of the Vector. - void ShuffleRange(internal::Random* random, int begin, int end) { - GTEST_CHECK_(0 <= begin && begin <= size_) - << "Invalid shuffle range start " << begin << ": must be in range [0, " - << size_ << "]."; - GTEST_CHECK_(begin <= end && end <= size_) - << "Invalid shuffle range finish " << end << ": must be in range [" - << begin << ", " << size_ << "]."; - - // Fisher-Yates shuffle, from - // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle - for (int range_width = end - begin; range_width >= 2; range_width--) { - const int last_in_range = begin + range_width - 1; - const int selected = begin + random->Generate(range_width); - Swap(selected, last_in_range); - } - } +// STL container utilities. - // Performs an in-place shuffle of this Vector's nodes. - void Shuffle(internal::Random* random) { - ShuffleRange(random, 0, size()); - } - - // Returns a copy of this Vector. - Vector* Clone() const { - Vector* const clone = new Vector; - clone->Reserve(size_); - for (int i = 0; i < size_; i++) { - clone->PushBack(GetElement(i)); - } - return clone; - } +// Returns the number of elements in the given container that satisfy +// the given predicate. +template <class Container, typename Predicate> +inline int CountIf(const Container& c, Predicate predicate) { + return static_cast<int>(std::count_if(c.begin(), c.end(), predicate)); +} - private: - // Makes sure this Vector's capacity is at least the given value. - void Reserve(int new_capacity) { - if (new_capacity <= capacity_) - return; - - capacity_ = new_capacity; - elements_ = static_cast<E**>( - realloc(elements_, capacity_*sizeof(elements_[0]))); - } +// Applies a function/functor to each element in the container. +template <class Container, typename Functor> +void ForEach(const Container& c, Functor functor) { + std::for_each(c.begin(), c.end(), functor); +} - // Grows the buffer if it is not big enough to hold one more element. - void GrowIfNeeded() { - if (size_ < capacity_) - return; - - // Exponential bump-up is necessary to ensure that inserting N - // elements is O(N) instead of O(N^2). The factor 3/2 means that - // no more than 1/3 of the slots are wasted. - const int new_capacity = 3*(capacity_/2 + 1); - GTEST_CHECK_(new_capacity > capacity_) // Does the new capacity overflow? - << "Cannot grow a Vector with " << capacity_ << " elements already."; - Reserve(new_capacity); - } +// Returns the i-th element of the vector, or default_value if i is not +// in range [0, v.size()). +template <typename E> +inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { + return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; +} - // Moves the give consecutive elements to a new index in the Vector. - void MoveElements(int source, int count, int dest) { - memmove(elements_ + dest, elements_ + source, count*sizeof(elements_[0])); +// Performs an in-place shuffle of a range of the vector's elements. +// 'begin' and 'end' are element indices as an STL-style range; +// i.e. [begin, end) are shuffled, where 'end' == size() means to +// shuffle to the end of the vector. +template <typename E> +void ShuffleRange(internal::Random* random, int begin, int end, + std::vector<E>* v) { + const int size = static_cast<int>(v->size()); + GTEST_CHECK_(0 <= begin && begin <= size) + << "Invalid shuffle range start " << begin << ": must be in range [0, " + << size << "]."; + GTEST_CHECK_(begin <= end && end <= size) + << "Invalid shuffle range finish " << end << ": must be in range [" + << begin << ", " << size << "]."; + + // Fisher-Yates shuffle, from + // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + for (int range_width = end - begin; range_width >= 2; range_width--) { + const int last_in_range = begin + range_width - 1; + const int selected = begin + random->Generate(range_width); + std::swap((*v)[selected], (*v)[last_in_range]); } +} - E** elements_; - int capacity_; // The number of elements allocated for elements_. - int size_; // The number of elements; in the range [0, capacity_]. - - // We disallow copying Vector. - GTEST_DISALLOW_COPY_AND_ASSIGN_(Vector); -}; // class Vector +// Performs an in-place shuffle of the vector's elements. +template <typename E> +inline void Shuffle(internal::Random* random, std::vector<E>* v) { + ShuffleRange(random, 0, static_cast<int>(v->size()), v); +} // A function for deleting an object. Handy for being used as a // functor. template <typename T> -static void Delete(T * x) { +static void Delete(T* x) { delete x; } @@ -600,7 +429,7 @@ class TestInfoImpl { // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. -class UnitTestOptions { +class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. @@ -642,7 +471,7 @@ class UnitTestOptions { // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. -FilePath GetCurrentExecutableName(); +GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { @@ -733,7 +562,7 @@ class DefaultPerThreadTestPartResultReporter // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. -class UnitTestImpl { +class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); @@ -802,15 +631,15 @@ class UnitTestImpl { // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const { - const int index = test_case_indices_.GetElementOr(i, -1); - return index < 0 ? NULL : test_cases_.GetElement(i); + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[i]; } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i) { - const int index = test_case_indices_.GetElementOr(i, -1); - return index < 0 ? NULL : test_cases_.GetElement(index); + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[index]; } // Provides access to the event listener list. @@ -898,15 +727,15 @@ class UnitTestImpl { #endif // GTEST_HAS_PARAM_TEST // Sets the TestCase object for the test that's currently running. - void set_current_test_case(TestCase* current_test_case) { - current_test_case_ = current_test_case; + void set_current_test_case(TestCase* a_current_test_case) { + current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. - void set_current_test_info(TestInfo* current_test_info) { - current_test_info_ = current_test_info; + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and @@ -927,7 +756,7 @@ class UnitTestImpl { // Clears the results of all tests, including the ad hoc test. void ClearResult() { - test_cases_.ForEach(TestCase::ClearTestCaseResult); + ForEach(test_cases_, TestCase::ClearTestCaseResult); ad_hoc_test_result_.Clear(); } @@ -953,17 +782,14 @@ class UnitTestImpl { // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. - internal::Vector<Environment*>* environments() { return &environments_; } - internal::Vector<Environment*>* environments_in_reverse_order() { - return &environments_in_reverse_order_; - } + std::vector<Environment*>& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. - internal::Vector<TraceInfo>* gtest_trace_stack() { - return gtest_trace_stack_.pointer(); + std::vector<TraceInfo>& gtest_trace_stack() { + return *(gtest_trace_stack_.pointer()); } - const internal::Vector<TraceInfo>* gtest_trace_stack() const { - return gtest_trace_stack_.pointer(); + const std::vector<TraceInfo>& gtest_trace_stack() const { + return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST @@ -1038,20 +864,18 @@ class UnitTestImpl { per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down - // before/after the tests are run. environments_in_reverse_order_ - // simply mirrors environments_ in reverse order. - internal::Vector<Environment*> environments_; - internal::Vector<Environment*> environments_in_reverse_order_; + // before/after the tests are run. + std::vector<Environment*> environments_; // The vector of TestCases in their original order. It owns the // elements in the vector. - internal::Vector<TestCase*> test_cases_; + std::vector<TestCase*> test_cases_; // Provides a level of indirection for the test case list to allow // easy shuffling and restoring the test case order. The i-th // element of this vector is the index of the i-th test case in the // shuffled order. - internal::Vector<int> test_case_indices_; + std::vector<int> test_case_indices_; #if GTEST_HAS_PARAM_TEST // ParameterizedTestRegistry object used to register value-parameterized @@ -1117,7 +941,7 @@ class UnitTestImpl { #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. - internal::ThreadLocal<internal::Vector<TraceInfo> > gtest_trace_stack_; + internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl @@ -1130,24 +954,24 @@ inline UnitTestImpl* GetUnitTestImpl() { // Internal helper functions for implementing the simple regular // expression matcher. -bool IsInSet(char ch, const char* str); -bool IsDigit(char ch); -bool IsPunct(char ch); -bool IsRepeat(char ch); -bool IsWhiteSpace(char ch); -bool IsWordChar(char ch); -bool IsValidEscape(char ch); -bool AtomMatchesChar(bool escaped, char pattern, char ch); -bool ValidateRegex(const char* regex); -bool MatchRegexAtHead(const char* regex, const char* str); -bool MatchRepetitionAndRegexAtHead( +GTEST_API_ bool IsInSet(char ch, const char* str); +GTEST_API_ bool IsDigit(char ch); +GTEST_API_ bool IsPunct(char ch); +GTEST_API_ bool IsRepeat(char ch); +GTEST_API_ bool IsWhiteSpace(char ch); +GTEST_API_ bool IsWordChar(char ch); +GTEST_API_ bool IsValidEscape(char ch); +GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); +GTEST_API_ bool ValidateRegex(const char* regex); +GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); -bool MatchRegexAnywhere(const char* regex, const char* str); +GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); // Parses the command line for Google Test flags, without initializing // other parts of Google Test. -void ParseGoogleTestFlagsOnly(int* argc, char** argv); -void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST @@ -1224,6 +1048,9 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. +// +// This class is supplied only for the purpose of testing Google Test's own +// constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, @@ -1235,7 +1062,7 @@ class TestResultAccessor { test_result->ClearTestPartResults(); } - static const Vector<testing::TestPartResult>& test_part_results( + static const std::vector<testing::TestPartResult>& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-internal.h b/utils/unittest/googletest/include/gtest/internal/gtest-internal.h index 20c32340d7..0b90132e78 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-internal.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-internal.h @@ -134,14 +134,13 @@ struct TraceInfo; // Information about a trace point. class ScopedTrace; // Implements scoped trace. class TestInfoImpl; // Opaque implementation of TestInfo class UnitTestImpl; // Opaque implementation of UnitTest -template <typename E> class Vector; // A generic vector. // How many times InitGoogleTest() has been called. extern int g_init_gtest_count; // The text used in failure messages to indicate the start of the // stack trace. -extern const char kStackTraceMarker[]; +GTEST_API_ extern const char kStackTraceMarker[]; // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a @@ -168,24 +167,21 @@ char (&IsNullLiteralHelper(...))[2]; // NOLINT // A compile-time bool constant that is true if and only if x is a // null pointer literal (i.e. NULL or any 0-valued compile-time // integral constant). -#ifdef GTEST_ELLIPSIS_NEEDS_COPY_ -// Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler. The Nokia Symbian and the IBM XL C/C++ compiler try to -// instantiate a copy constructor for objects passed through ellipsis -// (...), failing for uncopyable objects. Hence we define this to -// false (and lose support for NULL detection). +#ifdef GTEST_ELLIPSIS_NEEDS_POD_ +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). #define GTEST_IS_NULL_LITERAL_(x) false #else #define GTEST_IS_NULL_LITERAL_(x) \ (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) -#endif // GTEST_ELLIPSIS_NEEDS_COPY_ +#endif // GTEST_ELLIPSIS_NEEDS_POD_ // Appends the user-supplied message to the Google-Test-generated message. -String AppendUserMessage(const String& gtest_msg, - const Message& user_msg); +GTEST_API_ String AppendUserMessage(const String& gtest_msg, + const Message& user_msg); // A helper class for creating scoped traces in user programs. -class ScopedTrace { +class GTEST_API_ ScopedTrace { public: // The c'tor pushes the given source file location and message onto // a trace stack maintained by Google Test. @@ -264,8 +260,8 @@ inline String FormatForFailureMessage(T* pointer) { #endif // GTEST_NEEDS_IS_POINTER_ // These overloaded versions handle narrow and wide characters. -String FormatForFailureMessage(char ch); -String FormatForFailureMessage(wchar_t wchar); +GTEST_API_ String FormatForFailureMessage(char ch); +GTEST_API_ String FormatForFailureMessage(wchar_t wchar); // When this operand is a const char* or char*, and the other operand // is a ::std::string or ::string, we print this operand as a C string @@ -282,9 +278,7 @@ inline String FormatForComparisonFailureMessage(\ return operand1_printer(str);\ } -#if GTEST_HAS_STD_STRING GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_STD_WSTRING GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) #endif // GTEST_HAS_STD_WSTRING @@ -313,12 +307,18 @@ GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. -AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const String& expected_value, - const String& actual_value, - bool ignoring_case); - +GTEST_API_ AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const String& expected_value, + const String& actual_value, + bool ignoring_case); + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +GTEST_API_ String GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the @@ -538,7 +538,7 @@ TypeId GetTypeId() { // ::testing::Test, as the latter may give the wrong result due to a // suspected linker bug when compiling Google Test as a Mac OS X // framework. -TypeId GetTestTypeId(); +GTEST_API_ TypeId GetTestTypeId(); // Defines the abstract factory interface that creates instances // of a Test object. @@ -571,8 +571,10 @@ class TestFactoryImpl : public TestFactoryBase { // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} // We pass a long instead of HRESULT to avoid causing an // include dependency for the HRESULT type. -AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT -AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT +GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, + long hr); // NOLINT +GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, + long hr); // NOLINT #endif // GTEST_OS_WINDOWS @@ -611,7 +613,7 @@ typedef void (*TearDownTestCaseFunc)(); // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. -TestInfo* MakeAndRegisterTestInfo( +GTEST_API_ TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* test_case_comment, const char* comment, TypeId fixture_class_id, @@ -619,10 +621,15 @@ TestInfo* MakeAndRegisterTestInfo( TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory); +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +bool SkipPrefix(const char* prefix, const char** pstr); + #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // State of the definition of a type-parameterized test case. -class TypedTestCasePState { +class GTEST_API_ TypedTestCasePState { public: TypedTestCasePState() : registered_(false) {} @@ -763,13 +770,14 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count); +GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, + int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. // Always returns true. -bool AlwaysTrue(); +GTEST_API_ bool AlwaysTrue(); // Always returns false. inline bool AlwaysFalse() { return !AlwaysTrue(); } @@ -779,7 +787,7 @@ inline bool AlwaysFalse() { return !AlwaysTrue(); } // doesn't use global state (and therefore can't interfere with user // code). Unlike rand_r(), it's portable. An LCG isn't very random, // but it's good enough for our purposes. -class Random { +class GTEST_API_ Random { public: static const UInt32 kMaxRange = 1u << 31; @@ -878,12 +886,17 @@ class Random { fail(gtest_msg) -#define GTEST_TEST_BOOLEAN_(boolexpr, booltext, actual, expected, fail) \ +// Implements Boolean test assertions such as EXPECT_TRUE. expression can be +// either a boolean expression or an AssertionResult. text is a textual +// represenation of expression as it was passed into the EXPECT_TRUE. +#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(boolexpr)) \ + if (const ::testing::AssertionResult gtest_ar_ = \ + ::testing::AssertionResult(expression)) \ ; \ else \ - fail("Value of: " booltext "\n Actual: " #actual "\nExpected: " #expected) + fail(::testing::internal::GetBoolAssertionFailureMessage(\ + gtest_ar_, text, #actual, #expected).c_str()) #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h b/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h index d4c7a39b0e..2404ea8824 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -77,7 +77,7 @@ namespace testing { namespace internal { // Protects copying of all linked_ptr objects. -extern Mutex g_linked_ptr_mutex; +GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); // This is used internally by all instances of linked_ptr<>. It needs to be // a non-template class because different types of linked_ptr<> can refer to diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h b/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h index 1358c329f4..ab4ab56625 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h @@ -44,13 +44,30 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include <gtest/internal/gtest-param-util.h> #include <gtest/internal/gtest-port.h> #if GTEST_HAS_PARAM_TEST -#include <gtest/internal/gtest-param-util.h> - namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template <typename ForwardIterator> +internal::ParamGenerator< + typename ::std::iterator_traits<ForwardIterator>::value_type> ValuesIn( + ForwardIterator begin, ForwardIterator end); + +template <typename T, size_t N> +internal::ParamGenerator<T> ValuesIn(const T (&array)[N]); + +template <class Container> +internal::ParamGenerator<typename Container::value_type> ValuesIn( + const Container& container); + namespace internal { // Used in the Values() function to provide polymorphic capabilities. diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h b/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h index dcc5494745..0cbb58c21b 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h @@ -38,17 +38,15 @@ #include <utility> #include <vector> +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include <gtest/internal/gtest-internal.h> +#include <gtest/internal/gtest-linked_ptr.h> #include <gtest/internal/gtest-port.h> #if GTEST_HAS_PARAM_TEST -#if GTEST_HAS_RTTI -#include <typeinfo> -#endif // GTEST_HAS_RTTI - -#include <gtest/internal/gtest-linked_ptr.h> -#include <gtest/internal/gtest-internal.h> - namespace testing { namespace internal { @@ -58,26 +56,8 @@ namespace internal { // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. -void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line); - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Downcasts the pointer of type Base to Derived. -// Derived must be a subclass of Base. The parameter MUST -// point to a class of type Derived, not any subclass of it. -// When RTTI is available, the function performs a runtime -// check to enforce this. -template <class Derived, class Base> -Derived* CheckedDowncastToActualType(Base* base) { -#if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); - Derived* derived = dynamic_cast<Derived*>(base); // NOLINT -#else - Derived* derived = static_cast<Derived*>(base); // Poor man's downcast. -#endif // GTEST_HAS_RTTI - return derived; -} +GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, + const char* file, int line); template <typename> class ParamGeneratorInterface; template <typename> class ParamGenerator; @@ -169,7 +149,7 @@ class ParamGeneratorInterface { virtual ParamIteratorInterface<T>* End() const = 0; }; -// Wraps ParamGeneratorInetrface<T> and provides general generator syntax +// Wraps ParamGeneratorInterface<T> and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface<T> instance is shared among all copies @@ -245,7 +225,8 @@ class RangeGenerator : public ParamGeneratorInterface<T> { private: Iterator(const Iterator& other) - : base_(other.base_), value_(other.value_), index_(other.index_), + : ParamIteratorInterface<T>(), + base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. @@ -542,12 +523,12 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { - TestInfo(const char* test_case_base_name, - const char* test_base_name, - TestMetaFactoryBase<ParamType>* test_meta_factory) : - test_case_base_name(test_case_base_name), - test_base_name(test_base_name), - test_meta_factory(test_meta_factory) {} + TestInfo(const char* a_test_case_base_name, + const char* a_test_base_name, + TestMetaFactoryBase<ParamType>* a_test_meta_factory) : + test_case_base_name(a_test_case_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} const String test_case_base_name; const String test_base_name; diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-port.h b/utils/unittest/googletest/include/gtest/internal/gtest-port.h index e346cde848..cc5637d2fe 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-port.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-port.h @@ -42,6 +42,8 @@ // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. +// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions +// are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::string, which is different to std::string). @@ -52,9 +54,6 @@ // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. -// GTEST_HAS_STD_STRING - Define it to 1/0 to indicate that -// std::string does/doesn't work (Google Test can -// be used where std::string is unavailable). // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). @@ -67,11 +66,19 @@ // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. +// GTEST_LINKED_AS_SHARED_LIBRARY +// - Define to 1 when compiling tests that use +// Google Test as a shared library (known as +// DLL on Windows). +// GTEST_CREATE_SHARED_LIBRARY +// - Define to 1 when compiling Google Test itself +// as a shared library. // This header defines the following utilities: // // Macros indicating the current platform (defined to 1 if compiled on // the given platform; otherwise undefined): +// GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_LINUX - Linux // GTEST_OS_MAC - Mac OS X @@ -80,7 +87,7 @@ // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW -// GTEST_OS_WINODWS_MOBILE - Windows Mobile +// GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the @@ -103,11 +110,13 @@ // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. +// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. +// GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // @@ -134,7 +143,10 @@ // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // -// Stderr capturing: +// Stdout and stderr capturing: +// CaptureStdout() - starts capturing stdout. +// GetCapturedStdout() - stops capturing stdout and returns the captured +// string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. @@ -166,9 +178,12 @@ #endif // !_WIN32_WCE #include <iostream> // NOLINT +#include <sstream> // NOLINT +#include <string> // NOLINT #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" #define GTEST_FLAG_PREFIX_ "gtest_" +#define GTEST_FLAG_PREFIX_DASH_ "gtest-" #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" #define GTEST_NAME_ "Google Test" #define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" @@ -202,12 +217,14 @@ #define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) #define GTEST_OS_SOLARIS 1 +#elif defined(_AIX) +#define GTEST_OS_AIX 1 #elif defined(__HAIKU__) #define GTEST_OS_HAIKU #endif // __CYGWIN__ #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_SYMBIAN || \ - GTEST_OS_SOLARIS + GTEST_OS_SOLARIS || GTEST_OS_AIX // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already @@ -216,6 +233,7 @@ #include <regex.h> // NOLINT #include <strings.h> // NOLINT #include <sys/types.h> // NOLINT +#include <time.h> // NOLINT #include <unistd.h> // NOLINT #define GTEST_USES_POSIX_RE 1 @@ -238,11 +256,11 @@ #define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || - // GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS - -// Defines GTEST_HAS_EXCEPTIONS to 1 if exceptions are enabled, or 0 -// otherwise. + // GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS || GTEST_OS_AIX +#ifndef GTEST_HAS_EXCEPTIONS +// The user didn't tell us whether exceptions are enabled, so we need +// to figure it out. #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. @@ -251,30 +269,32 @@ #define _HAS_EXCEPTIONS 1 #endif // _HAS_EXCEPTIONS #define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -#else // The compiler is not MSVC or C++Builder. -// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. For -// other compilers, we assume exceptions are disabled to be -// conservative. -#if defined(__GNUC__) && __EXCEPTIONS +#elif defined(__GNUC__) && __EXCEPTIONS +// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__SUNPRO_CC) +// Sun Pro CC supports exceptions. However, there is no compile-time way of +// detecting whether they are enabled or not. Therefore, we assume that +// they are enabled unless the user tells us otherwise. +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__IBMCPP__) && __EXCEPTIONS +// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #else +// For other compilers, we assume exceptions are disabled to be +// conservative. #define GTEST_HAS_EXCEPTIONS 0 -#endif // defined(__GNUC__) && __EXCEPTIONS #endif // defined(_MSC_VER) || defined(__BORLANDC__) +#endif // GTEST_HAS_EXCEPTIONS -// Determines whether ::std::string and ::string are available. - -#ifndef GTEST_HAS_STD_STRING -// The user didn't tell us whether ::std::string is available, so we -// need to figure it out. The only environment that we know -// ::std::string is not available is MSVC 7.1 or lower with exceptions -// disabled. -#if defined(_MSC_VER) && (_MSC_VER < 1400) && !GTEST_HAS_EXCEPTIONS -#define GTEST_HAS_STD_STRING 0 -#else +#if !defined(GTEST_HAS_STD_STRING) +// Even though we don't use this macro any longer, we keep it in case +// some clients still depend on it. #define GTEST_HAS_STD_STRING 1 -#endif -#endif // GTEST_HAS_STD_STRING +#elif !GTEST_HAS_STD_STRING +// The user told us that ::std::string isn't available. +#error "Google Test cannot be used where ::std::string isn't available." +#endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING // The user didn't tell us whether ::string is available, so we need @@ -290,15 +310,11 @@ // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring // is available. -#if GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || GTEST_OS_HAIKU || defined(_MINIX) // Cygwin 1.5 and below doesn't support ::std::wstring. // Cygwin 1.7 might add wstring support; this should be updated when clear. // Solaris' libc++ doesn't support it either. // Minix currently doesn't support it either. -#define GTEST_HAS_STD_WSTRING 0 -#else -#define GTEST_HAS_STD_WSTRING GTEST_HAS_STD_STRING -#endif // GTEST_OS_CYGWIN || GTEST_OS_SOLARIS +#define GTEST_HAS_STD_WSTRING (!(GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || GTEST_OS_HAIKU || defined(_MINIX))) #endif // GTEST_HAS_STD_WSTRING @@ -309,18 +325,6 @@ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING -#if GTEST_HAS_STD_STRING || GTEST_HAS_GLOBAL_STRING || \ - GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING -#include <string> // NOLINT -#endif // GTEST_HAS_STD_STRING || GTEST_HAS_GLOBAL_STRING || - // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_STRING -#include <sstream> // NOLINT -#else -#include <strstream> // NOLINT -#endif // GTEST_HAS_STD_STRING - // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to @@ -332,34 +336,49 @@ #define GTEST_HAS_RTTI 1 #else #define GTEST_HAS_RTTI 0 -#endif // _CPPRTTI - -#elif defined(__GNUC__) +#endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. -#if GTEST_GCC_VER_ >= 40302 +#elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) + #ifdef __GXX_RTTI #define GTEST_HAS_RTTI 1 #else #define GTEST_HAS_RTTI 0 #endif // __GXX_RTTI -#else -// For gcc versions smaller than 4.3.2, we assume RTTI is enabled. + +// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if +// both the typeid and dynamic_cast features are present. +#elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) + +#ifdef __RTTI_ALL__ #define GTEST_HAS_RTTI 1 -#endif // GTEST_GCC_VER >= 40302 +#else +#define GTEST_HAS_RTTI 0 +#endif #else -// Unknown compiler - assume RTTI is enabled. +// For all other compilers, we assume RTTI is enabled. #define GTEST_HAS_RTTI 1 #endif // _MSC_VER #endif // GTEST_HAS_RTTI -// Determines whether <pthread.h> is available. +// It's this header's responsibility to #include <typeinfo> when RTTI +// is enabled. +#if GTEST_HAS_RTTI +#include <typeinfo> +#endif + +// Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD -// The user didn't tell us, so we need to figure it out. +// The user didn't tell us explicitly, so we assume pthreads support is +// available on Linux and Mac. +// +// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 +// to your compiler flags. #define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC) #endif // GTEST_HAS_PTHREAD @@ -376,17 +395,19 @@ #ifndef GTEST_USE_OWN_TR1_TUPLE // The user didn't tell us, so we need to figure it out. -// We use our own tr1 tuple if we aren't sure the user has an -// implementation of it already. At this time, GCC 4.0.0+ is the only -// mainstream compiler that comes with a TR1 tuple implementation. -// MSVC 2008 (9.0) provides TR1 tuple in a 323 MB Feature Pack -// download, which we cannot assume the user has. MSVC 2010 isn't -// released yet. -#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +// We use our own TR1 tuple if we aren't sure the user has an +// implementation of it already. At this time, GCC 4.0.0+ and MSVC +// 2010 are the only mainstream compilers that come with a TR1 tuple +// implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by +// defining __GNUC__ and friends, but cannot compile GCC's tuple +// implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB +// Feature Pack download, which we cannot assume the user has. +#if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \ + || _MSC_VER >= 1600 #define GTEST_USE_OWN_TR1_TUPLE 0 #else #define GTEST_USE_OWN_TR1_TUPLE 1 -#endif // defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +#endif #endif // GTEST_USE_OWN_TR1_TUPLE @@ -428,13 +449,13 @@ #undef _TR1_FUNCTIONAL // Allows the user to #include // <tr1/functional> if he chooses to. #else -#include <tr1/tuple> +#include <tr1/tuple> // NOLINT #endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 #else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. -#include <tuple> +#include <tuple> // NOLINT #endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE @@ -454,47 +475,49 @@ #endif // GTEST_HAS_CLONE +// Determines whether to support stream redirection. This is used to test +// output correctness and to implement death tests. +#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#define GTEST_HAS_STREAM_REDIRECTION_ 1 +#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN + // Determines whether to support death tests. -// Google Test does not support death tests for VC 7.1 and earlier for -// these reasons: -// 1. std::vector does not build in VC 7.1 when exceptions are disabled. -// 2. std::string does not build in VC 7.1 when exceptions are disabled -// (this is covered by GTEST_HAS_STD_STRING guard). -// 3. abort() in a VC 7.1 application compiled as GUI in debug config -// pops up a dialog window that cannot be suppressed programmatically. -#if GTEST_HAS_STD_STRING && \ - (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || GTEST_OS_WINDOWS_MINGW) +// Google Test does not support death tests for VC 7.1 and earlier as +// abort() in a VC 7.1 application compiled as GUI in debug config +// pops up a dialog window that cannot be suppressed programmatically. +#if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ + (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ + GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX) #define GTEST_HAS_DEATH_TEST 1 #include <vector> // NOLINT #endif -// Determines whether to support value-parameterized tests. - -#if defined(__GNUC__) || (_MSC_VER >= 1400) -// TODO(vladl@google.com): get the implementation rid of vector and list -// to compile on MSVC 7.1. +// We don't support MSVC 7.1 with exceptions disabled now. Therefore +// all the compilers we care about are adequate for supporting +// value-parameterized tests. #define GTEST_HAS_PARAM_TEST 1 -#endif // defined(__GNUC__) || (_MSC_VER >= 1400) // Determines whether to support type-driven tests. -// Typed tests need <typeinfo> and variadic macros, which gcc and VC -// 8.0+ support. -#if defined(__GNUC__) || (_MSC_VER >= 1400) +// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, +// Sun Pro CC, and IBM Visual Age support. +#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ + defined(__IBMCPP__) #define GTEST_HAS_TYPED_TEST 1 #define GTEST_HAS_TYPED_TEST_P 1 -#endif // defined(__GNUC__) || (_MSC_VER >= 1400) +#endif // Determines whether to support Combine(). This only makes sense when -// value-parameterized tests are enabled. -#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE +// value-parameterized tests are enabled. The implementation doesn't +// work on Sun Studio since it doesn't understand templated conversion +// operators. +#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) #define GTEST_HAS_COMBINE 1 -#endif // GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE +#endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN) + (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Defines some utility macros. @@ -529,11 +552,16 @@ #define GTEST_ATTRIBUTE_UNUSED_ #endif -// A macro to disallow the evil copy constructor and operator= functions +// A macro to disallow operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_ASSIGN_(type)\ + void operator=(type const &) + +// A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ - type(const type &);\ - void operator=(const type &) + type(type const &);\ + GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations @@ -562,6 +590,20 @@ #endif // GTEST_HAS_SEH +#ifdef _MSC_VER + +#if GTEST_LINKED_AS_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllimport) +#elif GTEST_CREATE_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllexport) +#endif + +#endif // _MSC_VER + +#ifndef GTEST_API_ +#define GTEST_API_ +#endif + namespace testing { class Message; @@ -570,19 +612,11 @@ namespace internal { class String; -// std::strstream is deprecated. However, we have to use it on -// Windows as std::stringstream won't compile on Windows when -// exceptions are disabled. We use std::stringstream on other -// platforms to avoid compiler warnings there. -#if GTEST_HAS_STD_STRING typedef ::std::stringstream StrStream; -#else -typedef ::std::strstream StrStream; -#endif // GTEST_HAS_STD_STRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. -bool IsTrue(bool condition); +GTEST_API_ bool IsTrue(bool condition); // Defines scoped_ptr. @@ -591,6 +625,8 @@ bool IsTrue(bool condition); template <typename T> class scoped_ptr { public: + typedef T element_type; + explicit scoped_ptr(T* p = NULL) : ptr_(p) {} ~scoped_ptr() { reset(); } @@ -620,14 +656,16 @@ class scoped_ptr { // Defines RE. -// A simple C++ wrapper for <regex.h>. It uses the POSIX Enxtended +// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // Regular Expression syntax. -class RE { +class GTEST_API_ RE { public: + // A copy constructor is required by the Standard to initialize object + // references from r-values. + RE(const RE& other) { Init(other.pattern()); } + // Constructs an RE from a string. -#if GTEST_HAS_STD_STRING RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT @@ -646,14 +684,12 @@ class RE { // // TODO(wan@google.com): make FullMatch() and PartialMatch() work // when str contains NUL characters. -#if GTEST_HAS_STD_STRING static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { @@ -683,7 +719,7 @@ class RE { const char* full_pattern_; // For FullMatch(); #endif - GTEST_DISALLOW_COPY_AND_ASSIGN_(RE); + GTEST_DISALLOW_ASSIGN_(RE); }; // Defines logging utilities: @@ -702,7 +738,7 @@ enum GTestLogSeverity { // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. -class GTestLog { +class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); @@ -724,12 +760,69 @@ class GTestLog { inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } +// INTERNAL IMPLEMENTATION - DO NOT USE. +// +// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition +// is not satisfied. +// Synopsys: +// GTEST_CHECK_(boolean_condition); +// or +// GTEST_CHECK_(boolean_condition) << "Additional message"; +// +// This checks the condition and if the condition is not satisfied +// it prints message about the condition violation, including the +// condition itself, plus additional message streamed into it, if any, +// and then it aborts the program. It aborts the program irrespective of +// whether it is built in the debug mode or not. +#define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " + +// An all-mode assert to verify that the given POSIX-style function +// call returns 0 (indicating success). Known limitation: this +// doesn't expand to a balanced 'if' statement, so enclose the macro +// in {} if you need to use it as the only statement in an 'if' +// branch. +#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ + << gtest_error + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Downcasts the pointer of type Base to Derived. +// Derived must be a subclass of Base. The parameter MUST +// point to a class of type Derived, not any subclass of it. +// When RTTI is available, the function performs a runtime +// check to enforce this. +template <class Derived, class Base> +Derived* CheckedDowncastToActualType(Base* base) { +#if GTEST_HAS_RTTI + GTEST_CHECK_(typeid(*base) == typeid(Derived)); + return dynamic_cast<Derived*>(base); // NOLINT +#else + return static_cast<Derived*>(base); // Poor man's downcast. +#endif +} + +#if GTEST_HAS_STREAM_REDIRECTION_ + // Defines the stderr capturer: +// CaptureStdout - starts capturing stdout. +// GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. +// +GTEST_API_ void CaptureStdout(); +GTEST_API_ String GetCapturedStdout(); +GTEST_API_ void CaptureStderr(); +GTEST_API_ String GetCapturedStderr(); + +#endif // GTEST_HAS_STREAM_REDIRECTION_ -void CaptureStderr(); -String GetCapturedStderr(); #if GTEST_HAS_DEATH_TEST @@ -743,6 +836,338 @@ const ::std::vector<String>& GetArgvs(); // Defines synchronization primitives. +#if GTEST_HAS_PTHREAD + +// Sleeps for (roughly) n milli-seconds. This function is only for +// testing Google Test's own constructs. Don't use it in user tests, +// either directly or indirectly. +inline void SleepMilliseconds(int n) { + const timespec time = { + 0, // 0 seconds. + n * 1000L * 1000L, // And n ms. + }; + nanosleep(&time, NULL); +} + +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class Notification { + public: + Notification() : notified_(false) {} + + // Notifies all threads created with this notification to start. Must + // be called from the controller thread. + void Notify() { notified_ = true; } + + // Blocks until the controller thread notifies. Must be called from a test + // thread. + void WaitForNotification() { + while(!notified_) { + SleepMilliseconds(10); + } + } + + private: + volatile bool notified_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; + +// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. +// Consequently, it cannot select a correct instantiation of ThreadWithParam +// in order to call its Run(). Introducing ThreadWithParamBase as a +// non-templated base class for ThreadWithParam allows us to bypass this +// problem. +class ThreadWithParamBase { + public: + virtual ~ThreadWithParamBase() {} + virtual void Run() = 0; +}; + +// pthread_create() accepts a pointer to a function type with the C linkage. +// According to the Standard (7.5/1), function types with different linkages +// are different even if they are otherwise identical. Some compilers (for +// example, SunStudio) treat them as different types. Since class methods +// cannot be defined with C-linkage we need to define a free C-function to +// pass into pthread_create(). +extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { + static_cast<ThreadWithParamBase*>(thread)->Run(); + return NULL; +} + +// Helper class for testing Google Test's multi-threading constructs. +// To use it, write: +// +// void ThreadFunc(int param) { /* Do things with param */ } +// Notification thread_can_start; +// ... +// // The thread_can_start parameter is optional; you can supply NULL. +// ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start); +// thread_can_start.Notify(); +// +// These classes are only for testing Google Test's own constructs. Do +// not use them in user tests, either directly or indirectly. +template <typename T> +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void (*UserThreadFunc)(T); + + ThreadWithParam( + UserThreadFunc func, T param, Notification* thread_can_start) + : func_(func), + param_(param), + thread_can_start_(thread_can_start), + finished_(false) { + ThreadWithParamBase* const base = this; + // The thread can be created only after all fields except thread_ + // have been initialized. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); + } + ~ThreadWithParam() { Join(); } + + void Join() { + if (!finished_) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); + finished_ = true; + } + } + + virtual void Run() { + if (thread_can_start_ != NULL) + thread_can_start_->WaitForNotification(); + func_(param_); + } + + private: + const UserThreadFunc func_; // User-supplied thread function. + const T param_; // User-supplied parameter to the thread function. + // When non-NULL, used to block execution until the controller thread + // notifies. + Notification* const thread_can_start_; + bool finished_; // true iff we know that the thread function has finished. + pthread_t thread_; // The native thread object. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; + +// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is +// true. +#include <pthread.h> + +// MutexBase and Mutex implement mutex on pthreads-based platforms. They +// are used in conjunction with class MutexLock: +// +// Mutex mutex; +// ... +// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end +// // of the current scope. +// +// MutexBase implements behavior for both statically and dynamically +// allocated mutexes. Do not use MutexBase directly. Instead, write +// the following to define a static mutex: +// +// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); +// +// You can forward declare a static mutex like this: +// +// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// +// To create a dynamic mutex, just define an object of type Mutex. +class MutexBase { + public: + // Acquires this mutex. + void Lock() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); + owner_ = pthread_self(); + } + + // Releases this mutex. + void Unlock() { + // We don't protect writing to owner_ here, as it's the caller's + // responsibility to ensure that the current thread holds the + // mutex when this is called. + owner_ = 0; + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); + } + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld() const { + GTEST_CHECK_(owner_ == pthread_self()) + << "The current thread is not holding the mutex @" << this; + } + + // A static mutex may be used before main() is entered. It may even + // be used before the dynamic initialization stage. Therefore we + // must be able to initialize a static mutex object at link time. + // This means MutexBase has to be a POD and its member variables + // have to be public. + public: + pthread_mutex_t mutex_; // The underlying pthread mutex. + pthread_t owner_; // The thread holding the mutex; 0 means no one holds it. +}; + +// Forward-declares a static mutex. +#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex + +// Defines and statically (i.e. at link time) initializes a static mutex. +#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 } + +// The Mutex class can only be used for mutexes created at runtime. It +// shares its API with MutexBase otherwise. +class Mutex : public MutexBase { + public: + Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + owner_ = 0; + } + ~Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +// We cannot name this class MutexLock as the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(MutexBase* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + MutexBase* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Helpers for ThreadLocal. + +// pthread_key_create() requires DeleteThreadLocalValue() to have +// C-linkage. Therefore it cannot be templatized to access +// ThreadLocal<T>. Hence the need for class +// ThreadLocalValueHolderBase. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Called by pthread to delete thread-local data stored by +// pthread_setspecific(). +extern "C" inline void DeleteThreadLocalValue(void* value_holder) { + delete static_cast<ThreadLocalValueHolderBase*>(value_holder); +} + +// Implements thread-local storage on pthreads-based systems. +// +// // Thread 1 +// ThreadLocal<int> tl(100); // 100 is the default value for each thread. +// +// // Thread 2 +// tl.set(150); // Changes the value for thread 2 only. +// EXPECT_EQ(150, tl.get()); +// +// // Thread 1 +// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. +// tl.set(200); +// EXPECT_EQ(200, tl.get()); +// +// The template type argument T must have a public copy constructor. +// In addition, the default ThreadLocal constructor requires T to have +// a public default constructor. +// +// An object managed for a thread by a ThreadLocal instance is deleted +// when the thread exits. Or, if the ThreadLocal instance dies in +// that thread, when the ThreadLocal dies. It's the user's +// responsibility to ensure that all other threads using a ThreadLocal +// have exited when it dies, or the per-thread objects for those +// threads will not be deleted. +// +// Google Test only uses global ThreadLocal objects. That means they +// will die after main() has returned. Therefore, no per-thread +// object managed by Google Test will be leaked as long as all threads +// using Google Test have exited when main() returns. +template <typename T> +class ThreadLocal { + public: + ThreadLocal() : key_(CreateKey()), + default_() {} + explicit ThreadLocal(const T& value) : key_(CreateKey()), + default_(value) {} + + ~ThreadLocal() { + // Destroys the managed object for the current thread, if any. + DeleteThreadLocalValue(pthread_getspecific(key_)); + + // Releases resources associated with the key. This will *not* + // delete managed objects for other threads. + GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); + } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of type T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + static pthread_key_t CreateKey() { + pthread_key_t key; + // When a thread exits, DeleteThreadLocalValue() will be called on + // the object managed for that thread. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_key_create(&key, &DeleteThreadLocalValue)); + return key; + } + + T* GetOrCreateValue() const { + ThreadLocalValueHolderBase* const holder = + static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); + if (holder != NULL) { + return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); + } + + ValueHolder* const new_holder = new ValueHolder(default_); + ThreadLocalValueHolderBase* const holder_base = new_holder; + GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); + return new_holder->pointer(); + } + + // A key pthreads uses for looking up per-thread values. + const pthread_key_t key_; + const T default_; // The default value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +#define GTEST_IS_THREADSAFE 1 + +#else // GTEST_HAS_PTHREAD + // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not @@ -751,14 +1176,14 @@ const ::std::vector<String>& GetArgvs(); class Mutex { public: Mutex() {} - explicit Mutex(int /*unused*/) {} void AssertHeld() const {} - enum { NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX = 0 }; }; -// We cannot call it MutexLock directly as the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. Hence the typedef trick below. +#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +#define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex + class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT @@ -779,30 +1204,37 @@ class ThreadLocal { T value_; }; -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -size_t GetThreadCount(); - // The above synchronization primitives have dummy implementations. // Therefore Google Test is not thread-safe. #define GTEST_IS_THREADSAFE 0 -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) +#endif // GTEST_HAS_PTHREAD + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler. The Nokia Symbian and the IBM XL C/C++ compiler try to -// instantiate a copy constructor for objects passed through ellipsis -// (...), failing for uncopyable objects. We define this to indicate -// the fact. -#define GTEST_ELLIPSIS_NEEDS_COPY_ 1 +// compiler and generates a warning in Sun Studio. The Nokia Symbian +// and the IBM XL C/C++ compiler try to instantiate a copy constructor +// for objects passed through ellipsis (...), failing for uncopyable +// objects. We define this to ensure that only POD is passed through +// ellipsis on these systems. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +#define GTEST_ELLIPSIS_NEEDS_POD_ 1 +#else +#define GTEST_CAN_COMPARE_NULL 1 +#endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) #define GTEST_NEEDS_IS_POINTER_ 1 - -#endif // defined(__SYMBIAN32__) || defined(__IBMCPP__) +#endif template <bool bool_value> struct bool_constant { @@ -822,10 +1254,12 @@ struct is_pointer<T*> : public true_type {}; #if GTEST_OS_WINDOWS #define GTEST_PATH_SEP_ "\\" +#define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else #define GTEST_PATH_SEP_ "/" +#define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS @@ -933,7 +1367,7 @@ inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE // We are on Windows CE, which has no environment variables. return NULL; -#elif defined(__BORLANDC__) +#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); @@ -1028,44 +1462,23 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. -// INTERNAL IMPLEMENTATION - DO NOT USE. -// -// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition -// is not satisfied. -// Synopsys: -// GTEST_CHECK_(boolean_condition); -// or -// GTEST_CHECK_(boolean_condition) << "Additional message"; -// -// This checks the condition and if the condition is not satisfied -// it prints message about the condition violation, including the -// condition itself, plus additional message streamed into it, if any, -// and then it aborts the program. It aborts the program irrespective of -// whether it is built in the debug mode or not. -#define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " - // Macro for referencing flags. #define GTEST_FLAG(name) FLAGS_gtest_##name // Macros for declaring flags. -#define GTEST_DECLARE_bool_(name) extern bool GTEST_FLAG(name) +#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) #define GTEST_DECLARE_int32_(name) \ - extern ::testing::internal::Int32 GTEST_FLAG(name) + GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ - extern ::testing::internal::String GTEST_FLAG(name) + GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ - bool GTEST_FLAG(name) = (default_val) + GTEST_API_ bool GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_int32_(name, default_val, doc) \ - ::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) \ - ::testing::internal::String GTEST_FLAG(name) = (default_val) + GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns @@ -1078,7 +1491,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); -Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); +GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); const char* StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-string.h b/utils/unittest/googletest/include/gtest/internal/gtest-string.h index 4bc824130b..aff093dec8 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-string.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-string.h @@ -41,26 +41,28 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +#ifdef __BORLANDC__ +// string.h is not guaranteed to provide strcpy on C++ Builder. +#include <mem.h> +#endif + #include <string.h> #include <gtest/internal/gtest-port.h> -#if GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING #include <string> -#endif // GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING namespace testing { namespace internal { // String - a UTF-8 string class. // -// We cannot use std::string as Microsoft's STL implementation in -// Visual C++ 7.1 has problems when exception is disabled. There is a -// hack to work around this, but we've seen cases where the hack fails -// to work. +// For historic reasons, we don't use std::string. // -// Also, String is different from std::string in that it can represent -// both NULL and the empty string, while std::string cannot represent -// NULL. +// 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. @@ -76,7 +78,7 @@ namespace internal { // // In order to make the representation efficient, the d'tor of String // is not virtual. Therefore DO NOT INHERIT FROM String. -class String { +class GTEST_API_ String { public: // Static utility methods @@ -190,12 +192,12 @@ class String { String() : c_str_(NULL), length_(0) {} // Constructs a String by cloning a 0-terminated C string. - String(const char* c_str) { // NOLINT - if (c_str == NULL) { + String(const char* a_c_str) { // NOLINT + if (a_c_str == NULL) { c_str_ = NULL; length_ = 0; } else { - ConstructNonNull(c_str, strlen(c_str)); + ConstructNonNull(a_c_str, strlen(a_c_str)); } } @@ -203,8 +205,8 @@ class String { // 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 length) { - ConstructNonNull(buffer, length); + 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 @@ -221,13 +223,11 @@ class String { // 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. -#if GTEST_HAS_STD_STRING String(const ::std::string& str) { ConstructNonNull(str.c_str(), str.length()); } operator ::std::string() const { return ::std::string(c_str(), length()); } -#endif // GTEST_HAS_STD_STRING #if GTEST_HAS_GLOBAL_STRING String(const ::string& str) { @@ -247,7 +247,7 @@ class String { // 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* c_str) const { return Compare(c_str) == 0; } + 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 "". @@ -255,7 +255,7 @@ class String { // 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* c_str) const { return !(*this == c_str); } + 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. @@ -275,7 +275,9 @@ class String { const char* c_str() const { return c_str_; } // Assigns a C string to this object. Self-assignment works. - const String& operator=(const char* c_str) { return *this = String(c_str); } + 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) { @@ -297,12 +299,12 @@ class String { // function can only be called when data_ 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 length) { - char* const str = new char[length + 1]; - memcpy(str, buffer, length); - str[length] = '\0'; + 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_ = length; + length_ = a_length; } const char* c_str_; @@ -329,7 +331,7 @@ inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { // Gets the content of the StrStream's buffer as a String. Each '\0' // character in the buffer is replaced with "\\0". -String StrStreamToString(StrStream* stream); +GTEST_API_ String StrStreamToString(StrStream* stream); // Converts a streamable value to a String. A NULL pointer is // converted to "(null)". When the input value is a ::string, diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h b/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h index 86b200be0f..16178fc07a 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h @@ -42,7 +42,8 @@ // tuple template as a friend (it complains that tuple is redefined). This // hack bypasses the bug by declaring the members that should otherwise be // private as public. -#if defined(__SYMBIAN32__) +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) #define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: #else #define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ @@ -183,7 +184,7 @@ class GTEST_1_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_() {} explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} @@ -215,7 +216,7 @@ class GTEST_2_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), f1_(f1) {} @@ -258,7 +259,7 @@ class GTEST_3_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} @@ -295,7 +296,7 @@ class GTEST_4_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), @@ -336,7 +337,7 @@ class GTEST_5_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, @@ -380,7 +381,7 @@ class GTEST_6_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, @@ -427,7 +428,7 @@ class GTEST_7_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, @@ -476,7 +477,7 @@ class GTEST_8_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, @@ -528,7 +529,7 @@ class GTEST_9_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, @@ -582,7 +583,8 @@ class tuple { public: template <int k> friend class gtest_internal::Get; - tuple() {} + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), + f9_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, diff --git a/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h b/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h index f1b1bedd86..093eee6f01 100644 --- a/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h +++ b/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h @@ -1,4 +1,6 @@ -// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! +// This file was GENERATED by command: +// pump.py gtest-type-util.h.pump +// DO NOT EDIT BY HAND!!! // Copyright 2008 Google Inc. // All Rights Reserved. @@ -53,8 +55,6 @@ #include <cxxabi.h> #endif // __GLIBCXX__ -#include <typeinfo> - namespace testing { namespace internal { |