32
32
// The Google C++ Testing Framework (Google Test)
34
#include <gtest/gtest.h>
35
#include <gtest/gtest-spi.h>
34
#include "gtest/gtest.h"
35
#include "gtest/gtest-spi.h"
39
39
#include <stdarg.h>
41
41
#include <stdlib.h>
43
44
#include <wctype.h>
47
#include <ostream> // NOLINT
49
53
// TODO(kenton@google.com): Use autoconf to detect availability of
51
#define GTEST_HAS_GETTIMEOFDAY_ 1
55
# define GTEST_HAS_GETTIMEOFDAY_ 1
57
# include <fcntl.h> // NOLINT
58
# include <limits.h> // NOLINT
59
# include <sched.h> // NOLINT
56
60
// Declares vsnprintf(). This header is not available on Windows.
61
# include <strings.h> // NOLINT
62
# include <sys/mman.h> // NOLINT
63
# include <sys/time.h> // NOLINT
64
# include <unistd.h> // NOLINT
64
67
#elif GTEST_OS_SYMBIAN
65
#define GTEST_HAS_GETTIMEOFDAY_ 1
66
#include <sys/time.h> // NOLINT
68
# define GTEST_HAS_GETTIMEOFDAY_ 1
69
# include <sys/time.h> // NOLINT
69
#define GTEST_HAS_GETTIMEOFDAY_ 1
70
#include <sys/time.h> // NOLINT
72
# define GTEST_HAS_GETTIMEOFDAY_ 1
73
# include <sys/time.h> // NOLINT
72
75
// On z/OS we additionally need strings.h for strcasecmp.
73
#include <strings.h> // NOLINT
76
# include <strings.h> // NOLINT
75
78
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
77
#include <windows.h> // NOLINT
80
# include <windows.h> // NOLINT
79
82
#elif GTEST_OS_WINDOWS // We are on Windows proper.
81
#include <io.h> // NOLINT
82
#include <sys/timeb.h> // NOLINT
83
#include <sys/types.h> // NOLINT
84
#include <sys/stat.h> // NOLINT
84
# include <io.h> // NOLINT
85
# include <sys/timeb.h> // NOLINT
86
# include <sys/types.h> // NOLINT
87
# include <sys/stat.h> // NOLINT
86
#if GTEST_OS_WINDOWS_MINGW
89
# if GTEST_OS_WINDOWS_MINGW
87
90
// MinGW has gettimeofday() but not _ftime64().
88
91
// TODO(kenton@google.com): Use autoconf to detect availability of
90
93
// TODO(kenton@google.com): There are other ways to get the time on
91
94
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
92
95
// supports these. consider using them instead.
93
#define GTEST_HAS_GETTIMEOFDAY_ 1
94
#include <sys/time.h> // NOLINT
95
#endif // GTEST_OS_WINDOWS_MINGW
96
# define GTEST_HAS_GETTIMEOFDAY_ 1
97
# include <sys/time.h> // NOLINT
98
# endif // GTEST_OS_WINDOWS_MINGW
97
100
// cpplint thinks that the header is already included, so we want to
99
#include <windows.h> // NOLINT
102
# include <windows.h> // NOLINT
103
106
// Assume other platforms have gettimeofday().
104
107
// TODO(kenton@google.com): Use autoconf to detect availability of
105
108
// gettimeofday().
106
#define GTEST_HAS_GETTIMEOFDAY_ 1
109
# define GTEST_HAS_GETTIMEOFDAY_ 1
108
111
// cpplint thinks that the header is already included, so we want to
110
#include <sys/time.h> // NOLINT
111
#include <unistd.h> // NOLINT
113
# include <sys/time.h> // NOLINT
114
# include <unistd.h> // NOLINT
113
116
#endif // GTEST_OS_LINUX
115
118
#if GTEST_HAS_EXCEPTIONS
119
# include <stdexcept>
122
#if GTEST_CAN_STREAM_RESULTS_
123
# include <arpa/inet.h> // NOLINT
124
# include <netdb.h> // NOLINT
119
127
// Indicates that this translation unit is part of Google Test's
363
383
// Functions for processing the gtest_output flag.
365
385
// Returns the output format, or "" for normal printed output.
366
String UnitTestOptions::GetOutputFormat() {
386
std::string UnitTestOptions::GetOutputFormat() {
367
387
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
368
if (gtest_output_flag == NULL) return String("");
388
if (gtest_output_flag == NULL) return std::string("");
370
390
const char* const colon = strchr(gtest_output_flag, ':');
371
391
return (colon == NULL) ?
372
String(gtest_output_flag) :
373
String(gtest_output_flag, colon - gtest_output_flag);
392
std::string(gtest_output_flag) :
393
std::string(gtest_output_flag, colon - gtest_output_flag);
376
396
// Returns the name of the requested output file, or the default if none
377
397
// was explicitly specified.
378
String UnitTestOptions::GetAbsolutePathToOutputFile() {
398
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
379
399
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
380
400
if (gtest_output_flag == NULL)
383
403
const char* const colon = strchr(gtest_output_flag, ':');
384
404
if (colon == NULL)
385
return String(internal::FilePath::ConcatPaths(
387
UnitTest::GetInstance()->original_working_dir()),
388
internal::FilePath(kDefaultOutputFile)).ToString() );
405
return internal::FilePath::ConcatPaths(
407
UnitTest::GetInstance()->original_working_dir()),
408
internal::FilePath(kDefaultOutputFile)).string();
390
410
internal::FilePath output_name(colon + 1);
391
411
if (!output_name.IsAbsolutePath())
482
499
!MatchesFilter(full_name, negative.c_str()));
486
503
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
487
504
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
488
505
// This function is useful as an __except condition.
489
506
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
490
// Google Test should handle an exception if:
507
// Google Test should handle a SEH exception if:
491
508
// 1. the user wants it to, AND
492
// 2. this is not a breakpoint exception.
493
return (GTEST_FLAG(catch_exceptions) &&
494
exception_code != EXCEPTION_BREAKPOINT) ?
495
EXCEPTION_EXECUTE_HANDLER :
496
EXCEPTION_CONTINUE_SEARCH;
509
// 2. this is not a breakpoint exception, AND
510
// 3. this is not a C++ exception (VC++ implements them via SEH,
513
// SEH exception code for C++ exceptions.
514
// (see http://support.microsoft.com/kb/185294 for more information).
515
const DWORD kCxxExceptionCode = 0xe06d7363;
517
bool should_handle = true;
519
if (!GTEST_FLAG(catch_exceptions))
520
should_handle = false;
521
else if (exception_code == EXCEPTION_BREAKPOINT)
522
should_handle = false;
523
else if (exception_code == kCxxExceptionCode)
524
should_handle = false;
526
return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
498
#endif // GTEST_OS_WINDOWS
528
#endif // GTEST_HAS_SEH
500
530
} // namespace internal
757
785
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
760
790
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
761
791
// (deprecated function) there.
762
792
// TODO(kenton@google.com): Use GetTickCount()? Or use
763
793
// SystemTimeToFileTime()
764
#pragma warning(push) // Saves the current warning state.
765
#pragma warning(disable:4996) // Temporarily disables warning 4996.
767
#pragma warning(pop) // Restores the warning state.
794
# pragma warning(push) // Saves the current warning state.
795
# pragma warning(disable:4996) // Temporarily disables warning 4996.
797
# pragma warning(pop) // Restores the warning state.
771
804
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
772
805
#elif GTEST_HAS_GETTIMEOFDAY_
773
806
struct timeval now;
774
807
gettimeofday(&now, NULL);
775
808
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
777
#error "Don't know how to get the current time on your system."
810
# error "Don't know how to get the current time on your system."
785
// Returns the input enclosed in double quotes if it's not NULL;
786
// otherwise returns "(null)". For example, "\"Hello\"" is returned
787
// for input "Hello".
789
// This is useful for printing a C string in the syntax of a literal.
791
// Known issue: escape sequences are not handled yet.
792
String String::ShowCStringQuoted(const char* c_str) {
793
return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
796
// Copies at most length characters from str into a newly-allocated
797
// piece of memory of size length+1. The memory is allocated with new[].
798
// A terminating null byte is written to the memory, and a pointer to it
799
// is returned. If str is NULL, NULL is returned.
800
static char* CloneString(const char* str, size_t length) {
804
char* const clone = new char[length + 1];
805
posix::StrNCpy(clone, str, length);
806
clone[length] = '\0';
811
// Clones a 0-terminated C string, allocating memory using new. The
812
// caller is responsible for deleting[] the return value. Returns the
813
// cloned string, or NULL if the input is NULL.
814
const char * String::CloneCString(const char* c_str) {
815
return (c_str == NULL) ?
816
NULL : CloneString(c_str, strlen(c_str));
819
818
#if GTEST_OS_WINDOWS_MOBILE
820
819
// Creates a UTF-16 wide string from the given ANSI string, allocating
911
905
#endif // GTEST_HAS_GLOBAL_WSTRING
915
// Formats a value to be used in a failure message.
917
// For a char value, we print it as a C++ char literal and as an
918
// unsigned integer (both in decimal and in hexadecimal).
919
String FormatForFailureMessage(char ch) {
920
const unsigned int ch_as_uint = ch;
921
// A String object cannot contain '\0', so we print "\\0" when ch is
923
return String::Format("'%s' (%u, 0x%X)",
924
ch ? String::Format("%c", ch).c_str() : "\\0",
925
ch_as_uint, ch_as_uint);
928
// For a wchar_t value, we print it as a C++ wchar_t literal and as an
929
// unsigned integer (both in decimal and in hexidecimal).
930
String FormatForFailureMessage(wchar_t wchar) {
931
// The C++ standard doesn't specify the exact size of the wchar_t
932
// type. It just says that it shall have the same size as another
933
// integral type, called its underlying type.
935
// Therefore, in order to print a wchar_t value in the numeric form,
936
// we first convert it to the largest integral type (UInt64) and
937
// then print the converted value.
939
// We use streaming to print the value as "%llu" doesn't work
940
// correctly with MSVC 7.1.
941
const UInt64 wchar_as_uint64 = wchar;
943
// A String object cannot contain '\0', so we print "\\0" when wchar is
945
char buffer[32]; // CodePointToUtf8 requires a buffer that big.
947
<< (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
948
<< "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
949
<< wchar_as_uint64 << ")";
950
return msg.GetString();
953
} // namespace internal
955
// AssertionResult constructor.
956
AssertionResult::AssertionResult(const internal::String& failure_message)
957
: failure_message_(failure_message) {
907
// AssertionResult constructors.
908
// Used in EXPECT_TRUE/FALSE(assertion_result).
909
AssertionResult::AssertionResult(const AssertionResult& other)
910
: success_(other.success_),
911
message_(other.message_.get() != NULL ?
912
new ::std::string(*other.message_) :
913
static_cast< ::std::string*>(NULL)) {
916
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
917
AssertionResult AssertionResult::operator!() const {
918
AssertionResult negation(!success_);
919
if (message_.get() != NULL)
920
negation << *message_;
961
924
// Makes a successful assertion result.
962
925
AssertionResult AssertionSuccess() {
963
return AssertionResult();
926
return AssertionResult(true);
929
// Makes a failed assertion result.
930
AssertionResult AssertionFailure() {
931
return AssertionResult(false);
967
934
// Makes a failed assertion result with the given failure message.
935
// Deprecated; use AssertionFailure() << message.
968
936
AssertionResult AssertionFailure(const Message& message) {
969
return AssertionResult(message.GetString());
937
return AssertionFailure() << message;
972
940
namespace internal {
1622
1586
#endif // OS selector
1625
// Compares this with another String.
1626
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1627
// if this is greater than rhs.
1628
int String::Compare(const String & rhs) const {
1629
const char* const lhs_c_str = c_str();
1630
const char* const rhs_c_str = rhs.c_str();
1632
if (lhs_c_str == NULL) {
1633
return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1634
} else if (rhs_c_str == NULL) {
1638
const size_t shorter_str_len =
1639
length() <= rhs.length() ? length() : rhs.length();
1640
for (size_t i = 0; i != shorter_str_len; i++) {
1641
if (lhs_c_str[i] < rhs_c_str[i]) {
1643
} else if (lhs_c_str[i] > rhs_c_str[i]) {
1647
return (length() < rhs.length()) ? -1 :
1648
(length() > rhs.length()) ? 1 : 0;
1651
// Returns true iff this String ends with the given suffix. *Any*
1652
// String is considered to end with a NULL or empty suffix.
1653
bool String::EndsWith(const char* suffix) const {
1654
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1656
if (c_str() == NULL) return false;
1658
const size_t this_len = strlen(c_str());
1659
const size_t suffix_len = strlen(suffix);
1660
return (this_len >= suffix_len) &&
1661
CStringEquals(c_str() + this_len - suffix_len, suffix);
1664
// Returns true iff this String ends with the given suffix, ignoring case.
1665
// Any String is considered to end with a NULL or empty suffix.
1666
bool String::EndsWithCaseInsensitive(const char* suffix) const {
1667
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1669
if (c_str() == NULL) return false;
1671
const size_t this_len = strlen(c_str());
1672
const size_t suffix_len = strlen(suffix);
1673
return (this_len >= suffix_len) &&
1674
CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1677
// Formats a list of arguments to a String, using the same format
1589
// Returns true iff str ends with the given suffix, ignoring case.
1590
// Any string is considered to end with an empty suffix.
1591
bool String::EndsWithCaseInsensitive(
1592
const std::string& str, const std::string& suffix) {
1593
const size_t str_len = str.length();
1594
const size_t suffix_len = suffix.length();
1595
return (str_len >= suffix_len) &&
1596
CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
1600
// Formats a list of arguments to an std::string, using the same format
1678
1601
// spec string as for printf.
1680
1603
// We do not use the StringPrintf class as it is not universally
1709
1634
// always returns a negative value. For simplicity, we lump the two
1710
1635
// error cases together.
1711
1636
if (size < 0 || size >= kBufferSize) {
1712
return String("<formatting error or buffer exceeded>");
1637
return "<formatting error or buffer exceeded>";
1714
return String(buffer, size);
1639
return std::string(buffer, size);
1718
// Converts the buffer in a StrStream to a String, converting NUL
1643
// Converts the buffer in a stringstream to an std::string, converting NUL
1719
1644
// bytes to "\\0" along the way.
1720
String StrStreamToString(StrStream* ss) {
1721
#if GTEST_HAS_STD_STRING
1645
std::string StringStreamToString(::std::stringstream* ss) {
1722
1646
const ::std::string& str = ss->str();
1723
1647
const char* const start = str.c_str();
1724
1648
const char* const end = start + str.length();
1726
const char* const start = ss->str();
1727
const char* const end = start + ss->pcount();
1728
#endif // GTEST_HAS_STD_STRING
1730
// We need to use a helper StrStream to do this transformation
1731
// because String doesn't support push_back().
1651
result.reserve(2 * (end - start));
1733
1652
for (const char* ch = start; ch != end; ++ch) {
1734
1653
if (*ch == '\0') {
1735
helper << "\\0"; // Replaces NUL with "\\0";
1654
result += "\\0"; // Replaces NUL with "\\0";
1741
#if GTEST_HAS_STD_STRING
1742
return String(helper.str().c_str());
1744
const String str(helper.str(), helper.pcount());
1745
helper.freeze(false);
1748
#endif // GTEST_HAS_STD_STRING
1751
1663
// Appends the user-supplied message to the Google-Test-generated message.
1752
String AppendUserMessage(const String& gtest_msg,
1753
const Message& user_msg) {
1664
std::string AppendUserMessage(const std::string& gtest_msg,
1665
const Message& user_msg) {
1754
1666
// Appends the user message if it's non-empty.
1755
const String user_msg_string = user_msg.GetString();
1667
const std::string user_msg_string = user_msg.GetString();
1756
1668
if (user_msg_string.empty()) {
1757
1669
return gtest_msg;
1761
msg << gtest_msg << "\n" << user_msg_string;
1763
return msg.GetString();
1672
return gtest_msg + "\n" + user_msg_string;
1766
1675
} // namespace internal
1920
// Adds an "exception thrown" fatal failure to the current test. This
1921
// function returns its result via an output parameter pointer because VC++
1922
// prohibits creation of objects with destructors on stack in functions
1923
// using __try (see error C2712).
1924
static std::string* FormatSehExceptionMessage(DWORD exception_code,
1925
const char* location) {
1927
message << "SEH exception with code 0x" << std::setbase(16) <<
1928
exception_code << std::setbase(10) << " thrown in " << location << ".";
1930
return new std::string(message.GetString());
1933
#endif // GTEST_HAS_SEH
1935
#if GTEST_HAS_EXCEPTIONS
1937
// Adds an "exception thrown" fatal failure to the current test.
1938
static std::string FormatCxxExceptionMessage(const char* description,
1939
const char* location) {
1941
if (description != NULL) {
1942
message << "C++ exception with description \"" << description << "\"";
1944
message << "Unknown C++ exception";
1946
message << " thrown in " << location << ".";
1948
return message.GetString();
1951
static std::string PrintTestPartResultToString(
1952
const TestPartResult& test_part_result);
1954
// A failed Google Test assertion will throw an exception of this type when
1955
// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
1956
// derive it from std::runtime_error, which is for errors presumably
1957
// detectable only at run time. Since std::runtime_error inherits from
1958
// std::exception, many testing frameworks know how to extract and print the
1959
// message inside it.
1960
class GoogleTestFailureException : public ::std::runtime_error {
1962
explicit GoogleTestFailureException(const TestPartResult& failure)
1963
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
1965
#endif // GTEST_HAS_EXCEPTIONS
1967
namespace internal {
1968
// We put these helper functions in the internal namespace as IBM's xlC
1969
// compiler rejects the code if they were declared static.
1971
// Runs the given method and handles SEH exceptions it throws, when
1972
// SEH is supported; returns the 0-value for type Result in case of an
1973
// SEH exception. (Microsoft compilers cannot handle SEH and C++
1974
// exceptions in the same function. Therefore, we provide a separate
1975
// wrapper function for handling SEH exceptions.)
1976
template <class T, typename Result>
1977
Result HandleSehExceptionsInMethodIfSupported(
1978
T* object, Result (T::*method)(), const char* location) {
1981
return (object->*method)();
1982
} __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
1983
GetExceptionCode())) {
1984
// We create the exception message on the heap because VC++ prohibits
1985
// creation of objects with destructors on stack in functions using __try
1986
// (see error C2712).
1987
std::string* exception_message = FormatSehExceptionMessage(
1988
GetExceptionCode(), location);
1989
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1990
*exception_message);
1991
delete exception_message;
1992
return static_cast<Result>(0);
1996
return (object->*method)();
1997
#endif // GTEST_HAS_SEH
2000
// Runs the given method and catches and reports C++ and/or SEH-style
2001
// exceptions, if they are supported; returns the 0-value for type
2002
// Result in case of an SEH exception.
2003
template <class T, typename Result>
2004
Result HandleExceptionsInMethodIfSupported(
2005
T* object, Result (T::*method)(), const char* location) {
2006
// NOTE: The user code can affect the way in which Google Test handles
2007
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2008
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
2009
// after the exception is caught and either report or re-throw the
2010
// exception based on the flag's value:
2013
// // Perform the test method.
2015
// if (GTEST_FLAG(catch_exceptions))
2016
// // Report the exception as failure.
2018
// throw; // Re-throws the original exception.
2021
// However, the purpose of this flag is to allow the program to drop into
2022
// the debugger when the exception is thrown. On most platforms, once the
2023
// control enters the catch block, the exception origin information is
2024
// lost and the debugger will stop the program at the point of the
2025
// re-throw in this function -- instead of at the point of the original
2026
// throw statement in the code under test. For this reason, we perform
2027
// the check early, sacrificing the ability to affect Google Test's
2028
// exception handling in the method where the exception is thrown.
2029
if (internal::GetUnitTestImpl()->catch_exceptions()) {
2030
#if GTEST_HAS_EXCEPTIONS
2032
return HandleSehExceptionsInMethodIfSupported(object, method, location);
2033
} catch (const GoogleTestFailureException&) { // NOLINT
2034
// This exception doesn't originate in code under test. It makes no
2035
// sense to report it as a test failure.
2037
} catch (const std::exception& e) { // NOLINT
2038
internal::ReportFailureInUnknownLocation(
2039
TestPartResult::kFatalFailure,
2040
FormatCxxExceptionMessage(e.what(), location));
2041
} catch (...) { // NOLINT
2042
internal::ReportFailureInUnknownLocation(
2043
TestPartResult::kFatalFailure,
2044
FormatCxxExceptionMessage(NULL, location));
2046
return static_cast<Result>(0);
2048
return HandleSehExceptionsInMethodIfSupported(object, method, location);
2049
#endif // GTEST_HAS_EXCEPTIONS
2051
return (object->*method)();
2055
} // namespace internal
2025
2057
// Runs the test and updates the test result.
2026
2058
void Test::Run() {
2027
2059
if (!HasSameFixtureClass()) return;
2029
2061
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2031
// Catch SEH-style exceptions.
2032
impl->os_stack_trace_getter()->UponLeavingGTest();
2035
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2036
GetExceptionCode())) {
2037
AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2040
// We will run the test only if SetUp() had no fatal failure.
2041
if (!HasFatalFailure()) {
2042
impl->os_stack_trace_getter()->UponLeavingGTest();
2045
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2046
GetExceptionCode())) {
2047
AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2051
// However, we want to clean up as much as possible. Hence we will
2052
// always call TearDown(), even if SetUp() or the test body has
2054
impl->os_stack_trace_getter()->UponLeavingGTest();
2057
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2058
GetExceptionCode())) {
2059
AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2062
#else // We are on a compiler or platform that doesn't support SEH.
2063
impl->os_stack_trace_getter()->UponLeavingGTest();
2062
impl->os_stack_trace_getter()->UponLeavingGTest();
2063
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2066
2064
// We will run the test only if SetUp() was successful.
2067
2065
if (!HasFatalFailure()) {
2068
2066
impl->os_stack_trace_getter()->UponLeavingGTest();
2067
internal::HandleExceptionsInMethodIfSupported(
2068
this, &Test::TestBody, "the test body");
2072
2071
// However, we want to clean up as much as possible. Hence we will
2073
2072
// always call TearDown(), even if SetUp() or the test body has
2075
2074
impl->os_stack_trace_getter()->UponLeavingGTest();
2077
#endif // GTEST_HAS_SEH
2075
internal::HandleExceptionsInMethodIfSupported(
2076
this, &Test::TearDown, "TearDown()");
2081
2079
// Returns true iff the current test has a fatal failure.
2082
2080
bool Test::HasFatalFailure() {
2083
2081
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2092
2090
// class TestInfo
2094
2092
// Constructs a TestInfo object. It assumes ownership of the test factory
2095
// object via impl_.
2096
TestInfo::TestInfo(const char* test_case_name,
2098
const char* test_case_comment,
2099
const char* comment,
2094
// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
2095
// to signify they cannot be NULLs.
2096
TestInfo::TestInfo(const char* a_test_case_name,
2098
const char* a_type_param,
2099
const char* a_value_param,
2100
2100
internal::TypeId fixture_class_id,
2101
internal::TestFactoryBase* factory) {
2102
impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2103
test_case_comment, comment,
2104
fixture_class_id, factory);
2101
internal::TestFactoryBase* factory)
2102
: test_case_name_(a_test_case_name),
2104
type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2105
value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2106
fixture_class_id_(fixture_class_id),
2108
is_disabled_(false),
2109
matches_filter_(false),
2107
2113
// Destructs a TestInfo object.
2108
TestInfo::~TestInfo() {
2114
TestInfo::~TestInfo() { delete factory_; }
2112
2116
namespace internal {
2214
} // namespace internal
2244
2216
// Creates the test object, runs it, records its result, and then
2246
void TestInfoImpl::Run() {
2218
void TestInfo::Run() {
2247
2219
if (!should_run_) return;
2249
2221
// Tells UnitTest where to store test result.
2250
UnitTestImpl* const impl = internal::GetUnitTestImpl();
2251
impl->set_current_test_info(parent_);
2222
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2223
impl->set_current_test_info(this);
2253
2225
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2255
2227
// Notifies the unit test event listeners that a test is about to start.
2256
repeater->OnTestStart(*parent_);
2228
repeater->OnTestStart(*this);
2258
const TimeInMillis start = GetTimeInMillis();
2230
const TimeInMillis start = internal::GetTimeInMillis();
2260
2232
impl->os_stack_trace_getter()->UponLeavingGTest();
2262
// Catch SEH-style exceptions.
2266
// Creates the test object.
2267
test = factory_->CreateTest();
2268
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2269
GetExceptionCode())) {
2270
AddExceptionThrownFailure(GetExceptionCode(),
2271
"the test fixture's constructor");
2274
#else // We are on a compiler or platform that doesn't support SEH.
2276
// TODO(wan): If test->Run() throws, test won't be deleted. This is
2277
// not a problem now as we don't use exceptions. If we were to
2278
// enable exceptions, we should revise the following to be
2281
2234
// Creates the test object.
2282
Test* test = factory_->CreateTest();
2283
#endif // GTEST_HAS_SEH
2235
Test* const test = internal::HandleExceptionsInMethodIfSupported(
2236
factory_, &internal::TestFactoryBase::CreateTest,
2237
"the test fixture's constructor");
2285
// Runs the test only if the constructor of the test fixture didn't
2286
// generate a fatal failure.
2287
if (!Test::HasFatalFailure()) {
2239
// Runs the test only if the test object was created and its
2240
// constructor didn't generate a fatal failure.
2241
if ((test != NULL) && !Test::HasFatalFailure()) {
2242
// This doesn't throw as all user code that can throw are wrapped into
2243
// exception handling code.
2291
2247
// Deletes the test object.
2292
2248
impl->os_stack_trace_getter()->UponLeavingGTest();
2249
internal::HandleExceptionsInMethodIfSupported(
2250
test, &Test::DeleteSelf_, "the test fixture's destructor");
2296
result_.set_elapsed_time(GetTimeInMillis() - start);
2252
result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2298
2254
// Notifies the unit test event listener that a test has just finished.
2299
repeater->OnTestEnd(*parent_);
2255
repeater->OnTestEnd(*this);
2301
2257
// Tells UnitTest to stop associating assertion results to this
2303
2259
impl->set_current_test_info(NULL);
2306
} // namespace internal
2308
2262
// class TestCase
2310
2264
// Gets the number of successful tests in this test case.
2311
2265
int TestCase::successful_test_count() const {
2312
return test_info_list_->CountIf(TestPassed);
2266
return CountIf(test_info_list_, TestPassed);
2315
2269
// Gets the number of failed tests in this test case.
2316
2270
int TestCase::failed_test_count() const {
2317
return test_info_list_->CountIf(TestFailed);
2271
return CountIf(test_info_list_, TestFailed);
2320
2274
int TestCase::disabled_test_count() const {
2321
return test_info_list_->CountIf(TestDisabled);
2275
return CountIf(test_info_list_, TestDisabled);
2324
2278
// Get the number of tests in this test case that should run.
2325
2279
int TestCase::test_to_run_count() const {
2326
return test_info_list_->CountIf(ShouldRunTest);
2280
return CountIf(test_info_list_, ShouldRunTest);
2329
2283
// Gets the number of all tests.
2330
2284
int TestCase::total_test_count() const {
2331
return test_info_list_->size();
2285
return static_cast<int>(test_info_list_.size());
2334
2288
// Creates a TestCase with the given name.
2354
2308
// Destructor of TestCase.
2355
2309
TestCase::~TestCase() {
2356
2310
// Deletes every Test in the collection.
2357
test_info_list_->ForEach(internal::Delete<TestInfo>);
2311
ForEach(test_info_list_, internal::Delete<TestInfo>);
2360
2314
// Returns the i-th test among all the tests. i can range from 0 to
2361
2315
// total_test_count() - 1. If i is not in that range, returns NULL.
2362
2316
const TestInfo* TestCase::GetTestInfo(int i) const {
2363
const int index = test_indices_->GetElementOr(i, -1);
2364
return index < 0 ? NULL : test_info_list_->GetElement(index);
2317
const int index = GetElementOr(test_indices_, i, -1);
2318
return index < 0 ? NULL : test_info_list_[index];
2367
2321
// Returns the i-th test among all the tests. i can range from 0 to
2368
2322
// total_test_count() - 1. If i is not in that range, returns NULL.
2369
2323
TestInfo* TestCase::GetMutableTestInfo(int i) {
2370
const int index = test_indices_->GetElementOr(i, -1);
2371
return index < 0 ? NULL : test_info_list_->GetElement(index);
2324
const int index = GetElementOr(test_indices_, i, -1);
2325
return index < 0 ? NULL : test_info_list_[index];
2374
2328
// Adds a test to this test case. Will delete the test upon
2375
2329
// destruction of the TestCase object.
2376
2330
void TestCase::AddTestInfo(TestInfo * test_info) {
2377
test_info_list_->PushBack(test_info);
2378
test_indices_->PushBack(test_indices_->size());
2331
test_info_list_.push_back(test_info);
2332
test_indices_.push_back(static_cast<int>(test_indices_.size()));
2381
2335
// Runs every test in this TestCase.
2390
2344
repeater->OnTestCaseStart(*this);
2391
2345
impl->os_stack_trace_getter()->UponLeavingGTest();
2346
internal::HandleExceptionsInMethodIfSupported(
2347
this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2394
2349
const internal::TimeInMillis start = internal::GetTimeInMillis();
2395
2350
for (int i = 0; i < total_test_count(); i++) {
2396
GetMutableTestInfo(i)->impl()->Run();
2351
GetMutableTestInfo(i)->Run();
2398
2353
elapsed_time_ = internal::GetTimeInMillis() - start;
2400
2355
impl->os_stack_trace_getter()->UponLeavingGTest();
2356
internal::HandleExceptionsInMethodIfSupported(
2357
this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2402
2359
repeater->OnTestCaseEnd(*this);
2403
2360
impl->set_current_test_case(NULL);
2406
2363
// Clears the results of all tests in this test case.
2407
2364
void TestCase::ClearResult() {
2408
test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2411
// Returns true iff test passed.
2412
bool TestCase::TestPassed(const TestInfo * test_info) {
2413
const internal::TestInfoImpl* const impl = test_info->impl();
2414
return impl->should_run() && impl->result()->Passed();
2417
// Returns true iff test failed.
2418
bool TestCase::TestFailed(const TestInfo * test_info) {
2419
const internal::TestInfoImpl* const impl = test_info->impl();
2420
return impl->should_run() && impl->result()->Failed();
2423
// Returns true iff test is disabled.
2424
bool TestCase::TestDisabled(const TestInfo * test_info) {
2425
return test_info->impl()->is_disabled();
2428
// Returns true if the given test should run.
2429
bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2430
return test_info->impl()->should_run();
2365
ForEach(test_info_list_, TestInfo::ClearTestResult);
2433
2368
// Shuffles the tests in this test case.
2434
2369
void TestCase::ShuffleTests(internal::Random* random) {
2435
test_indices_->Shuffle(random);
2370
Shuffle(random, &test_indices_);
2438
2373
// Restores the test order to before the first shuffle.
2439
2374
void TestCase::UnshuffleTests() {
2440
for (int i = 0; i < test_indices_->size(); i++) {
2441
test_indices_->GetMutableElement(i) = i;
2375
for (size_t i = 0; i < test_indices_.size(); i++) {
2376
test_indices_[i] = static_cast<int>(i);
3277
3258
// End XmlUnitTestResultPrinter
3260
#if GTEST_CAN_STREAM_RESULTS_
3262
// Streams test results to the given port on the given host machine.
3263
class StreamingListener : public EmptyTestEventListener {
3265
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
3266
static string UrlEncode(const char* str);
3268
StreamingListener(const string& host, const string& port)
3269
: sockfd_(-1), host_name_(host), port_num_(port) {
3271
Send("gtest_streaming_protocol_version=1.0\n");
3274
virtual ~StreamingListener() {
3279
void OnTestProgramStart(const UnitTest& /* unit_test */) {
3280
Send("event=TestProgramStart\n");
3283
void OnTestProgramEnd(const UnitTest& unit_test) {
3284
// Note that Google Test current only report elapsed time for each
3285
// test iteration, not for the entire test program.
3286
Send(String::Format("event=TestProgramEnd&passed=%d\n",
3287
unit_test.Passed()));
3289
// Notify the streaming server to stop.
3293
void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
3294
Send(String::Format("event=TestIterationStart&iteration=%d\n",
3298
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
3299
Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
3301
StreamableToString(unit_test.elapsed_time()).c_str()));
3304
void OnTestCaseStart(const TestCase& test_case) {
3305
Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
3308
void OnTestCaseEnd(const TestCase& test_case) {
3309
Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
3311
StreamableToString(test_case.elapsed_time()).c_str()));
3314
void OnTestStart(const TestInfo& test_info) {
3315
Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
3318
void OnTestEnd(const TestInfo& test_info) {
3319
Send(String::Format(
3320
"event=TestEnd&passed=%d&elapsed_time=%sms\n",
3321
(test_info.result())->Passed(),
3322
StreamableToString((test_info.result())->elapsed_time()).c_str()));
3325
void OnTestPartResult(const TestPartResult& test_part_result) {
3326
const char* file_name = test_part_result.file_name();
3327
if (file_name == NULL)
3329
Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
3330
UrlEncode(file_name).c_str(),
3331
test_part_result.line_number()));
3332
Send(UrlEncode(test_part_result.message()) + "\n");
3336
// Creates a client socket and connects to the server.
3337
void MakeConnection();
3339
// Closes the socket.
3340
void CloseConnection() {
3341
GTEST_CHECK_(sockfd_ != -1)
3342
<< "CloseConnection() can be called only when there is a connection.";
3348
// Sends a string to the socket.
3349
void Send(const string& message) {
3350
GTEST_CHECK_(sockfd_ != -1)
3351
<< "Send() can be called only when there is a connection.";
3353
const int len = static_cast<int>(message.length());
3354
if (write(sockfd_, message.c_str(), len) != len) {
3356
<< "stream_result_to: failed to stream to "
3357
<< host_name_ << ":" << port_num_;
3361
int sockfd_; // socket file descriptor
3362
const string host_name_;
3363
const string port_num_;
3365
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
3366
}; // class StreamingListener
3368
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
3369
// replaces them by "%xx" where xx is their hexadecimal value. For
3370
// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
3371
// in both time and space -- important as the input str may contain an
3372
// arbitrarily long test failure message and stack trace.
3373
string StreamingListener::UrlEncode(const char* str) {
3375
result.reserve(strlen(str) + 1);
3376
for (char ch = *str; ch != '\0'; ch = *++str) {
3382
result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
3385
result.push_back(ch);
3392
void StreamingListener::MakeConnection() {
3393
GTEST_CHECK_(sockfd_ == -1)
3394
<< "MakeConnection() can't be called when there is already a connection.";
3397
memset(&hints, 0, sizeof(hints));
3398
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
3399
hints.ai_socktype = SOCK_STREAM;
3400
addrinfo* servinfo = NULL;
3402
// Use the getaddrinfo() to get a linked list of IP addresses for
3403
// the given host name.
3404
const int error_num = getaddrinfo(
3405
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
3406
if (error_num != 0) {
3407
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
3408
<< gai_strerror(error_num);
3411
// Loop through all the results and connect to the first we can.
3412
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
3413
cur_addr = cur_addr->ai_next) {
3415
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
3416
if (sockfd_ != -1) {
3417
// Connect the client socket to the server socket.
3418
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
3425
freeaddrinfo(servinfo); // all done with this structure
3427
if (sockfd_ == -1) {
3428
GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
3429
<< host_name_ << ":" << port_num_;
3433
// End of class Streaming Listener
3434
#endif // GTEST_CAN_STREAM_RESULTS__
3279
3436
// Class ScopedTrace
3281
3438
// Pushes the given source file location and message onto a per-thread
3282
3439
// trace stack maintained by Google Test.
3283
// L < UnitTest::mutex_
3284
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3440
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
3441
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3285
3442
TraceInfo trace;
3286
3443
trace.file = file;
3287
3444
trace.line = line;
3515
impl_->environments()->PushBack(env);
3516
impl_->environments_in_reverse_order()->PushFront(env);
3678
impl_->environments().push_back(env);
3520
#if GTEST_HAS_EXCEPTIONS
3521
// A failed Google Test assertion will throw an exception of this type
3522
// when exceptions are enabled. We derive it from std::runtime_error,
3523
// which is for errors presumably detectable only at run time. Since
3524
// std::runtime_error inherits from std::exception, many testing
3525
// frameworks know how to extract and print the message inside it.
3526
class GoogleTestFailureException : public ::std::runtime_error {
3528
explicit GoogleTestFailureException(const TestPartResult& failure)
3529
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3533
3682
// Adds a TestPartResult to the current TestResult object. All Google Test
3534
3683
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3535
3684
// this to report their results. The user code should use the
3536
3685
// assertion macros instead of calling this directly.
3538
void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3539
const char* file_name,
3541
const internal::String& message,
3542
const internal::String& os_stack_trace) {
3686
void UnitTest::AddTestPartResult(
3687
TestPartResult::Type result_type,
3688
const char* file_name,
3690
const std::string& message,
3691
const std::string& os_stack_trace)
3692
GTEST_LOCK_EXCLUDED_(mutex_) {
3544
3694
msg << message;
3546
3696
internal::MutexLock lock(&mutex_);
3547
if (impl_->gtest_trace_stack()->size() > 0) {
3697
if (impl_->gtest_trace_stack().size() > 0) {
3548
3698
msg << "\n" << GTEST_NAME_ << " trace:";
3550
for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) {
3551
const internal::TraceInfo& trace =
3552
impl_->gtest_trace_stack()->GetElement(i);
3700
for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
3702
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
3553
3703
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3554
3704
<< " " << trace.message;
3606
3760
// We don't protect this under mutex_, as we only support calling it
3607
3761
// from the main thread.
3608
3762
int UnitTest::Run() {
3763
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
3764
// used for the duration of the program.
3765
impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
3609
3767
#if GTEST_HAS_SEH
3610
// Catch SEH-style exceptions.
3612
3768
const bool in_death_test_child_process =
3613
3769
internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3615
3771
// Either the user wants Google Test to catch exceptions thrown by the
3616
3772
// tests or this is executing in the context of death test child
3617
3773
// process. In either case the user does not want to see pop-up dialogs
3618
// about crashes - they are expected..
3619
if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3620
#if !GTEST_OS_WINDOWS_MOBILE
3774
// about crashes - they are expected.
3775
if (impl()->catch_exceptions() || in_death_test_child_process) {
3776
# if !GTEST_OS_WINDOWS_MOBILE
3621
3777
// SetErrorMode doesn't exist on CE.
3622
3778
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3623
3779
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3624
#endif // !GTEST_OS_WINDOWS_MOBILE
3780
# endif // !GTEST_OS_WINDOWS_MOBILE
3626
#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3782
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3627
3783
// Death test children can be terminated with _abort(). On Windows,
3628
3784
// _abort() can show a dialog with a warning message. This forces the
3629
3785
// abort message to go to stderr instead.
3630
3786
_set_error_mode(_OUT_TO_STDERR);
3633
#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3789
# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3634
3790
// In the debug version, Visual Studio pops up a separate dialog
3635
3791
// offering a choice to debug the aborted program. We need to suppress
3636
3792
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3857
4030
// test_case_name: name of the test case
4031
// type_param: the name of the test case's type parameter, or NULL if
4032
// this is not a typed or a type-parameterized test case.
3858
4033
// set_up_tc: pointer to the function that sets up the test case
3859
4034
// tear_down_tc: pointer to the function that tears down the test case
3860
4035
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3861
const char* comment,
4036
const char* type_param,
3862
4037
Test::SetUpTestCaseFunc set_up_tc,
3863
4038
Test::TearDownTestCaseFunc tear_down_tc) {
3864
4039
// Can we find a TestCase with the given name?
3865
TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name));
4040
const std::vector<TestCase*>::const_iterator test_case =
4041
std::find_if(test_cases_.begin(), test_cases_.end(),
4042
TestCaseNameIs(test_case_name));
3867
if (test_case != NULL)
4044
if (test_case != test_cases_.end())
3868
4045
return *test_case;
3870
4047
// No. Let's create one.
3871
4048
TestCase* const new_test_case =
3872
new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
4049
new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
3874
4051
// Is this a death test case?
3875
if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
4052
if (internal::UnitTestOptions::MatchesFilter(test_case_name,
3876
4053
kDeathTestCaseFilter)) {
3877
4054
// Yes. Inserts the test case after the last death test case
3878
4055
// defined so far. This only works when the test cases haven't
3879
4056
// been shuffled. Otherwise we may end up running a death test
3880
4057
// after a non-death test.
3881
test_cases_.Insert(new_test_case, ++last_death_test_case_);
4058
++last_death_test_case_;
4059
test_cases_.insert(test_cases_.begin() + last_death_test_case_,
3883
4062
// No. Appends to the end of the list.
3884
test_cases_.PushBack(new_test_case);
4063
test_cases_.push_back(new_test_case);
3887
test_case_indices_.PushBack(test_case_indices_.size());
4066
test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
3888
4067
return new_test_case;
3891
4070
// Helpers for setting up / tearing down the given environment. They
3892
// are for use in the Vector::ForEach() method.
4071
// are for use in the ForEach() function.
3893
4072
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3894
4073
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3896
4075
// Runs all tests in this UnitTest object, prints the result, and
3897
// returns 0 if all tests are successful, or 1 otherwise. If any
3898
// exception is thrown during a test on Windows, this test is
3899
// considered to be failed, but the rest of the tests will still be
3900
// run. (We disable exceptions on Linux and Mac OS X, so the issue
3901
// doesn't apply there.)
4076
// returns true if all tests are successful. If any exception is
4077
// thrown during a test, the test is considered to be failed, but the
4078
// rest of the tests will still be run.
3902
4080
// When parameterized tests are enabled, it expands and registers
3903
4081
// parameterized tests first in RegisterParameterizedTests().
3904
4082
// All other functions called from RunAllTests() may safely assume that
3905
4083
// parameterized tests are ready to be counted and run.
3906
int UnitTestImpl::RunAllTests() {
4084
bool UnitTestImpl::RunAllTests() {
3907
4085
// Makes sure InitGoogleTest() was called.
3908
4086
if (!GTestIsInitialized()) {
3910
4088
"\nThis test program did NOT call ::testing::InitGoogleTest "
3911
4089
"before calling RUN_ALL_TESTS(). Please fix it.\n");
3915
4093
// Do not run any test if the --help flag was specified.
3916
4094
if (g_help_flag)
3919
4097
// Repeats the call to the post-flag parsing initialization in case the
3920
4098
// user didn't call InitGoogleTest.
4234
4416
// the TestResult for the ad hoc test if no test is running.
4235
4417
TestResult* UnitTestImpl::current_test_result() {
4236
4418
return current_test_info_ ?
4237
current_test_info_->impl()->result() : &ad_hoc_test_result_;
4419
&(current_test_info_->result_) : &ad_hoc_test_result_;
4240
4422
// Shuffles all test cases, and the tests within each test case,
4241
4423
// making sure that death tests are still run first.
4242
4424
void UnitTestImpl::ShuffleTests() {
4243
4425
// Shuffles the death test cases.
4244
test_case_indices_.ShuffleRange(random(), 0, last_death_test_case_ + 1);
4426
ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4246
4428
// Shuffles the non-death test cases.
4247
test_case_indices_.ShuffleRange(random(), last_death_test_case_ + 1,
4248
test_cases_.size());
4429
ShuffleRange(random(), last_death_test_case_ + 1,
4430
static_cast<int>(test_cases_.size()), &test_case_indices_);
4250
4432
// Shuffles the tests inside each test case.
4251
for (int i = 0; i < test_cases_.size(); i++) {
4252
test_cases_.GetElement(i)->ShuffleTests(random());
4433
for (size_t i = 0; i < test_cases_.size(); i++) {
4434
test_cases_[i]->ShuffleTests(random());
4256
4438
// Restores the test cases and tests to their order before the first shuffle.
4257
4439
void UnitTestImpl::UnshuffleTests() {
4258
for (int i = 0; i < test_cases_.size(); i++) {
4440
for (size_t i = 0; i < test_cases_.size(); i++) {
4259
4441
// Unshuffles the tests in each test case.
4260
test_cases_.GetElement(i)->UnshuffleTests();
4442
test_cases_[i]->UnshuffleTests();
4261
4443
// Resets the index of each test case.
4262
test_case_indices_.GetMutableElement(i) = i;
4444
test_case_indices_[i] = static_cast<int>(i);
4266
// TestInfoImpl constructor. The new instance assumes ownership of the test
4268
TestInfoImpl::TestInfoImpl(TestInfo* parent,
4269
const char* test_case_name,
4271
const char* test_case_comment,
4272
const char* comment,
4273
TypeId fixture_class_id,
4274
internal::TestFactoryBase* factory) :
4276
test_case_name_(String(test_case_name)),
4277
name_(String(name)),
4278
test_case_comment_(String(test_case_comment)),
4279
comment_(String(comment)),
4280
fixture_class_id_(fixture_class_id),
4282
is_disabled_(false),
4283
matches_filter_(false),
4287
// TestInfoImpl destructor.
4288
TestInfoImpl::~TestInfoImpl() {
4292
// Returns the current OS stack trace as a String.
4448
// Returns the current OS stack trace as an std::string.
4294
4450
// The maximum number of stack frames to be included is specified by
4295
4451
// the gtest_stack_trace_depth flag. The skip_count parameter