Commit b007c54f authored by Abseil Team's avatar Abseil Team Committed by Copybara-Service
Browse files

Running clang-format over all of GoogleTest

A few tests are examining code locations and looking af the resulting line
numbers to verify that GoogleTest shows those to users correctly. Some of those
locations change when clang-format is run. For those locations, I've wrapped
portions in:
// clang-format off
...
// clang-format on

There may be other locations that are currently not tickled by running
clang-format.

PiperOrigin-RevId: 434844712
Change-Id: I3a9f0a6f39eff741c576b6de389bef9b1d11139d
parent 8a422b83
...@@ -29,26 +29,22 @@ ...@@ -29,26 +29,22 @@
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
#include <stdio.h>
#include "sample4.h" #include "sample4.h"
#include <stdio.h>
// Returns the current counter value, and increments it. // Returns the current counter value, and increments it.
int Counter::Increment() { int Counter::Increment() { return counter_++; }
return counter_++;
}
// Returns the current counter value, and decrements it. // Returns the current counter value, and decrements it.
// counter can not be less than 0, return 0 in this case // counter can not be less than 0, return 0 in this case
int Counter::Decrement() { int Counter::Decrement() {
if (counter_ == 0) { if (counter_ == 0) {
return counter_; return counter_;
} else { } else {
return counter_--; return counter_--;
} }
} }
// Prints the current counter value to STDOUT. // Prints the current counter value to STDOUT.
void Counter::Print() const { void Counter::Print() const { printf("%d", counter_); }
printf("%d", counter_);
}
...@@ -27,8 +27,8 @@ ...@@ -27,8 +27,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sample4.h" #include "sample4.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample teaches how to reuse a test fixture in multiple test // This sample teaches how to reuse a test fixture in multiple test
// cases by deriving sub-fixtures from it. // cases by deriving sub-fixtures from it.
// //
...@@ -45,9 +44,10 @@ ...@@ -45,9 +44,10 @@
#include <limits.h> #include <limits.h>
#include <time.h> #include <time.h>
#include "gtest/gtest.h"
#include "sample1.h" #include "sample1.h"
#include "sample3-inl.h" #include "sample3-inl.h"
#include "gtest/gtest.h"
namespace { namespace {
// In this sample, we want to ensure that every test finishes within // In this sample, we want to ensure that every test finishes within
// ~5 seconds. If a test takes longer to run, we consider it a // ~5 seconds. If a test takes longer to run, we consider it a
...@@ -81,7 +81,6 @@ class QuickTest : public testing::Test { ...@@ -81,7 +81,6 @@ class QuickTest : public testing::Test {
time_t start_time_; time_t start_time_;
}; };
// We derive a fixture named IntegerFunctionTest from the QuickTest // We derive a fixture named IntegerFunctionTest from the QuickTest
// fixture. All tests using this fixture will be automatically // fixture. All tests using this fixture will be automatically
// required to be quick. // required to be quick.
...@@ -90,7 +89,6 @@ class IntegerFunctionTest : public QuickTest { ...@@ -90,7 +89,6 @@ class IntegerFunctionTest : public QuickTest {
// Therefore the body is empty. // Therefore the body is empty.
}; };
// Now we can write tests in the IntegerFunctionTest test case. // Now we can write tests in the IntegerFunctionTest test case.
// Tests Factorial() // Tests Factorial()
...@@ -110,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) { ...@@ -110,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) {
EXPECT_EQ(40320, Factorial(8)); EXPECT_EQ(40320, Factorial(8));
} }
// Tests IsPrime() // Tests IsPrime()
TEST_F(IntegerFunctionTest, IsPrime) { TEST_F(IntegerFunctionTest, IsPrime) {
// Tests negative input. // Tests negative input.
...@@ -131,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) { ...@@ -131,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) {
EXPECT_TRUE(IsPrime(23)); EXPECT_TRUE(IsPrime(23));
} }
// The next test case (named "QueueTest") also needs to be quick, so // The next test case (named "QueueTest") also needs to be quick, so
// we derive another fixture from QuickTest. // we derive another fixture from QuickTest.
// //
...@@ -163,13 +159,10 @@ class QueueTest : public QuickTest { ...@@ -163,13 +159,10 @@ class QueueTest : public QuickTest {
Queue<int> q2_; Queue<int> q2_;
}; };
// Now, let's write tests using the QueueTest fixture. // Now, let's write tests using the QueueTest fixture.
// Tests the default constructor. // Tests the default constructor.
TEST_F(QueueTest, DefaultConstructor) { TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); }
EXPECT_EQ(0u, q0_.Size());
}
// Tests Dequeue(). // Tests Dequeue().
TEST_F(QueueTest, Dequeue) { TEST_F(QueueTest, Dequeue) {
......
...@@ -27,13 +27,11 @@ ...@@ -27,13 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to test common properties of multiple // This sample shows how to test common properties of multiple
// implementations of the same interface (aka interface tests). // implementations of the same interface (aka interface tests).
// The interface and its implementations are in this header. // The interface and its implementations are in this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
// First, we define some factory functions for creating instances of // First, we define some factory functions for creating instances of
...@@ -151,8 +149,7 @@ using testing::Types; ...@@ -151,8 +149,7 @@ using testing::Types;
// the PrimeTableTest fixture defined earlier: // the PrimeTableTest fixture defined earlier:
template <class T> template <class T>
class PrimeTableTest2 : public PrimeTableTest<T> { class PrimeTableTest2 : public PrimeTableTest<T> {};
};
// Then, declare the test case. The argument is the name of the test // Then, declare the test case. The argument is the name of the test
// fixture, and also the name of the test case (as usual). The _P // fixture, and also the name of the test case (as usual). The _P
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to test common properties of multiple // This sample shows how to test common properties of multiple
// implementations of an interface (aka interface tests) using // implementations of an interface (aka interface tests) using
// value-parameterized tests. Each test in the test case has // value-parameterized tests. Each test in the test case has
...@@ -36,7 +35,6 @@ ...@@ -36,7 +35,6 @@
// The interface and its implementations are in this header. // The interface and its implementations are in this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
...@@ -50,9 +48,7 @@ using ::testing::Values; ...@@ -50,9 +48,7 @@ using ::testing::Values;
// SetUp() method and delete them in TearDown() method. // SetUp() method and delete them in TearDown() method.
typedef PrimeTable* CreatePrimeTableFunc(); typedef PrimeTable* CreatePrimeTableFunc();
PrimeTable* CreateOnTheFlyPrimeTable() { PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); }
return new OnTheFlyPrimeTable();
}
template <size_t max_precalculated> template <size_t max_precalculated>
PrimeTable* CreatePreCalculatedPrimeTable() { PrimeTable* CreatePreCalculatedPrimeTable() {
......
...@@ -27,14 +27,12 @@ ...@@ -27,14 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to test code relying on some global flag variables. // This sample shows how to test code relying on some global flag variables.
// Combine() helps with generating all possible combinations of such flags, // Combine() helps with generating all possible combinations of such flags,
// and each test is given one combination as a parameter. // and each test is given one combination as a parameter.
// Use class definitions to test from this header. // Use class definitions to test from this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
...@@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable { ...@@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable {
int max_precalculated_; int max_precalculated_;
}; };
using ::testing::TestWithParam;
using ::testing::Bool; using ::testing::Bool;
using ::testing::Values;
using ::testing::Combine; using ::testing::Combine;
using ::testing::TestWithParam;
using ::testing::Values;
// To test all code paths for HybridPrimeTable we must test it with numbers // To test all code paths for HybridPrimeTable we must test it with numbers
// both within and outside PreCalculatedPrimeTable's capacity and also with // both within and outside PreCalculatedPrimeTable's capacity and also with
......
...@@ -26,7 +26,6 @@ ...@@ -26,7 +26,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to use Google Test listener API to implement // This sample shows how to use Google Test listener API to implement
// an alternative console output and how to use the UnitTest reflection API // an alternative console output and how to use the UnitTest reflection API
// to enumerate test suites and tests and to inspect their results. // to enumerate test suites and tests and to inspect their results.
...@@ -38,10 +37,10 @@ ...@@ -38,10 +37,10 @@
using ::testing::EmptyTestEventListener; using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestSuite;
using ::testing::TestEventListeners; using ::testing::TestEventListeners;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest; using ::testing::UnitTest;
namespace { namespace {
// Provides alternative output mode which produces minimal amount of // Provides alternative output mode which produces minimal amount of
...@@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener { ...@@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener {
// Called before a test starts. // Called before a test starts.
void OnTestStart(const TestInfo& test_info) override { void OnTestStart(const TestInfo& test_info) override {
fprintf(stdout, fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_suite_name(),
"*** Test %s.%s starting.\n",
test_info.test_suite_name(),
test_info.name()); test_info.name());
fflush(stdout); fflush(stdout);
} }
// Called after a failed assertion or a SUCCEED() invocation. // Called after a failed assertion or a SUCCEED() invocation.
void OnTestPartResult(const TestPartResult& test_part_result) override { void OnTestPartResult(const TestPartResult& test_part_result) override {
fprintf(stdout, fprintf(stdout, "%s in %s:%d\n%s\n",
"%s in %s:%d\n%s\n",
test_part_result.failed() ? "*** Failure" : "Success", test_part_result.failed() ? "*** Failure" : "Success",
test_part_result.file_name(), test_part_result.file_name(), test_part_result.line_number(),
test_part_result.line_number(),
test_part_result.summary()); test_part_result.summary());
fflush(stdout); fflush(stdout);
} }
// Called after a test ends. // Called after a test ends.
void OnTestEnd(const TestInfo& test_info) override { void OnTestEnd(const TestInfo& test_info) override {
fprintf(stdout, fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(),
"*** Test %s.%s ending.\n",
test_info.test_suite_name(),
test_info.name()); test_info.name());
fflush(stdout); fflush(stdout);
} }
...@@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) { ...@@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) {
} }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
bool terse_output = false; bool terse_output = false;
if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 ) if (argc > 1 && strcmp(argv[1], "--terse_output") == 0)
terse_output = true; terse_output = true;
else else
printf("%s\n", "Run this program with --terse_output to change the way " printf("%s\n",
"Run this program with --terse_output to change the way "
"it prints its output."); "it prints its output.");
UnitTest& unit_test = *UnitTest::GetInstance(); UnitTest& unit_test = *UnitTest::GetInstance();
...@@ -149,8 +143,7 @@ int main(int argc, char **argv) { ...@@ -149,8 +143,7 @@ int main(int argc, char **argv) {
} }
// Test that were meant to fail should not affect the test program outcome. // Test that were meant to fail should not affect the test program outcome.
if (unexpectedly_failed_tests == 0) if (unexpectedly_failed_tests == 0) ret_val = 0;
ret_val = 0;
return ret_val; return ret_val;
} }
...@@ -38,7 +38,6 @@ ...@@ -38,7 +38,6 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// The following lines pull in the real gtest *.cc files. // The following lines pull in the real gtest *.cc files.
#include "src/gtest.cc"
#include "src/gtest-assertion-result.cc" #include "src/gtest-assertion-result.cc"
#include "src/gtest-death-test.cc" #include "src/gtest-death-test.cc"
#include "src/gtest-filepath.cc" #include "src/gtest-filepath.cc"
...@@ -47,3 +46,4 @@ ...@@ -47,3 +46,4 @@
#include "src/gtest-printers.cc" #include "src/gtest-printers.cc"
#include "src/gtest-test-part.cc" #include "src/gtest-test-part.cc"
#include "src/gtest-typed-test.cc" #include "src/gtest-typed-test.cc"
#include "src/gtest.cc"
...@@ -33,8 +33,8 @@ ...@@ -33,8 +33,8 @@
#include "gtest/gtest-assertion-result.h" #include "gtest/gtest-assertion-result.h"
#include <utility>
#include <string> #include <string>
#include <utility>
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
...@@ -63,14 +63,10 @@ AssertionResult AssertionResult::operator!() const { ...@@ -63,14 +63,10 @@ AssertionResult AssertionResult::operator!() const {
} }
// Makes a successful assertion result. // Makes a successful assertion result.
AssertionResult AssertionSuccess() { AssertionResult AssertionSuccess() { return AssertionResult(true); }
return AssertionResult(true);
}
// Makes a failed assertion result. // Makes a failed assertion result.
AssertionResult AssertionFailure() { AssertionResult AssertionFailure() { return AssertionResult(false); }
return AssertionResult(false);
}
// Makes a failed assertion result with the given failure message. // Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << message. // Deprecated; use AssertionFailure() << message.
......
...@@ -35,49 +35,49 @@ ...@@ -35,49 +35,49 @@
#include <functional> #include <functional>
#include <utility> #include <utility>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/custom/gtest.h" #include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_OS_MAC #if GTEST_OS_MAC
# include <crt_externs.h> #include <crt_externs.h>
# endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
# include <errno.h> #include <errno.h>
# include <fcntl.h> #include <fcntl.h>
# include <limits.h> #include <limits.h>
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <signal.h> #include <signal.h>
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# include <stdarg.h> #include <stdarg.h>
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <windows.h>
# else #else
# include <sys/mman.h> #include <sys/mman.h>
# include <sys/wait.h> #include <sys/wait.h>
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_QNX #if GTEST_OS_QNX
# include <spawn.h> #include <spawn.h>
# endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
# if GTEST_OS_FUCHSIA #if GTEST_OS_FUCHSIA
# include <lib/fdio/fd.h> #include <lib/fdio/fd.h>
# include <lib/fdio/io.h> #include <lib/fdio/io.h>
# include <lib/fdio/spawn.h> #include <lib/fdio/spawn.h>
# include <lib/zx/channel.h> #include <lib/zx/channel.h>
# include <lib/zx/port.h> #include <lib/zx/port.h>
# include <lib/zx/process.h> #include <lib/zx/process.h>
# include <lib/zx/socket.h> #include <lib/zx/socket.h>
# include <zircon/processargs.h> #include <zircon/processargs.h>
# include <zircon/syscalls.h> #include <zircon/syscalls.h>
# include <zircon/syscalls/policy.h> #include <zircon/syscalls/policy.h>
# include <zircon/syscalls/port.h> #include <zircon/syscalls/port.h>
# endif // GTEST_OS_FUCHSIA #endif // GTEST_OS_FUCHSIA
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
...@@ -137,9 +137,9 @@ namespace internal { ...@@ -137,9 +137,9 @@ namespace internal {
// Valid only for fast death tests. Indicates the code is running in the // Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test. // child process of a fast style death test.
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
static bool g_in_fast_death_test_child = false; static bool g_in_fast_death_test_child = false;
# endif #endif
// Returns a Boolean value indicating whether the caller is currently // Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process. Tools such as // executing in the context of the death test child process. Tools such as
...@@ -147,13 +147,13 @@ static bool g_in_fast_death_test_child = false; ...@@ -147,13 +147,13 @@ static bool g_in_fast_death_test_child = false;
// tests. IMPORTANT: This is an internal utility. Using it may break the // tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it. // implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() { bool InDeathTestChild() {
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// On Windows and Fuchsia, death tests are thread-safe regardless of the value // On Windows and Fuchsia, death tests are thread-safe regardless of the value
// of the death_test_style flag. // of the death_test_style flag.
return !GTEST_FLAG_GET(internal_run_death_test).empty(); return !GTEST_FLAG_GET(internal_run_death_test).empty();
# else #else
if (GTEST_FLAG_GET(death_test_style) == "threadsafe") if (GTEST_FLAG_GET(death_test_style) == "threadsafe")
return !GTEST_FLAG_GET(internal_run_death_test).empty(); return !GTEST_FLAG_GET(internal_run_death_test).empty();
...@@ -165,40 +165,38 @@ bool InDeathTestChild() { ...@@ -165,40 +165,38 @@ bool InDeathTestChild() {
} // namespace internal } // namespace internal
// ExitedWithCode constructor. // ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
}
// ExitedWithCode function-call operator. // ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const { bool ExitedWithCode::operator()(int exit_status) const {
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
return exit_status == exit_code_; return exit_status == exit_code_;
# else #else
return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
} }
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// KilledBySignal constructor. // KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) { KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
}
// KilledBySignal function-call operator. // KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const { bool KilledBySignal::operator()(int exit_status) const {
# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) #if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
{ {
bool result; bool result;
if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
return result; return result;
} }
} }
# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) #endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
} }
# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
namespace internal { namespace internal {
...@@ -209,23 +207,23 @@ namespace internal { ...@@ -209,23 +207,23 @@ namespace internal {
static std::string ExitSummary(int exit_code) { static std::string ExitSummary(int exit_code) {
Message m; Message m;
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
m << "Exited with exit status " << exit_code; m << "Exited with exit status " << exit_code;
# else #else
if (WIFEXITED(exit_code)) { if (WIFEXITED(exit_code)) {
m << "Exited with exit status " << WEXITSTATUS(exit_code); m << "Exited with exit status " << WEXITSTATUS(exit_code);
} else if (WIFSIGNALED(exit_code)) { } else if (WIFSIGNALED(exit_code)) {
m << "Terminated by signal " << WTERMSIG(exit_code); m << "Terminated by signal " << WTERMSIG(exit_code);
} }
# ifdef WCOREDUMP #ifdef WCOREDUMP
if (WCOREDUMP(exit_code)) { if (WCOREDUMP(exit_code)) {
m << " (core dumped)"; m << " (core dumped)";
} }
# endif #endif
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
return m.GetString(); return m.GetString();
} }
...@@ -236,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) { ...@@ -236,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(exit_status); return !ExitedWithCode(0)(exit_status);
} }
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Generates a textual failure message when a death test finds more than // Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior // one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the // to executing the given statement. It is the responsibility of the
...@@ -257,7 +255,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) { ...@@ -257,7 +255,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) {
<< " this is the last message you see before your test times out."; << " this is the last message you see before your test times out.";
return msg.GetString(); return msg.GetString();
} }
# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Flag characters for reporting a death test that did not die. // Flag characters for reporting a death test that did not die.
static const char kDeathTestLived = 'L'; static const char kDeathTestLived = 'L';
...@@ -307,14 +305,14 @@ static void DeathTestAbort(const std::string& message) { ...@@ -307,14 +305,14 @@ static void DeathTestAbort(const std::string& message) {
// A replacement for CHECK that calls DeathTestAbort if the assertion // A replacement for CHECK that calls DeathTestAbort if the assertion
// fails. // fails.
# define GTEST_DEATH_TEST_CHECK_(expression) \ #define GTEST_DEATH_TEST_CHECK_(expression) \
do { \ do { \
if (!::testing::internal::IsTrue(expression)) { \ if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort( \ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \ ::testing::internal::StreamableToString(__LINE__) + \
+ #expression); \ ": " + #expression); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
...@@ -324,23 +322,23 @@ static void DeathTestAbort(const std::string& message) { ...@@ -324,23 +322,23 @@ static void DeathTestAbort(const std::string& message) {
// evaluates the expression as long as it evaluates to -1 and sets // evaluates the expression as long as it evaluates to -1 and sets
// errno to EINTR. If the expression evaluates to -1 but errno is // errno to EINTR. If the expression evaluates to -1 but errno is
// something other than EINTR, DeathTestAbort is called. // something other than EINTR, DeathTestAbort is called.
# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
do { \ do { \
int gtest_retval; \ int gtest_retval; \
do { \ do { \
gtest_retval = (expression); \ gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \ } while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \ if (gtest_retval == -1) { \
DeathTestAbort( \ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \ ::testing::internal::StreamableToString(__LINE__) + \
+ #expression + " != -1"); \ ": " + #expression + " != -1"); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno. // Returns the message describing the last system error in errno.
std::string GetLastErrnoDescription() { std::string GetLastErrnoDescription() {
return errno == 0 ? "" : posix::StrError(errno); return errno == 0 ? "" : posix::StrError(errno);
} }
// This is called from a death test parent process to read a failure // This is called from a death test parent process to read a failure
...@@ -373,8 +371,9 @@ static void FailFromInternalError(int fd) { ...@@ -373,8 +371,9 @@ static void FailFromInternalError(int fd) {
DeathTest::DeathTest() { DeathTest::DeathTest() {
TestInfo* const info = GetUnitTestImpl()->current_test_info(); TestInfo* const info = GetUnitTestImpl()->current_test_info();
if (info == nullptr) { if (info == nullptr) {
DeathTestAbort("Cannot run a death test outside of a TEST or " DeathTestAbort(
"TEST_F construct"); "Cannot run a death test outside of a TEST or "
"TEST_F construct");
} }
} }
...@@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() { ...@@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() {
set_read_fd(-1); set_read_fd(-1);
} }
std::string DeathTestImpl::GetErrorLogs() { std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }
return GetCapturedStderr();
}
// Signals that the death test code which should have exited, didn't. // Signals that the death test code which should have exited, didn't.
// Should be called only in a death test child process. // Should be called only in a death test child process.
...@@ -515,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) { ...@@ -515,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) {
// The parent process considers the death test to be a failure if // The parent process considers the death test to be a failure if
// it finds any data in our pipe. So, here we write a single flag byte // it finds any data in our pipe. So, here we write a single flag byte
// to the pipe, then exit. // to the pipe, then exit.
const char status_ch = const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived
reason == TEST_DID_NOT_DIE ? kDeathTestLived : : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew
reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; : kDeathTestReturned;
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
// We are leaking the descriptor here because on some platforms (i.e., // We are leaking the descriptor here because on some platforms (i.e.,
...@@ -536,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) { ...@@ -536,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) {
// much easier. // much easier.
static ::std::string FormatDeathTestOutput(const ::std::string& output) { static ::std::string FormatDeathTestOutput(const ::std::string& output) {
::std::string ret; ::std::string ret;
for (size_t at = 0; ; ) { for (size_t at = 0;;) {
const size_t line_end = output.find('\n', at); const size_t line_end = output.find('\n', at);
ret += "[ DEATH ] "; ret += "[ DEATH ] ";
if (line_end == ::std::string::npos) { if (line_end == ::std::string::npos) {
...@@ -571,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) { ...@@ -571,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) {
// the first failing condition, in the order given above, is the one that is // the first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string. // reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) { bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned()) if (!spawned()) return false;
return false;
const std::string error_message = GetErrorLogs(); const std::string error_message = GetErrorLogs();
...@@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) { ...@@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) {
switch (outcome()) { switch (outcome()) {
case LIVED: case LIVED:
buffer << " Result: failed to die.\n" buffer << " Result: failed to die.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case THREW: case THREW:
buffer << " Result: threw an exception.\n" buffer << " Result: threw an exception.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case RETURNED: case RETURNED:
buffer << " Result: illegal return in test statement.\n" buffer << " Result: illegal return in test statement.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case DIED: case DIED:
if (status_ok) { if (status_ok) {
...@@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) { ...@@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) {
} else { } else {
buffer << " Result: died but not with expected exit code:\n" buffer << " Result: died but not with expected exit code:\n"
<< " " << ExitSummary(status()) << "\n" << " " << ExitSummary(status()) << "\n"
<< "Actual msg:\n" << FormatDeathTestOutput(error_message); << "Actual msg:\n"
<< FormatDeathTestOutput(error_message);
} }
break; break;
case IN_PROGRESS: case IN_PROGRESS:
...@@ -621,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) { ...@@ -621,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
return success; return success;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the // WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are // specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the // always threadsafe, and Google Test considers the
...@@ -682,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl { ...@@ -682,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl {
// status, or 0 if no child process exists. As a side effect, sets the // status, or 0 if no child process exists. As a side effect, sets the
// outcome data member. // outcome data member.
int WindowsDeathTest::Wait() { int WindowsDeathTest::Wait() {
if (!spawned()) if (!spawned()) return 0;
return 0;
// Wait until the child either signals that it has acquired the write end // Wait until the child either signals that it has acquired the write end
// of the pipe or it dies. // of the pipe or it dies.
const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
switch (::WaitForMultipleObjects(2, switch (::WaitForMultipleObjects(2, wait_handles,
wait_handles,
FALSE, // Waits for any of the handles. FALSE, // Waits for any of the handles.
INFINITE)) { INFINITE)) {
case WAIT_OBJECT_0: case WAIT_OBJECT_0:
...@@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() { ...@@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() {
// returns immediately if the child has already exited, regardless of // returns immediately if the child has already exited, regardless of
// whether previous calls to WaitForMultipleObjects synchronized on this // whether previous calls to WaitForMultipleObjects synchronized on this
// handle or not. // handle or not.
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), ::WaitForSingleObject(child_handle_.Get(), INFINITE));
INFINITE));
DWORD status_code; DWORD status_code;
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
...@@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { ...@@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
nullptr, TRUE}; nullptr, TRUE};
HANDLE read_handle, write_handle; HANDLE read_handle, write_handle;
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, &handles_are_inheritable,
0) // Default buffer size. 0) // Default buffer size.
!= FALSE); != FALSE);
set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), set_read_fd(
O_RDONLY)); ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
write_handle_.Reset(write_handle); write_handle_.Reset(write_handle);
event_handle_.Reset(::CreateEvent( event_handle_.Reset(::CreateEvent(
&handles_are_inheritable, &handles_are_inheritable,
...@@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { ...@@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
executable_path, executable_path,
_MAX_PATH)); _MAX_PATH));
std::string command_line = std::string command_line = std::string(::GetCommandLineA()) + " " +
std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + filter_flag + " \"" + internal_flag + "\"";
internal_flag + "\"";
DeathTest::set_last_death_test_message(""); DeathTest::set_last_death_test_message("");
...@@ -812,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { ...@@ -812,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
return OVERSEE_TEST; return OVERSEE_TEST;
} }
# elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
class FuchsiaDeathTest : public DeathTestImpl { class FuchsiaDeathTest : public DeathTestImpl {
public: public:
...@@ -858,18 +854,13 @@ class Arguments { ...@@ -858,18 +854,13 @@ class Arguments {
template <typename Str> template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) { void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); i != arguments.end(); ++i) {
++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
} }
} }
char* const* Argv() { char* const* Argv() { return &args_[0]; }
return &args_[0];
}
int size() { int size() { return static_cast<int>(args_.size()) - 1; }
return static_cast<int>(args_.size()) - 1;
}
private: private:
std::vector<char*> args_; std::vector<char*> args_;
...@@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() { ...@@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() {
const int kSocketKey = 1; const int kSocketKey = 1;
const int kExceptionKey = 2; const int kExceptionKey = 2;
if (!spawned()) if (!spawned()) return 0;
return 0;
// Create a port to wait for socket/task/exception events. // Create a port to wait for socket/task/exception events.
zx_status_t status_zx; zx_status_t status_zx;
...@@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() { ...@@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the child process to terminate. // Register to wait for the child process to terminate.
status_zx = child_process_.wait_async( status_zx =
port, kProcessKey, ZX_PROCESS_TERMINATED, 0); child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the socket to be readable or closed. // Register to wait for the socket to be readable or closed.
...@@ -903,8 +893,8 @@ int FuchsiaDeathTest::Wait() { ...@@ -903,8 +893,8 @@ int FuchsiaDeathTest::Wait() {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for an exception. // Register to wait for an exception.
status_zx = exception_channel_.wait_async( status_zx = exception_channel_.wait_async(port, kExceptionKey,
port, kExceptionKey, ZX_CHANNEL_READABLE, 0); ZX_CHANNEL_READABLE, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
bool process_terminated = false; bool process_terminated = false;
...@@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() { ...@@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() {
size_t old_length = captured_stderr_.length(); size_t old_length = captured_stderr_.length();
size_t bytes_read = 0; size_t bytes_read = 0;
captured_stderr_.resize(old_length + kBufferSize); captured_stderr_.resize(old_length + kBufferSize);
status_zx = stderr_socket_.read( status_zx =
0, &captured_stderr_.front() + old_length, kBufferSize, stderr_socket_.read(0, &captured_stderr_.front() + old_length,
&bytes_read); kBufferSize, &bytes_read);
captured_stderr_.resize(old_length + bytes_read); captured_stderr_.resize(old_length + bytes_read);
} while (status_zx == ZX_OK); } while (status_zx == ZX_OK);
if (status_zx == ZX_ERR_PEER_CLOSED) { if (status_zx == ZX_ERR_PEER_CLOSED) {
...@@ -992,11 +982,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { ...@@ -992,11 +982,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
"filter=" + info->test_suite_name() + "." + "filter=" + info->test_suite_name() + "." +
info->name(); info->name();
const std::string internal_flag = const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" kInternalRunDeathTestFlag + "=" + file_ +
+ file_ + "|" "|" + StreamableToString(line_) + "|" +
+ StreamableToString(line_) + "|" StreamableToString(death_test_index);
+ StreamableToString(death_test_index);
Arguments args; Arguments args;
args.AddArguments(GetInjectableArgvs()); args.AddArguments(GetInjectableArgvs());
args.AddArgument(filter_flag.c_str()); args.AddArgument(filter_flag.c_str());
...@@ -1019,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { ...@@ -1019,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
// Create a socket pair will be used to receive the child process' stderr. // Create a socket pair will be used to receive the child process' stderr.
zx::socket stderr_producer_socket; zx::socket stderr_producer_socket;
status = status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
GTEST_DEATH_TEST_CHECK_(status >= 0); GTEST_DEATH_TEST_CHECK_(status >= 0);
int stderr_producer_fd = -1; int stderr_producer_fd = -1;
status = status =
...@@ -1037,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { ...@@ -1037,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
// Create a child job. // Create a child job.
zx_handle_t child_job = ZX_HANDLE_INVALID; zx_handle_t child_job = ZX_HANDLE_INVALID;
status = zx_job_create(zx_job_default(), 0, & child_job); status = zx_job_create(zx_job_default(), 0, &child_job);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
zx_policy_basic_t policy; zx_policy_basic_t policy;
policy.condition = ZX_POL_NEW_ANY; policy.condition = ZX_POL_NEW_ANY;
policy.policy = ZX_POL_ACTION_ALLOW; policy.policy = ZX_POL_ACTION_ALLOW;
status = zx_job_set_policy( status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,
child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); &policy, 1);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Create an exception channel attached to the |child_job|, to allow // Create an exception channel attached to the |child_job|, to allow
// us to suppress the system default exception handler from firing. // us to suppress the system default exception handler from firing.
status = status = zx_task_create_exception_channel(
zx_task_create_exception_channel( child_job, 0, exception_channel_.reset_and_get_address());
child_job, 0, exception_channel_.reset_and_get_address());
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Spawn the child process. // Spawn the child process.
status = fdio_spawn_etc( status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, args.Argv(), nullptr, 2, spawn_actions,
2, spawn_actions, child_process_.reset_and_get_address(), nullptr); child_process_.reset_and_get_address(), nullptr);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
set_spawned(true); set_spawned(true);
return OVERSEE_TEST; return OVERSEE_TEST;
} }
std::string FuchsiaDeathTest::GetErrorLogs() { std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }
return captured_stderr_;
}
#else // We are neither on Windows, nor on Fuchsia. #else // We are neither on Windows, nor on Fuchsia.
...@@ -1096,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement, ...@@ -1096,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement,
// status, or 0 if no child process exists. As a side effect, sets the // status, or 0 if no child process exists. As a side effect, sets the
// outcome data member. // outcome data member.
int ForkingDeathTest::Wait() { int ForkingDeathTest::Wait() {
if (!spawned()) if (!spawned()) return 0;
return 0;
ReadAndInterpretStatusByte(); ReadAndInterpretStatusByte();
...@@ -1176,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest { ...@@ -1176,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest {
private: private:
static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
::std::vector<std::string> args = GetInjectableArgvs(); ::std::vector<std::string> args = GetInjectableArgvs();
# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) #if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
::std::vector<std::string> extra_args = ::std::vector<std::string> extra_args =
GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
args.insert(args.end(), extra_args.begin(), extra_args.end()); args.insert(args.end(), extra_args.begin(), extra_args.end());
# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) #endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
return args; return args;
} }
// The name of the file in which the death test is located. // The name of the file in which the death test is located.
...@@ -1207,14 +1191,11 @@ class Arguments { ...@@ -1207,14 +1191,11 @@ class Arguments {
template <typename Str> template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) { void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); i != arguments.end(); ++i) {
++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
} }
} }
char* const* Argv() { char* const* Argv() { return &args_[0]; }
return &args_[0];
}
private: private:
std::vector<char*> args_; std::vector<char*> args_;
...@@ -1227,9 +1208,9 @@ struct ExecDeathTestArgs { ...@@ -1227,9 +1208,9 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe int close_fd; // File descriptor to close; the read end of a pipe
}; };
# if GTEST_OS_QNX #if GTEST_OS_QNX
extern "C" char** environ; extern "C" char** environ;
# else // GTEST_OS_QNX #else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process. // The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid // This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions. // any potentially unsafe operations like malloc or libc functions.
...@@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) { ...@@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + DeathTestAbort(std::string("chdir(\"") + original_dir +
GetLastErrnoDescription()); "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
...@@ -1256,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) { ...@@ -1256,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) {
// one path separator. // one path separator.
execv(args->argv[0], args->argv); execv(args->argv[0], args->argv);
DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " + DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " + original_dir + " failed: " + GetLastErrnoDescription());
GetLastErrnoDescription());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
# endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
# if GTEST_HAS_CLONE #if GTEST_HAS_CLONE
// Two utility routines that together determine the direction the stack // Two utility routines that together determine the direction the stack
// grows. // grows.
// This could be accomplished more elegantly by a single recursive // This could be accomplished more elegantly by a single recursive
...@@ -1296,7 +1276,7 @@ static bool StackGrowsDown() { ...@@ -1296,7 +1276,7 @@ static bool StackGrowsDown() {
StackLowerThanAddress(&dummy, &result); StackLowerThanAddress(&dummy, &result);
return result; return result;
} }
# endif // GTEST_HAS_CLONE #endif // GTEST_HAS_CLONE
// Spawns a child process with the same executable as the current process in // Spawns a child process with the same executable as the current process in
// a thread-safe manner and instructs it to run the death test. The // a thread-safe manner and instructs it to run the death test. The
...@@ -1306,10 +1286,10 @@ static bool StackGrowsDown() { ...@@ -1306,10 +1286,10 @@ static bool StackGrowsDown() {
// spawn(2) there instead. The function dies with an error message if // spawn(2) there instead. The function dies with an error message if
// anything goes wrong. // anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
ExecDeathTestArgs args = { argv, close_fd }; ExecDeathTestArgs args = {argv, close_fd};
pid_t child_pid = -1; pid_t child_pid = -1;
# if GTEST_OS_QNX #if GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child // Obtains the current directory and sets it to be closed in the child
// process. // process.
const int cwd_fd = open(".", O_RDONLY); const int cwd_fd = open(".", O_RDONLY);
...@@ -1322,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ...@@ -1322,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + DeathTestAbort(std::string("chdir(\"") + original_dir +
GetLastErrnoDescription()); "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
int fd_flags; int fd_flags;
// Set close_fd to be closed after spawn. // Set close_fd to be closed after spawn.
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, GTEST_DEATH_TEST_CHECK_SYSCALL_(
fd_flags | FD_CLOEXEC)); fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0}; struct inheritance inherit = {0};
// spawn is a system call. // spawn is a system call.
child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ); child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
...@@ -1339,8 +1319,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ...@@ -1339,8 +1319,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
# else // GTEST_OS_QNX #else // GTEST_OS_QNX
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing, // When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete. // it after the call to fork()/clone() is complete.
...@@ -1349,11 +1329,11 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ...@@ -1349,11 +1329,11 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask); sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN; ignore_sigprof_action.sa_handler = SIG_IGN;
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( GTEST_DEATH_TEST_CHECK_SYSCALL_(
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# if GTEST_HAS_CLONE #if GTEST_HAS_CLONE
const bool use_fork = GTEST_FLAG_GET(death_test_use_fork); const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);
if (!use_fork) { if (!use_fork) {
...@@ -1373,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ...@@ -1373,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
const size_t kMaxStackAlignment = 64; const size_t kMaxStackAlignment = 64;
void* const stack_top = void* const stack_top =
static_cast<char*>(stack) + static_cast<char*>(stack) +
(stack_grows_down ? stack_size - kMaxStackAlignment : 0); (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
static_cast<size_t>(stack_size) > kMaxStackAlignment && static_cast<size_t>(stack_size) > kMaxStackAlignment &&
reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0); reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
...@@ -1382,19 +1362,19 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ...@@ -1382,19 +1362,19 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
} }
# else #else
const bool use_fork = true; const bool use_fork = true;
# endif // GTEST_HAS_CLONE #endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) { if (use_fork && (child_pid = fork()) == 0) {
ExecDeathTestChildMain(&args); ExecDeathTestChildMain(&args);
_exit(0); _exit(0);
} }
# endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_( GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, nullptr)); sigaction(SIGPROF, &saved_sigprof_action, nullptr));
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_(child_pid != -1); GTEST_DEATH_TEST_CHECK_(child_pid != -1);
return child_pid; return child_pid;
...@@ -1450,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { ...@@ -1450,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
return OVERSEE_TEST; return OVERSEE_TEST;
} }
# endif // !GTEST_OS_WINDOWS #endif // !GTEST_OS_WINDOWS
// Creates a concrete DeathTest-derived class that depends on the // Creates a concrete DeathTest-derived class that depends on the
// --gtest_death_test_style flag, and sets the pointer pointed to // --gtest_death_test_style flag, and sets the pointer pointed to
...@@ -1464,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement, ...@@ -1464,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement,
UnitTestImpl* const impl = GetUnitTestImpl(); UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag = const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag(); impl->internal_run_death_test_flag();
const int death_test_index = impl->current_test_info() const int death_test_index =
->increment_death_test_count(); impl->current_test_info()->increment_death_test_count();
if (flag != nullptr) { if (flag != nullptr) {
if (death_test_index > flag->index()) { if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message( DeathTest::set_last_death_test_message(
"Death test count (" + StreamableToString(death_test_index) "Death test count (" + StreamableToString(death_test_index) +
+ ") somehow exceeded expected maximum (" ") somehow exceeded expected maximum (" +
+ StreamableToString(flag->index()) + ")"); StreamableToString(flag->index()) + ")");
return false; return false;
} }
...@@ -1483,21 +1463,21 @@ bool DefaultDeathTestFactory::Create(const char* statement, ...@@ -1483,21 +1463,21 @@ bool DefaultDeathTestFactory::Create(const char* statement,
} }
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") { GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, std::move(matcher), file, line); *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
} }
# elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") { GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
} }
# else #else
if (GTEST_FLAG_GET(death_test_style) == "threadsafe") { if (GTEST_FLAG_GET(death_test_style) == "threadsafe") {
*test = new ExecDeathTest(statement, std::move(matcher), file, line); *test = new ExecDeathTest(statement, std::move(matcher), file, line);
...@@ -1505,7 +1485,7 @@ bool DefaultDeathTestFactory::Create(const char* statement, ...@@ -1505,7 +1485,7 @@ bool DefaultDeathTestFactory::Create(const char* statement,
*test = new NoExecDeathTest(statement, std::move(matcher)); *test = new NoExecDeathTest(statement, std::move(matcher));
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
else { // NOLINT - this is more readable than unbalanced brackets inside #if. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
DeathTest::set_last_death_test_message("Unknown death test style \"" + DeathTest::set_last_death_test_message("Unknown death test style \"" +
...@@ -1517,16 +1497,16 @@ bool DefaultDeathTestFactory::Create(const char* statement, ...@@ -1517,16 +1497,16 @@ bool DefaultDeathTestFactory::Create(const char* statement,
return true; return true;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters, // Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe // signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only. // handle. This function is called in the child process only.
static int GetStatusFileDescriptor(unsigned int parent_process_id, static int GetStatusFileDescriptor(unsigned int parent_process_id,
size_t write_handle_as_size_t, size_t write_handle_as_size_t,
size_t event_handle_as_size_t) { size_t event_handle_as_size_t) {
AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
FALSE, // Non-inheritable. FALSE, // Non-inheritable.
parent_process_id)); parent_process_id));
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
DeathTestAbort("Unable to open parent process " + DeathTestAbort("Unable to open parent process " +
StreamableToString(parent_process_id)); StreamableToString(parent_process_id));
...@@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, ...@@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
const HANDLE write_handle = const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
reinterpret_cast<HANDLE>(write_handle_as_size_t);
HANDLE dup_write_handle; HANDLE dup_write_handle;
// The newly initialized handle is accessible only in the parent // The newly initialized handle is accessible only in the parent
...@@ -1557,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, ...@@ -1557,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
HANDLE dup_event_handle; HANDLE dup_event_handle;
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
::GetCurrentProcess(), &dup_event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
0x0,
FALSE,
DUPLICATE_SAME_ACCESS)) { DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the event handle " + DeathTestAbort("Unable to duplicate the event handle " +
StreamableToString(event_handle_as_size_t) + StreamableToString(event_handle_as_size_t) +
...@@ -1581,7 +1558,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, ...@@ -1581,7 +1558,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
return write_fd; return write_fd;
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Returns a newly created InternalRunDeathTestFlag object with fields // Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if // initialized from the GTEST_FLAG(internal_run_death_test) flag if
...@@ -1597,45 +1574,41 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { ...@@ -1597,45 +1574,41 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields); SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);
int write_fd = -1; int write_fd = -1;
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
unsigned int parent_process_id = 0; unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0; size_t write_handle_as_size_t = 0;
size_t event_handle_as_size_t = 0; size_t event_handle_as_size_t = 0;
if (fields.size() != 6 if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index) ||
|| !ParseNaturalNumber(fields[2], &index) !ParseNaturalNumber(fields[3], &parent_process_id) ||
|| !ParseNaturalNumber(fields[3], &parent_process_id) !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t) !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
write_fd = GetStatusFileDescriptor(parent_process_id, write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
write_handle_as_size_t,
event_handle_as_size_t); event_handle_as_size_t);
# elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
if (fields.size() != 3 if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index)) {
|| !ParseNaturalNumber(fields[2], &index)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
# else #else
if (fields.size() != 4 if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index) ||
|| !ParseNaturalNumber(fields[2], &index) !ParseNaturalNumber(fields[3], &write_fd)) {
|| !ParseNaturalNumber(fields[3], &write_fd)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
} }
......
...@@ -30,29 +30,31 @@ ...@@ -30,29 +30,31 @@
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
#include <stdlib.h> #include <stdlib.h>
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> #include <windows.h>
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> #include <direct.h>
# include <io.h> #include <io.h>
#else #else
# include <limits.h> #include <limits.h>
# include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE #include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# define GTEST_PATH_MAX_ _MAX_PATH #define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX) #elif defined(PATH_MAX)
# define GTEST_PATH_MAX_ PATH_MAX #define GTEST_PATH_MAX_ PATH_MAX
#elif defined(_XOPEN_PATH_MAX) #elif defined(_XOPEN_PATH_MAX)
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
#else #else
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX #define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
namespace testing { namespace testing {
...@@ -66,16 +68,16 @@ namespace internal { ...@@ -66,16 +68,16 @@ namespace internal {
const char kPathSeparator = '\\'; const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparator = '/';
const char kAlternatePathSeparatorString[] = "/"; const char kAlternatePathSeparatorString[] = "/";
# if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use // Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least // the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback. // provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\"; const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff; const DWORD kInvalidFileAttributes = 0xffffffff;
# else #else
const char kCurrentDirectoryString[] = ".\\"; const char kCurrentDirectoryString[] = ".\\";
# endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
#else #else
const char kPathSeparator = '/'; const char kPathSeparator = '/';
const char kCurrentDirectoryString[] = "./"; const char kCurrentDirectoryString[] = "./";
...@@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() { ...@@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() {
// something reasonable. // something reasonable.
return FilePath(kCurrentDirectoryString); return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else #else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
char* result = getcwd(cwd, sizeof(cwd)); char* result = getcwd(cwd, sizeof(cwd));
# if GTEST_OS_NACL #if GTEST_OS_NACL
// getcwd will likely fail in NaCl due to the sandbox, so return something // getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd, // reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected. // however, so fallback only when failure is detected.
return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
# endif // GTEST_OS_NACL #endif // GTEST_OS_NACL
return FilePath(result == nullptr ? "" : cwd); return FilePath(result == nullptr ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} }
...@@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() { ...@@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() {
FilePath FilePath::RemoveExtension(const char* extension) const { FilePath FilePath::RemoveExtension(const char* extension) const {
const std::string dot_extension = std::string(".") + extension; const std::string dot_extension = std::string(".") + extension;
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(pathname_.substr( return FilePath(
0, pathname_.length() - dot_extension.length())); pathname_.substr(0, pathname_.length() - dot_extension.length()));
} }
return *this; return *this;
} }
...@@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const { ...@@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const {
// than zero (e.g., 12), returns "dir/test_12.xml". // than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /. // On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory, FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name, const FilePath& base_name, int number,
int number,
const char* extension) { const char* extension) {
std::string file; std::string file;
if (number == 0) { if (number == 0) {
file = base_name.string() + "." + extension; file = base_name.string() + "." + extension;
} else { } else {
file = base_name.string() + "_" + StreamableToString(number) file =
+ "." + extension; base_name.string() + "_" + StreamableToString(number) + "." + extension;
} }
return ConcatPaths(directory, FilePath(file)); return ConcatPaths(directory, FilePath(file));
} }
...@@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory, ...@@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
// On Windows, uses \ as the separator rather than /. // On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory, FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) { const FilePath& relative_path) {
if (directory.IsEmpty()) if (directory.IsEmpty()) return relative_path;
return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator()); const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(dir.string() + kPathSeparator + relative_path.string()); return FilePath(dir.string() + kPathSeparator + relative_path.string());
} }
...@@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const { ...@@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode); const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode; delete[] unicode;
return attributes != kInvalidFileAttributes; return attributes != kInvalidFileAttributes;
#else #else
posix::StatStruct file_stat{}; posix::StatStruct file_stat{};
...@@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const { ...@@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on // Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\"). // Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this : const FilePath& path(IsRootDirectory() ? *this
RemoveTrailingPathSeparator()); : RemoveTrailingPathSeparator());
#else #else
const FilePath& path(*this); const FilePath& path(*this);
#endif #endif
...@@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const { ...@@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode); const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode; delete[] unicode;
if ((attributes != kInvalidFileAttributes) && if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) { (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true; result = true;
} }
#else #else
posix::StatStruct file_stat{}; posix::StatStruct file_stat{};
result = posix::Stat(path.c_str(), &file_stat) == 0 && result =
posix::IsDir(file_stat); posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
return result; return result;
...@@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const { ...@@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const {
const char* const name = pathname_.c_str(); const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
return pathname_.length() >= 3 && return pathname_.length() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') || ((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) && (name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' && name[1] == ':' && IsPathSeparator(name[2]);
IsPathSeparator(name[2]);
#else #else
return IsPathSeparator(name[0]); return IsPathSeparator(name[0]);
#endif #endif
...@@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const { ...@@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const {
FilePath removed_sep(this->RemoveTrailingPathSeparator()); FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1; int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete [] unicode; delete[] unicode;
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str()); int result = _mkdir(pathname_.c_str());
#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
...@@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const { ...@@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const {
// name, otherwise return the name string unmodified. // name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /. // On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const { FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory() return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this;
: *this;
} }
// Removes any redundant separators that might be in the pathname. // Removes any redundant separators that might be in the pathname.
......
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
#ifndef _WIN32_WCE #ifndef _WIN32_WCE
# include <errno.h> #include <errno.h>
#endif // !_WIN32_WCE #endif // !_WIN32_WCE
#include <stddef.h> #include <stddef.h>
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
...@@ -50,16 +50,16 @@ ...@@ -50,16 +50,16 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT #include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT #include <netdb.h> // NOLINT
#endif #endif
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */) /* class A needs to have dll-interface to be used by clients of class B */)
...@@ -109,15 +109,16 @@ GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value); ...@@ -109,15 +109,16 @@ GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
// Returns a random seed in range [1, kMaxRandomSeed] based on the // Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value. // given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
const unsigned int raw_seed = (random_seed_flag == 0) ? const unsigned int raw_seed =
static_cast<unsigned int>(GetTimeInMillis()) : (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
static_cast<unsigned int>(random_seed_flag); : static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type. // it's easy to type.
const int normalized_seed = const int normalized_seed =
static_cast<int>((raw_seed - 1U) % static_cast<int>((raw_seed - 1U) %
static_cast<unsigned int>(kMaxRandomSeed)) + 1; static_cast<unsigned int>(kMaxRandomSeed)) +
1;
return normalized_seed; return normalized_seed;
} }
...@@ -261,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val); ...@@ -261,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
// returns true if and only if the test should be run on this shard. The test id // returns true if and only if the test should be run on this shard. The test id
// is some arbitrary but unique non-negative integer assigned to each test // is some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards. // method. Assumes that 0 <= shard_index < total_shards.
GTEST_API_ bool ShouldRunTestOnShard( GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
int total_shards, int shard_index, int test_id); int test_id);
// STL container utilities. // STL container utilities.
...@@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) { ...@@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) {
// Solaris has a non-standard signature. // Solaris has a non-standard signature.
int count = 0; int count = 0;
for (auto it = c.begin(); it != c.end(); ++it) { for (auto it = c.begin(); it != c.end(); ++it) {
if (predicate(*it)) if (predicate(*it)) ++count;
++count;
} }
return count; return count;
} }
...@@ -459,7 +459,7 @@ struct TraceInfo { ...@@ -459,7 +459,7 @@ struct TraceInfo {
// This is the default global test part result reporter used in UnitTestImpl. // This is the default global test part result reporter used in UnitTestImpl.
// This class should only be used by UnitTestImpl. // This class should only be used by UnitTestImpl.
class DefaultGlobalTestPartResultReporter class DefaultGlobalTestPartResultReporter
: public TestPartResultReporterInterface { : public TestPartResultReporterInterface {
public: public:
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. Reports the test part // Implements the TestPartResultReporterInterface. Reports the test part
...@@ -728,9 +728,7 @@ class GTEST_API_ UnitTestImpl { ...@@ -728,9 +728,7 @@ class GTEST_API_ UnitTestImpl {
} }
// Clears the results of ad-hoc test assertions. // Clears the results of ad-hoc test assertions.
void ClearAdHocTestResult() { void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
ad_hoc_test_result_.Clear();
}
// Adds a TestProperty to the current TestResult object when invoked in a // Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test suite, or to the global property set. If the // context of a test or a test suite, or to the global property set. If the
...@@ -738,10 +736,7 @@ class GTEST_API_ UnitTestImpl { ...@@ -738,10 +736,7 @@ class GTEST_API_ UnitTestImpl {
// updated. // updated.
void RecordProperty(const TestProperty& test_property); void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding { enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL
};
// Matches the full name of each test against the user-specified // Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the // filter to decide whether the test should run, then records the
...@@ -970,8 +965,9 @@ GTEST_API_ bool IsValidEscape(char ch); ...@@ -970,8 +965,9 @@ GTEST_API_ bool IsValidEscape(char ch);
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead( GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
bool escaped, char ch, char repeat, const char* regex, const char* str); char repeat, const char* regex,
const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
#endif // GTEST_USES_SIMPLE_RE #endif // GTEST_USES_SIMPLE_RE
...@@ -1073,8 +1069,7 @@ class StreamingListener : public EmptyTestEventListener { ...@@ -1073,8 +1069,7 @@ class StreamingListener : public EmptyTestEventListener {
} }
~SocketWriter() override { ~SocketWriter() override {
if (sockfd_ != -1) if (sockfd_ != -1) CloseConnection();
CloseConnection();
} }
// Sends a string to the socket. // Sends a string to the socket.
...@@ -1084,9 +1079,8 @@ class StreamingListener : public EmptyTestEventListener { ...@@ -1084,9 +1079,8 @@ class StreamingListener : public EmptyTestEventListener {
const auto len = static_cast<size_t>(message.length()); const auto len = static_cast<size_t>(message.length());
if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) { if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
GTEST_LOG_(WARNING) GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
<< "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_;
<< host_name_ << ":" << port_num_;
} }
} }
...@@ -1119,7 +1113,9 @@ class StreamingListener : public EmptyTestEventListener { ...@@ -1119,7 +1113,9 @@ class StreamingListener : public EmptyTestEventListener {
} }
explicit StreamingListener(AbstractSocketWriter* socket_writer) explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); } : socket_writer_(socket_writer) {
Start();
}
void OnTestProgramStart(const UnitTest& /* unit_test */) override { void OnTestProgramStart(const UnitTest& /* unit_test */) override {
SendLn("event=TestProgramStart"); SendLn("event=TestProgramStart");
...@@ -1142,9 +1138,9 @@ class StreamingListener : public EmptyTestEventListener { ...@@ -1142,9 +1138,9 @@ class StreamingListener : public EmptyTestEventListener {
void OnTestIterationEnd(const UnitTest& unit_test, void OnTestIterationEnd(const UnitTest& unit_test,
int /* iteration */) override { int /* iteration */) override {
SendLn("event=TestIterationEnd&passed=" + SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
FormatBool(unit_test.Passed()) + "&elapsed_time=" + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
StreamableToString(unit_test.elapsed_time()) + "ms"); "ms");
} }
// Note that "event=TestCaseStart" is a wire format and has to remain // Note that "event=TestCaseStart" is a wire format and has to remain
...@@ -1167,8 +1163,7 @@ class StreamingListener : public EmptyTestEventListener { ...@@ -1167,8 +1163,7 @@ class StreamingListener : public EmptyTestEventListener {
void OnTestEnd(const TestInfo& test_info) override { void OnTestEnd(const TestInfo& test_info) override {
SendLn("event=TestEnd&passed=" + SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
"&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms"); StreamableToString((test_info.result())->elapsed_time()) + "ms");
} }
......
...@@ -32,12 +32,13 @@ ...@@ -32,12 +32,13 @@
// This file implements just enough of the matcher interface to allow // This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument. // EXPECT_DEATH and friends to accept a matcher argument.
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-matchers.h" #include "gtest/gtest-matchers.h"
#include <string> #include <string>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
namespace testing { namespace testing {
// Constructs a matcher that matches a const std::string& whose value is // Constructs a matcher that matches a const std::string& whose value is
......
...@@ -27,61 +27,62 @@ ...@@ -27,61 +27,62 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include <limits.h> #include <limits.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <cstdint> #include <cstdint>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <io.h>
# include <io.h> #include <sys/stat.h>
# include <sys/stat.h> #include <windows.h>
# include <map> // Used in ThreadLocal.
# ifdef _MSC_VER #include <map> // Used in ThreadLocal.
# include <crtdbg.h> #ifdef _MSC_VER
# endif // _MSC_VER #include <crtdbg.h>
#endif // _MSC_VER
#else #else
# include <unistd.h> #include <unistd.h>
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC #if GTEST_OS_MAC
# include <mach/mach_init.h> #include <mach/mach_init.h>
# include <mach/task.h> #include <mach/task.h>
# include <mach/vm_map.h> #include <mach/vm_map.h>
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD || GTEST_OS_OPENBSD GTEST_OS_NETBSD || GTEST_OS_OPENBSD
# include <sys/sysctl.h> #include <sys/sysctl.h>
# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
# include <sys/user.h> #include <sys/user.h>
# endif #endif
#endif #endif
#if GTEST_OS_QNX #if GTEST_OS_QNX
# include <devctl.h> #include <devctl.h>
# include <fcntl.h> #include <fcntl.h>
# include <sys/procfs.h> #include <sys/procfs.h>
#endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
#if GTEST_OS_AIX #if GTEST_OS_AIX
# include <procinfo.h> #include <procinfo.h>
# include <sys/types.h> #include <sys/types.h>
#endif // GTEST_OS_AIX #endif // GTEST_OS_AIX
#if GTEST_OS_FUCHSIA #if GTEST_OS_FUCHSIA
# include <zircon/process.h> #include <zircon/process.h>
# include <zircon/syscalls.h> #include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA #endif // GTEST_OS_FUCHSIA
#include "gtest/gtest-spi.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
...@@ -131,8 +132,7 @@ size_t GetThreadCount() { ...@@ -131,8 +132,7 @@ size_t GetThreadCount() {
if (status == KERN_SUCCESS) { if (status == KERN_SUCCESS) {
// task_threads allocates resources in thread_list and we need to free them // task_threads allocates resources in thread_list and we need to free them
// to avoid leaks. // to avoid leaks.
vm_deallocate(task, vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count); sizeof(thread_t) * thread_count);
return static_cast<size_t>(thread_count); return static_cast<size_t>(thread_count);
} else { } else {
...@@ -141,7 +141,7 @@ size_t GetThreadCount() { ...@@ -141,7 +141,7 @@ size_t GetThreadCount() {
} }
#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD GTEST_OS_NETBSD
#if GTEST_OS_NETBSD #if GTEST_OS_NETBSD
#undef KERN_PROC #undef KERN_PROC
...@@ -184,12 +184,12 @@ size_t GetThreadCount() { ...@@ -184,12 +184,12 @@ size_t GetThreadCount() {
// we cannot detect it. // we cannot detect it.
size_t GetThreadCount() { size_t GetThreadCount() {
int mib[] = { int mib[] = {
CTL_KERN, CTL_KERN,
KERN_PROC, KERN_PROC,
KERN_PROC_PID | KERN_PROC_SHOW_THREADS, KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
getpid(), getpid(),
sizeof(struct kinfo_proc), sizeof(struct kinfo_proc),
0, 0,
}; };
u_int miblen = sizeof(mib) / sizeof(mib[0]); u_int miblen = sizeof(mib) / sizeof(mib[0]);
...@@ -210,8 +210,7 @@ size_t GetThreadCount() { ...@@ -210,8 +210,7 @@ size_t GetThreadCount() {
// exclude empty members // exclude empty members
size_t nthreads = 0; size_t nthreads = 0;
for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) { for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
if (info[i].p_tid != -1) if (info[i].p_tid != -1) nthreads++;
nthreads++;
} }
return nthreads; return nthreads;
} }
...@@ -254,13 +253,9 @@ size_t GetThreadCount() { ...@@ -254,13 +253,9 @@ size_t GetThreadCount() {
size_t GetThreadCount() { size_t GetThreadCount() {
int dummy_buffer; int dummy_buffer;
size_t avail; size_t avail;
zx_status_t status = zx_object_get_info( zx_status_t status =
zx_process_self(), zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
ZX_INFO_PROCESS_THREADS, &dummy_buffer, 0, nullptr, &avail);
&dummy_buffer,
0,
nullptr,
&avail);
if (status == ZX_OK) { if (status == ZX_OK) {
return avail; return avail;
} else { } else {
...@@ -280,23 +275,15 @@ size_t GetThreadCount() { ...@@ -280,23 +275,15 @@ size_t GetThreadCount() {
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
AutoHandle::AutoHandle() AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
: handle_(INVALID_HANDLE_VALUE) {}
AutoHandle::AutoHandle(Handle handle) AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
: handle_(handle) {}
AutoHandle::~AutoHandle() { AutoHandle::~AutoHandle() { Reset(); }
Reset();
}
AutoHandle::Handle AutoHandle::Get() const { AutoHandle::Handle AutoHandle::Get() const { return handle_; }
return handle_;
}
void AutoHandle::Reset() { void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
Reset(INVALID_HANDLE_VALUE);
}
void AutoHandle::Reset(HANDLE handle) { void AutoHandle::Reset(HANDLE handle) {
// Resetting with the same handle we already own is invalid. // Resetting with the same handle we already own is invalid.
...@@ -308,7 +295,7 @@ void AutoHandle::Reset(HANDLE handle) { ...@@ -308,7 +295,7 @@ void AutoHandle::Reset(HANDLE handle) {
} else { } else {
GTEST_CHECK_(!IsCloseable()) GTEST_CHECK_(!IsCloseable())
<< "Resetting a valid handle to itself is likely a programmer error " << "Resetting a valid handle to itself is likely a programmer error "
"and thus not allowed."; "and thus not allowed.";
} }
} }
...@@ -370,8 +357,7 @@ namespace { ...@@ -370,8 +357,7 @@ namespace {
// MemoryIsNotDeallocated memory_is_not_deallocated; // MemoryIsNotDeallocated memory_is_not_deallocated;
// critical_section_ = new CRITICAL_SECTION; // critical_section_ = new CRITICAL_SECTION;
// //
class MemoryIsNotDeallocated class MemoryIsNotDeallocated {
{
public: public:
MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
...@@ -414,15 +400,13 @@ void Mutex::ThreadSafeLazyInit() { ...@@ -414,15 +400,13 @@ void Mutex::ThreadSafeLazyInit() {
::InitializeCriticalSection(critical_section_); ::InitializeCriticalSection(critical_section_);
// Updates the critical_section_init_phase_ to 2 to signal // Updates the critical_section_init_phase_ to 2 to signal
// initialization complete. // initialization complete.
GTEST_CHECK_(::InterlockedCompareExchange( GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
&critical_section_init_phase_, 2L, 1L) == 2L, 1L) == 1L);
1L);
break; break;
case 1: case 1:
// Somebody else is already initializing the mutex; spin until they // Somebody else is already initializing the mutex; spin until they
// are done. // are done.
while (::InterlockedCompareExchange(&critical_section_init_phase_, while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
2L,
2L) != 2L) { 2L) != 2L) {
// Possibly yields the rest of the thread's time slice to other // Possibly yields the rest of the thread's time slice to other
// threads. // threads.
...@@ -467,9 +451,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase { ...@@ -467,9 +451,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
private: private:
struct ThreadMainParam { struct ThreadMainParam {
ThreadMainParam(Runnable* runnable, Notification* thread_can_start) ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
: runnable_(runnable), : runnable_(runnable), thread_can_start_(thread_can_start) {}
thread_can_start_(thread_can_start) {
}
std::unique_ptr<Runnable> runnable_; std::unique_ptr<Runnable> runnable_;
// Does not own. // Does not own.
Notification* thread_can_start_; Notification* thread_can_start_;
...@@ -492,15 +474,12 @@ class ThreadWithParamSupport : public ThreadWithParamBase { ...@@ -492,15 +474,12 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
} // namespace } // namespace
ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,
Notification* thread_can_start) Notification* thread_can_start)
: thread_(ThreadWithParamSupport::CreateThread(runnable, : thread_(
thread_can_start)) { ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
}
ThreadWithParamBase::~ThreadWithParamBase() { ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
Join();
}
void ThreadWithParamBase::Join() { void ThreadWithParamBase::Join() {
GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
...@@ -527,8 +506,10 @@ class ThreadLocalRegistryImpl { ...@@ -527,8 +506,10 @@ class ThreadLocalRegistryImpl {
ThreadIdToThreadLocals::iterator thread_local_pos = ThreadIdToThreadLocals::iterator thread_local_pos =
thread_to_thread_locals->find(current_thread); thread_to_thread_locals->find(current_thread);
if (thread_local_pos == thread_to_thread_locals->end()) { if (thread_local_pos == thread_to_thread_locals->end()) {
thread_local_pos = thread_to_thread_locals->insert( thread_local_pos =
std::make_pair(current_thread, ThreadLocalValues())).first; thread_to_thread_locals
->insert(std::make_pair(current_thread, ThreadLocalValues()))
.first;
StartWatcherThreadFor(current_thread); StartWatcherThreadFor(current_thread);
} }
ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues& thread_local_values = thread_local_pos->second;
...@@ -556,9 +537,8 @@ class ThreadLocalRegistryImpl { ...@@ -556,9 +537,8 @@ class ThreadLocalRegistryImpl {
ThreadIdToThreadLocals* const thread_to_thread_locals = ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked(); GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it = for (ThreadIdToThreadLocals::iterator it =
thread_to_thread_locals->begin(); thread_to_thread_locals->begin();
it != thread_to_thread_locals->end(); it != thread_to_thread_locals->end(); ++it) {
++it) {
ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues& thread_local_values = it->second;
ThreadLocalValues::iterator value_pos = ThreadLocalValues::iterator value_pos =
thread_local_values.find(thread_local_instance); thread_local_values.find(thread_local_instance);
...@@ -588,9 +568,8 @@ class ThreadLocalRegistryImpl { ...@@ -588,9 +568,8 @@ class ThreadLocalRegistryImpl {
if (thread_local_pos != thread_to_thread_locals->end()) { if (thread_local_pos != thread_to_thread_locals->end()) {
ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues& thread_local_values = thread_local_pos->second;
for (ThreadLocalValues::iterator value_pos = for (ThreadLocalValues::iterator value_pos =
thread_local_values.begin(); thread_local_values.begin();
value_pos != thread_local_values.end(); value_pos != thread_local_values.end(); ++value_pos) {
++value_pos) {
value_holders.push_back(value_pos->second); value_holders.push_back(value_pos->second);
} }
thread_to_thread_locals->erase(thread_local_pos); thread_to_thread_locals->erase(thread_local_pos);
...@@ -616,9 +595,8 @@ class ThreadLocalRegistryImpl { ...@@ -616,9 +595,8 @@ class ThreadLocalRegistryImpl {
static void StartWatcherThreadFor(DWORD thread_id) { static void StartWatcherThreadFor(DWORD thread_id) {
// The returned handle will be kept in thread_map and closed by // The returned handle will be kept in thread_map and closed by
// watcher_thread in WatcherThreadFunc. // watcher_thread in WatcherThreadFunc.
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, HANDLE thread =
FALSE, ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
thread_id);
GTEST_CHECK_(thread != nullptr); GTEST_CHECK_(thread != nullptr);
// We need to pass a valid thread ID pointer into CreateThread for it // We need to pass a valid thread ID pointer into CreateThread for it
// to work correctly under Win98. // to work correctly under Win98.
...@@ -644,8 +622,7 @@ class ThreadLocalRegistryImpl { ...@@ -644,8 +622,7 @@ class ThreadLocalRegistryImpl {
static DWORD WINAPI WatcherThreadFunc(LPVOID param) { static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
const ThreadIdAndHandle* tah = const ThreadIdAndHandle* tah =
reinterpret_cast<const ThreadIdAndHandle*>(param); reinterpret_cast<const ThreadIdAndHandle*>(param);
GTEST_CHECK_( GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
OnThreadExit(tah->first); OnThreadExit(tah->first);
::CloseHandle(tah->second); ::CloseHandle(tah->second);
delete tah; delete tah;
...@@ -669,16 +646,17 @@ class ThreadLocalRegistryImpl { ...@@ -669,16 +646,17 @@ class ThreadLocalRegistryImpl {
}; };
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT Mutex ThreadLocalRegistryImpl::thread_map_mutex_(
Mutex::kStaticMutex); // NOLINT
ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) { const ThreadLocalBase* thread_local_instance) {
return ThreadLocalRegistryImpl::GetValueOnCurrentThread( return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
thread_local_instance); thread_local_instance);
} }
void ThreadLocalRegistry::OnThreadLocalDestroyed( void ThreadLocalRegistry::OnThreadLocalDestroyed(
const ThreadLocalBase* thread_local_instance) { const ThreadLocalBase* thread_local_instance) {
ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
} }
...@@ -766,7 +744,7 @@ bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } ...@@ -766,7 +744,7 @@ bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
bool IsAsciiWordChar(char ch) { bool IsAsciiWordChar(char ch) {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') || ch == '_'; ('0' <= ch && ch <= '9') || ch == '_';
} }
// Returns true if and only if "\\c" is a supported escape sequence. // Returns true if and only if "\\c" is a supported escape sequence.
...@@ -779,17 +757,28 @@ bool IsValidEscape(char c) { ...@@ -779,17 +757,28 @@ bool IsValidEscape(char c) {
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
if (escaped) { // "\\p" where p is pattern_char. if (escaped) { // "\\p" where p is pattern_char.
switch (pattern_char) { switch (pattern_char) {
case 'd': return IsAsciiDigit(ch); case 'd':
case 'D': return !IsAsciiDigit(ch); return IsAsciiDigit(ch);
case 'f': return ch == '\f'; case 'D':
case 'n': return ch == '\n'; return !IsAsciiDigit(ch);
case 'r': return ch == '\r'; case 'f':
case 's': return IsAsciiWhiteSpace(ch); return ch == '\f';
case 'S': return !IsAsciiWhiteSpace(ch); case 'n':
case 't': return ch == '\t'; return ch == '\n';
case 'v': return ch == '\v'; case 'r':
case 'w': return IsAsciiWordChar(ch); return ch == '\r';
case 'W': return !IsAsciiWordChar(ch); case 's':
return IsAsciiWhiteSpace(ch);
case 'S':
return !IsAsciiWhiteSpace(ch);
case 't':
return ch == '\t';
case 'v':
return ch == '\v';
case 'w':
return IsAsciiWordChar(ch);
case 'W':
return !IsAsciiWordChar(ch);
} }
return IsAsciiPunct(pattern_char) && pattern_char == ch; return IsAsciiPunct(pattern_char) && pattern_char == ch;
} }
...@@ -800,7 +789,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { ...@@ -800,7 +789,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
// Helper function used by ValidateRegex() to format error messages. // Helper function used by ValidateRegex() to format error messages.
static std::string FormatRegexSyntaxError(const char* regex, int index) { static std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index return (Message() << "Syntax error at index " << index
<< " in simple regular expression \"" << regex << "\": ").GetString(); << " in simple regular expression \"" << regex << "\": ")
.GetString();
} }
// Generates non-fatal failures and returns false if regex is invalid; // Generates non-fatal failures and returns false if regex is invalid;
...@@ -842,12 +832,12 @@ bool ValidateRegex(const char* regex) { ...@@ -842,12 +832,12 @@ bool ValidateRegex(const char* regex) {
<< "'$' can only appear at the end."; << "'$' can only appear at the end.";
is_valid = false; is_valid = false;
} else if (IsInSet(ch, "()[]{}|")) { } else if (IsInSet(ch, "()[]{}|")) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "'" << ch << "' is unsupported."; << "' is unsupported.";
is_valid = false; is_valid = false;
} else if (IsRepeat(ch) && !prev_repeatable) { } else if (IsRepeat(ch) && !prev_repeatable) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "'" << ch << "' can only follow a repeatable token."; << "' can only follow a repeatable token.";
is_valid = false; is_valid = false;
} }
...@@ -865,12 +855,10 @@ bool ValidateRegex(const char* regex) { ...@@ -865,12 +855,10 @@ bool ValidateRegex(const char* regex) {
// characters to be indexable by size_t, in which case the test will // characters to be indexable by size_t, in which case the test will
// probably time out anyway. We are fine with this limitation as // probably time out anyway. We are fine with this limitation as
// std::string has it too. // std::string has it too.
bool MatchRepetitionAndRegexAtHead( bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
bool escaped, char c, char repeat, const char* regex, const char* regex, const char* str) {
const char* str) {
const size_t min_count = (repeat == '+') ? 1 : 0; const size_t min_count = (repeat == '+') ? 1 : 0;
const size_t max_count = (repeat == '?') ? 1 : const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
static_cast<size_t>(-1) - 1;
// We cannot call numeric_limits::max() as it conflicts with the // We cannot call numeric_limits::max() as it conflicts with the
// max() macro on Windows. // max() macro on Windows.
...@@ -883,8 +871,7 @@ bool MatchRepetitionAndRegexAtHead( ...@@ -883,8 +871,7 @@ bool MatchRepetitionAndRegexAtHead(
// greedy match. // greedy match.
return true; return true;
} }
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
return false;
} }
return false; return false;
} }
...@@ -898,25 +885,23 @@ bool MatchRegexAtHead(const char* regex, const char* str) { ...@@ -898,25 +885,23 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
// "$" only matches the end of a string. Note that regex being // "$" only matches the end of a string. Note that regex being
// valid guarantees that there's nothing after "$" in it. // valid guarantees that there's nothing after "$" in it.
if (*regex == '$') if (*regex == '$') return *str == '\0';
return *str == '\0';
// Is the first thing in regex an escape sequence? // Is the first thing in regex an escape sequence?
const bool escaped = *regex == '\\'; const bool escaped = *regex == '\\';
if (escaped) if (escaped) ++regex;
++regex;
if (IsRepeat(regex[1])) { if (IsRepeat(regex[1])) {
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
// here's an indirect recursion. It terminates as the regex gets // here's an indirect recursion. It terminates as the regex gets
// shorter in each recursion. // shorter in each recursion.
return MatchRepetitionAndRegexAtHead( return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
escaped, regex[0], regex[1], regex + 2, str); str);
} else { } else {
// regex isn't empty, isn't "$", and doesn't start with a // regex isn't empty, isn't "$", and doesn't start with a
// repetition. We match the first atom of regex with the first // repetition. We match the first atom of regex with the first
// character of str and recurse. // character of str and recurse.
return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
MatchRegexAtHead(regex + 1, str + 1); MatchRegexAtHead(regex + 1, str + 1);
} }
} }
...@@ -931,13 +916,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) { ...@@ -931,13 +916,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
bool MatchRegexAnywhere(const char* regex, const char* str) { bool MatchRegexAnywhere(const char* regex, const char* str) {
if (regex == nullptr || str == nullptr) return false; if (regex == nullptr || str == nullptr) return false;
if (*regex == '^') if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
return MatchRegexAtHead(regex + 1, str);
// A successful match can be anywhere in str. // A successful match can be anywhere in str.
do { do {
if (MatchRegexAtHead(regex, str)) if (MatchRegexAtHead(regex, str)) return true;
return true;
} while (*str++ != '\0'); } while (*str++ != '\0');
return false; return false;
} }
...@@ -1018,8 +1001,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { ...@@ -1018,8 +1001,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
// FormatFileLocation in order to contrast the two functions. // FormatFileLocation in order to contrast the two functions.
// Note that FormatCompilerIndependentFileLocation() does NOT append colon // Note that FormatCompilerIndependentFileLocation() does NOT append colon
// to the file location it produces, unlike FormatFileLocation(). // to the file location it produces, unlike FormatFileLocation().
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
const char* file, int line) { int line) {
const std::string file_name(file == nullptr ? kUnknownFile : file); const std::string file_name(file == nullptr ? kUnknownFile : file);
if (line < 0) if (line < 0)
...@@ -1030,12 +1013,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( ...@@ -1030,12 +1013,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
: severity_(severity) { : severity_(severity) {
const char* const marker = const char* const marker = severity == GTEST_INFO ? "[ INFO ]"
severity == GTEST_INFO ? "[ INFO ]" : : severity == GTEST_WARNING ? "[WARNING]"
severity == GTEST_WARNING ? "[WARNING]" : : severity == GTEST_ERROR ? "[ ERROR ]"
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; : "[ FATAL ]";
GetStream() << ::std::endl << marker << " " GetStream() << ::std::endl
<< FormatFileLocation(file, line).c_str() << ": "; << marker << " " << FormatFileLocation(file, line).c_str()
<< ": ";
} }
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
...@@ -1058,27 +1042,26 @@ class CapturedStream { ...@@ -1058,27 +1042,26 @@ class CapturedStream {
public: public:
// The ctor redirects the stream to a temporary file. // The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
const UINT success = ::GetTempFileNameA(temp_dir_path, const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
"gtest_redir",
0, // Generate unique file name. 0, // Generate unique file name.
temp_file_path); temp_file_path);
GTEST_CHECK_(success != 0) GTEST_CHECK_(success != 0)
<< "Unable to create a temporary file in " << temp_dir_path; << "Unable to create a temporary file in " << temp_dir_path;
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " GTEST_CHECK_(captured_fd != -1)
<< temp_file_path; << "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path; filename_ = temp_file_path;
# else #else
// There's no guarantee that a test has write access to the current // There's no guarantee that a test has write access to the current
// directory, so we create the temporary file in a temporary directory. // directory, so we create the temporary file in a temporary directory.
std::string name_template; std::string name_template;
# if GTEST_OS_LINUX_ANDROID #if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's // Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get // Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However, // the location of the world-writable SD Card directory. However,
...@@ -1091,7 +1074,7 @@ class CapturedStream { ...@@ -1091,7 +1074,7 @@ class CapturedStream {
// '/sdcard' and other variants cannot be relied on, as they are not // '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting. // guaranteed to be mounted, or may have a delay in mounting.
name_template = "/data/local/tmp/"; name_template = "/data/local/tmp/";
# elif GTEST_OS_IOS #elif GTEST_OS_IOS
char user_temp_dir[PATH_MAX + 1]; char user_temp_dir[PATH_MAX + 1];
// Documented alternative to NSTemporaryDirectory() (for obtaining creating // Documented alternative to NSTemporaryDirectory() (for obtaining creating
...@@ -1112,9 +1095,9 @@ class CapturedStream { ...@@ -1112,9 +1095,9 @@ class CapturedStream {
name_template = user_temp_dir; name_template = user_temp_dir;
if (name_template.back() != GTEST_PATH_SEP_[0]) if (name_template.back() != GTEST_PATH_SEP_[0])
name_template.push_back(GTEST_PATH_SEP_[0]); name_template.push_back(GTEST_PATH_SEP_[0]);
# else #else
name_template = "/tmp/"; name_template = "/tmp/";
# endif #endif
name_template.append("gtest_captured_stream.XXXXXX"); name_template.append("gtest_captured_stream.XXXXXX");
// mkstemp() modifies the string bytes in place, and does not go beyond the // mkstemp() modifies the string bytes in place, and does not go beyond the
...@@ -1130,15 +1113,13 @@ class CapturedStream { ...@@ -1130,15 +1113,13 @@ class CapturedStream {
<< " for test; does the test have access to the /tmp directory?"; << " for test; does the test have access to the /tmp directory?";
} }
filename_ = std::move(name_template); filename_ = std::move(name_template);
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
fflush(nullptr); fflush(nullptr);
dup2(captured_fd, fd_); dup2(captured_fd, fd_);
close(captured_fd); close(captured_fd);
} }
~CapturedStream() { ~CapturedStream() { remove(filename_.c_str()); }
remove(filename_.c_str());
}
std::string GetCapturedString() { std::string GetCapturedString() {
if (uncaptured_fd_ != -1) { if (uncaptured_fd_ != -1) {
...@@ -1215,10 +1196,6 @@ std::string GetCapturedStderr() { ...@@ -1215,10 +1196,6 @@ std::string GetCapturedStderr() {
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
size_t GetFileSize(FILE* file) { size_t GetFileSize(FILE* file) {
fseek(file, 0, SEEK_END); fseek(file, 0, SEEK_END);
return static_cast<size_t>(ftell(file)); return static_cast<size_t>(ftell(file));
...@@ -1236,7 +1213,8 @@ std::string ReadEntireFile(FILE* file) { ...@@ -1236,7 +1213,8 @@ std::string ReadEntireFile(FILE* file) {
// Keeps reading the file until we cannot read further or the // Keeps reading the file until we cannot read further or the
// pre-determined file size is reached. // pre-determined file size is reached.
do { do {
bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_last_read =
fread(buffer + bytes_read, 1, file_size - bytes_read, file);
bytes_read += bytes_last_read; bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size); } while (bytes_last_read > 0 && bytes_read < file_size);
...@@ -1324,7 +1302,7 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { ...@@ -1324,7 +1302,7 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
// LONG_MAX or LONG_MIN when the input overflows.) // LONG_MAX or LONG_MIN when the input overflows.)
result != long_value result != long_value
// The parsed value overflows as an int32_t. // The parsed value overflows as an int32_t.
) { ) {
Message msg; Message msg;
msg << "WARNING: " << src_text msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually" << " is expected to be a 32-bit integer, but actually"
...@@ -1368,8 +1346,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { ...@@ -1368,8 +1346,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
} }
int32_t result = default_value; int32_t result = default_value;
if (!ParseInt32(Message() << "Environment variable " << env_var, if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
string_value, &result)) { &result)) {
printf("The default value %s is used.\n", printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str()); (Message() << default_value).GetString().c_str());
fflush(stdout); fflush(stdout);
...@@ -1388,7 +1366,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { ...@@ -1388,7 +1366,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
// not check that the flag is 'output' // not check that the flag is 'output'
// In essence this checks an env variable called XML_OUTPUT_FILE // In essence this checks an env variable called XML_OUTPUT_FILE
// and if it is set we prepend "xml:" to its value, if it not set we return "" // and if it is set we prepend "xml:" to its value, if it not set we return ""
std::string OutputFlagAlsoCheckEnvVar(){ std::string OutputFlagAlsoCheckEnvVar() {
std::string default_value_for_output_flag = ""; std::string default_value_for_output_flag = "";
const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
if (nullptr != xml_output_file_env) { if (nullptr != xml_output_file_env) {
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Test - The Google C++ Testing and Mocking Framework // Google Test - The Google C++ Testing and Mocking Framework
// //
// This file implements a universal value printer that can print a // This file implements a universal value printer that can print a
...@@ -101,7 +100,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ...@@ -101,7 +100,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... "; *os << " ... ";
// Rounds up to 2-byte boundary. // Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2; const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
} }
*os << ">"; *os << ">";
...@@ -136,11 +135,7 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ...@@ -136,11 +135,7 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexadecimal escape sequence (e.g. '\x7F'), or // - as a hexadecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n'). // - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat { enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the // Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on // value of c directly instead of calling isprint(), which is buggy on
...@@ -213,35 +208,21 @@ static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) { ...@@ -213,35 +208,21 @@ static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
} }
} }
static const char* GetCharWidthPrefix(char) { static const char* GetCharWidthPrefix(char) { return ""; }
return "";
}
static const char* GetCharWidthPrefix(signed char) { static const char* GetCharWidthPrefix(signed char) { return ""; }
return "";
}
static const char* GetCharWidthPrefix(unsigned char) { static const char* GetCharWidthPrefix(unsigned char) { return ""; }
return "";
}
#ifdef __cpp_char8_t #ifdef __cpp_char8_t
static const char* GetCharWidthPrefix(char8_t) { static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
return "u8";
}
#endif #endif
static const char* GetCharWidthPrefix(char16_t) { static const char* GetCharWidthPrefix(char16_t) { return "u"; }
return "u";
}
static const char* GetCharWidthPrefix(char32_t) { static const char* GetCharWidthPrefix(char32_t) { return "U"; }
return "U";
}
static const char* GetCharWidthPrefix(wchar_t) { static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
return "L";
}
// Prints a char c as if it's part of a string literal, escaping it when // Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted. // necessary; returns how c was formatted.
...@@ -276,8 +257,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) { ...@@ -276,8 +257,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
// To aid user debugging, we also print c's code in decimal, unless // To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code // it's 0 (in which case c was printed as '\\0', making the code
// obvious). // obvious).
if (c == 0) if (c == 0) return;
return;
*os << " (" << static_cast<int>(c); *os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexadecimal, // For more convenience, we print c's code again in hexadecimal,
...@@ -354,12 +334,10 @@ void PrintTo(__int128_t v, ::std::ostream* os) { ...@@ -354,12 +334,10 @@ void PrintTo(__int128_t v, ::std::ostream* os) {
// The array starts at begin, the length is len, it may include '\0' characters // The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated. // and may not be NUL-terminated.
template <typename CharType> template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
static CharFormat PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const quote_prefix = GetCharWidthPrefix(*begin); const char* const quote_prefix = GetCharWidthPrefix(*begin);
*os << quote_prefix << "\""; *os << quote_prefix << "\"";
bool is_previous_hex = false; bool is_previous_hex = false;
...@@ -385,12 +363,11 @@ static CharFormat PrintCharsAsStringTo( ...@@ -385,12 +363,11 @@ static CharFormat PrintCharsAsStringTo(
// Prints a (const) char/wchar_t array of 'len' elements, starting at address // Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t. // 'begin'. CharType must be either char or wchar_t.
template <typename CharType> template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ UniversalPrintCharArray(const CharType* begin, size_t len,
static void UniversalPrintCharArray( ostream* os) {
const CharType* begin, size_t len, ostream* os) {
// The code // The code
// const char kFoo[] = "foo"; // const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'. // generates an array of 4, not 3, elements, with the last one being '\0'.
...@@ -481,28 +458,28 @@ void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); } ...@@ -481,28 +458,28 @@ void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
namespace { namespace {
bool ContainsUnprintableControlCodes(const char* str, size_t length) { bool ContainsUnprintableControlCodes(const char* str, size_t length) {
const unsigned char *s = reinterpret_cast<const unsigned char *>(str); const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
for (size_t i = 0; i < length; i++) { for (size_t i = 0; i < length; i++) {
unsigned char ch = *s++; unsigned char ch = *s++;
if (std::iscntrl(ch)) { if (std::iscntrl(ch)) {
switch (ch) { switch (ch) {
case '\t': case '\t':
case '\n': case '\n':
case '\r': case '\r':
break; break;
default: default:
return true; return true;
}
} }
}
} }
return false; return false;
} }
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; } bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }
bool IsValidUTF8(const char* str, size_t length) { bool IsValidUTF8(const char* str, size_t length) {
const unsigned char *s = reinterpret_cast<const unsigned char *>(str); const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
for (size_t i = 0; i < length;) { for (size_t i = 0; i < length;) {
unsigned char lead = s[i++]; unsigned char lead = s[i++];
...@@ -515,15 +492,13 @@ bool IsValidUTF8(const char* str, size_t length) { ...@@ -515,15 +492,13 @@ bool IsValidUTF8(const char* str, size_t length) {
} else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
++i; // 2-byte character ++i; // 2-byte character
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 1]) &&
// check for non-shortest form and surrogate // check for non-shortest form and surrogate
(lead != 0xe0 || s[i] >= 0xa0) && (lead != 0xe0 || s[i] >= 0xa0) &&
(lead != 0xed || s[i] < 0xa0)) { (lead != 0xed || s[i] < 0xa0)) {
i += 2; // 3-byte character i += 2; // 3-byte character
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 2]) && IsUTF8TrailByte(s[i + 2]) &&
// check for non-shortest form // check for non-shortest form
(lead != 0xf0 || s[i] >= 0x90) && (lead != 0xf0 || s[i] >= 0x90) &&
......
...@@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { ...@@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
return os << internal::FormatFileLocation(result.file_name(), return os << internal::FormatFileLocation(result.file_name(),
result.line_number()) result.line_number())
<< " " << " "
<< (result.type() == TestPartResult::kSuccess << (result.type() == TestPartResult::kSuccess ? "Success"
? "Success" : result.type() == TestPartResult::kSkip ? "Skipped"
: result.type() == TestPartResult::kSkip : result.type() == TestPartResult::kFatalFailure
? "Skipped" ? "Fatal failure"
: result.type() == TestPartResult::kFatalFailure : "Non-fatal failure")
? "Fatal failure"
: "Non-fatal failure")
<< ":\n" << ":\n"
<< result.message() << std::endl; << result.message() << std::endl;
} }
...@@ -86,8 +84,8 @@ namespace internal { ...@@ -86,8 +84,8 @@ namespace internal {
HasNewFatalFailureHelper::HasNewFatalFailureHelper() HasNewFatalFailureHelper::HasNewFatalFailureHelper()
: has_new_fatal_failure_(false), : has_new_fatal_failure_(false),
original_reporter_(GetUnitTestImpl()-> original_reporter_(
GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
} }
...@@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { ...@@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
void HasNewFatalFailureHelper::ReportTestPartResult( void HasNewFatalFailureHelper::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
if (result.fatally_failed()) if (result.fatally_failed()) has_new_fatal_failure_ = true;
has_new_fatal_failure_ = true;
original_reporter_->ReportTestPartResult(result); original_reporter_->ReportTestPartResult(result);
} }
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest-typed-test.h" #include "gtest/gtest-typed-test.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -38,8 +37,7 @@ namespace internal { ...@@ -38,8 +37,7 @@ namespace internal {
// Skips to the first non-space char in str. Returns an empty string if str // Skips to the first non-space char in str. Returns an empty string if str
// contains only whitespace characters. // contains only whitespace characters.
static const char* SkipSpaces(const char* str) { static const char* SkipSpaces(const char* str) {
while (IsSpace(*str)) while (IsSpace(*str)) str++;
str++;
return str; return str;
} }
...@@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames( ...@@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
} }
for (RegisteredTestIter it = registered_tests_.begin(); for (RegisteredTestIter it = registered_tests_.begin();
it != registered_tests_.end(); it != registered_tests_.end(); ++it) {
++it) {
if (tests.count(it->first) == 0) { if (tests.count(it->first) == 0) {
errors << "You forgot to list test " << it->first << ".\n"; errors << "You forgot to list test " << it->first << ".\n";
} }
......
...@@ -60,69 +60,70 @@ ...@@ -60,69 +60,70 @@
#if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <fcntl.h> // NOLINT #include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT #include <limits.h> // NOLINT
# include <sched.h> // NOLINT #include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows. // Declares vsnprintf(). This header is not available on Windows.
# include <strings.h> // NOLINT #include <strings.h> // NOLINT
# include <sys/mman.h> // NOLINT #include <sys/mman.h> // NOLINT
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
# include <string>
#include <string>
#elif GTEST_OS_ZOS #elif GTEST_OS_ZOS
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp. // On z/OS we additionally need strings.h for strcasecmp.
# include <strings.h> // NOLINT #include <strings.h> // NOLINT
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
# undef min #undef min
#elif GTEST_OS_WINDOWS // We are on Windows proper. #elif GTEST_OS_WINDOWS // We are on Windows proper.
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
# undef min #undef min
#ifdef _MSC_VER #ifdef _MSC_VER
# include <crtdbg.h> // NOLINT #include <crtdbg.h> // NOLINT
#endif #endif
# include <io.h> // NOLINT #include <io.h> // NOLINT
# include <sys/timeb.h> // NOLINT #include <sys/stat.h> // NOLINT
# include <sys/types.h> // NOLINT #include <sys/timeb.h> // NOLINT
# include <sys/stat.h> // NOLINT #include <sys/types.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW #if GTEST_OS_WINDOWS_MINGW
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW #endif // GTEST_OS_WINDOWS_MINGW
#else #else
// cpplint thinks that the header is already included, so we want to // cpplint thinks that the header is already included, so we want to
// silence it. // silence it.
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <stdexcept> #include <stdexcept>
#endif #endif
#if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT #include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT #include <netdb.h> // NOLINT
# include <sys/socket.h> // NOLINT #include <sys/socket.h> // NOLINT
# include <sys/types.h> // NOLINT #include <sys/types.h> // NOLINT
#endif #endif
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# define vsnprintf _vsnprintf #define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC #if GTEST_OS_MAC
...@@ -271,8 +272,7 @@ GTEST_DEFINE_bool_( ...@@ -271,8 +272,7 @@ GTEST_DEFINE_bool_(
"install a signal handler that dumps debugging information when fatal " "install a signal handler that dumps debugging information when fatal "
"signals are raised."); "signals are raised.");
GTEST_DEFINE_bool_(list_tests, false, GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
"List all tests without running them.");
// The net priority order after flag processing is thus: // The net priority order after flag processing is thus:
// --gtest_output command line flag // --gtest_output command line flag
...@@ -374,10 +374,9 @@ namespace internal { ...@@ -374,10 +374,9 @@ namespace internal {
uint32_t Random::Generate(uint32_t range) { uint32_t Random::Generate(uint32_t range) {
// These constants are the same as are used in glibc's rand(3). // These constants are the same as are used in glibc's rand(3).
// Use wider types than necessary to prevent unsigned overflow diagnostics. // Use wider types than necessary to prevent unsigned overflow diagnostics.
state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange; state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
GTEST_CHECK_(range > 0) GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
<< "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange) GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, " << "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ")."; << "but this can only generate numbers in [0, " << kMaxRange << ").";
...@@ -422,26 +421,20 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) { ...@@ -422,26 +421,20 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) {
} }
// AssertHelper constructor. // AssertHelper constructor.
AssertHelper::AssertHelper(TestPartResult::Type type, AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
const char* file, int line, const char* message)
int line, : data_(new AssertHelperData(type, file, line, message)) {}
const char* message)
: data_(new AssertHelperData(type, file, line, message)) {
}
AssertHelper::~AssertHelper() { AssertHelper::~AssertHelper() { delete data_; }
delete data_;
}
// Message assignment, for assertion streaming support. // Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const { void AssertHelper::operator=(const Message& message) const {
UnitTest::GetInstance()-> UnitTest::GetInstance()->AddTestPartResult(
AddTestPartResult(data_->type, data_->file, data_->line, data_->type, data_->file, data_->line,
AppendUserMessage(data_->message, message), AppendUserMessage(data_->message, message),
UnitTest::GetInstance()->impl() UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself.
// Skips the stack frame for this function itself. ); // NOLINT
); // NOLINT
} }
namespace { namespace {
...@@ -478,7 +471,6 @@ class FailureTest : public Test { ...@@ -478,7 +471,6 @@ class FailureTest : public Test {
const bool as_error_; const bool as_error_;
}; };
} // namespace } // namespace
std::set<std::string>* GetIgnoredParameterizedTestSuites() { std::set<std::string>* GetIgnoredParameterizedTestSuites() {
...@@ -522,7 +514,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, ...@@ -522,7 +514,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
"To suppress this error for this test suite, insert the following line " "To suppress this error for this test suite, insert the following line "
"(in a non-header) in the namespace it is defined in:" "(in a non-header) in the namespace it is defined in:"
"\n\n" "\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
name + ");";
std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
RegisterTest( // RegisterTest( //
...@@ -542,19 +535,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, ...@@ -542,19 +535,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
} }
void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
GetUnitTestImpl() GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
->type_parameterized_test_registry() case_name);
.RegisterInstantiation(case_name);
} }
void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
const char* test_suite_name, CodeLocation code_location) { const char* test_suite_name, CodeLocation code_location) {
suites_.emplace(std::string(test_suite_name), suites_.emplace(std::string(test_suite_name),
TypeParameterizedTestSuiteInfo(code_location)); TypeParameterizedTestSuiteInfo(code_location));
} }
void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
const char* test_suite_name) { const char* test_suite_name) {
auto it = suites_.find(std::string(test_suite_name)); auto it = suites_.find(std::string(test_suite_name));
if (it != suites_.end()) { if (it != suites_.end()) {
it->second.instantiated = true; it->second.instantiated = true;
...@@ -648,16 +640,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { ...@@ -648,16 +640,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = s.c_str(); const char* const gtest_output_flag = s.c_str();
std::string format = GetOutputFormat(); std::string format = GetOutputFormat();
if (format.empty()) if (format.empty()) format = std::string(kDefaultOutputFormat);
format = std::string(kDefaultOutputFormat);
const char* const colon = strchr(gtest_output_flag, ':'); const char* const colon = strchr(gtest_output_flag, ':');
if (colon == nullptr) if (colon == nullptr)
return internal::FilePath::MakeFileName( return internal::FilePath::MakeFileName(
internal::FilePath( internal::FilePath(
UnitTest::GetInstance()->original_working_dir()), UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile), 0, internal::FilePath(kDefaultOutputFile), 0, format.c_str())
format.c_str()).string(); .string();
internal::FilePath output_name(colon + 1); internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath()) if (!output_name.IsAbsolutePath())
...@@ -665,8 +656,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { ...@@ -665,8 +656,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1)); internal::FilePath(colon + 1));
if (!output_name.IsDirectory()) if (!output_name.IsDirectory()) return output_name.string();
return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName( internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(), output_name, internal::GetCurrentExecutableName(),
...@@ -877,8 +867,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { ...@@ -877,8 +867,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
// results. Intercepts only failures from the current thread. // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result) TestPartResultArray* result)
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
result_(result) {
Init(); Init();
} }
...@@ -887,8 +876,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ...@@ -887,8 +876,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
// results. // results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result) InterceptMode intercept_mode, TestPartResultArray* result)
: intercept_mode_(intercept_mode), : intercept_mode_(intercept_mode), result_(result) {
result_(result) {
Init(); Init();
} }
...@@ -932,9 +920,7 @@ namespace internal { ...@@ -932,9 +920,7 @@ namespace internal {
// from user test code. GetTestTypeId() is guaranteed to always // from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the // return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework. // gtest.cc, which is within the Google Test framework.
TypeId GetTestTypeId() { TypeId GetTestTypeId() { return GetTypeId<Test>(); }
return GetTypeId<Test>();
}
// The value of GetTestTypeId() as seen from within the Google Test // The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId(). // library. This is solely for testing GetTestTypeId().
...@@ -949,9 +935,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, ...@@ -949,9 +935,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
const TestPartResultArray& results, const TestPartResultArray& results,
TestPartResult::Type type, TestPartResult::Type type,
const std::string& substr) { const std::string& substr) {
const std::string expected(type == TestPartResult::kFatalFailure ? const std::string expected(type == TestPartResult::kFatalFailure
"1 fatal failure" : ? "1 fatal failure"
"1 non-fatal failure"); : "1 non-fatal failure");
Message msg; Message msg;
if (results.size() != 1) { if (results.size() != 1) {
msg << "Expected: " << expected << "\n" msg << "Expected: " << expected << "\n"
...@@ -970,10 +956,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, ...@@ -970,10 +956,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
} }
if (strstr(r.message(), substr.c_str()) == nullptr) { if (strstr(r.message(), substr.c_str()) == nullptr) {
return AssertionFailure() << "Expected: " << expected << " containing \"" return AssertionFailure()
<< substr << "\"\n" << "Expected: " << expected << " containing \"" << substr << "\"\n"
<< " Actual:\n" << " Actual:\n"
<< r; << r;
} }
return AssertionSuccess(); return AssertionSuccess();
...@@ -996,7 +982,8 @@ SingleFailureChecker::~SingleFailureChecker() { ...@@ -996,7 +982,8 @@ SingleFailureChecker::~SingleFailureChecker() {
} }
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {} UnitTestImpl* unit_test)
: unit_test_(unit_test) {}
void DefaultGlobalTestPartResultReporter::ReportTestPartResult( void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
...@@ -1005,7 +992,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult( ...@@ -1005,7 +992,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
} }
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {} UnitTestImpl* unit_test)
: unit_test_(unit_test) {}
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
...@@ -1159,8 +1147,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { ...@@ -1159,8 +1147,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
const int unicode_length = const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1]; WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
unicode, unicode_length);
unicode[unicode_length] = 0; unicode[unicode_length] = 0;
return unicode; return unicode;
} }
...@@ -1169,7 +1156,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { ...@@ -1169,7 +1156,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
// memory using new. The caller is responsible for deleting the return // memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the // value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL. // input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return nullptr; if (!utf16_str) return nullptr;
const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
0, nullptr, nullptr); 0, nullptr, nullptr);
...@@ -1188,7 +1175,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { ...@@ -1188,7 +1175,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
// Unlike strcmp(), this function can handle NULL argument(s). A NULL // Unlike strcmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string, // C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::CStringEquals(const char * lhs, const char * rhs) { bool String::CStringEquals(const char* lhs, const char* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
...@@ -1202,11 +1189,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { ...@@ -1202,11 +1189,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) {
// encoding, and streams the result to the given Message object. // encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) { Message* msg) {
for (size_t i = 0; i != length; ) { // NOLINT for (size_t i = 0; i != length;) { // NOLINT
if (wstr[i] != L'\0') { if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
while (i != length && wstr[i] != L'\0') while (i != length && wstr[i] != L'\0') i++;
i++;
} else { } else {
*msg << '\0'; *msg << '\0';
i++; i++;
...@@ -1248,17 +1234,17 @@ Message::Message() : ss_(new ::std::stringstream) { ...@@ -1248,17 +1234,17 @@ Message::Message() : ss_(new ::std::stringstream) {
// These two overloads allow streaming a wide C string to a Message // These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding. // using the UTF-8 encoding.
Message& Message::operator <<(const wchar_t* wide_c_str) { Message& Message::operator<<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str); return *this << internal::String::ShowWideCString(wide_c_str);
} }
Message& Message::operator <<(wchar_t* wide_c_str) { Message& Message::operator<<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str); return *this << internal::String::ShowWideCString(wide_c_str);
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8 // Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object. // encoding, and streams the result to this Message object.
Message& Message::operator <<(const ::std::wstring& wstr) { Message& Message::operator<<(const ::std::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this; return *this;
} }
...@@ -1561,8 +1547,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) { ...@@ -1561,8 +1547,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) {
AssertionResult EqFailure(const char* lhs_expression, AssertionResult EqFailure(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression,
const std::string& lhs_value, const std::string& lhs_value,
const std::string& rhs_value, const std::string& rhs_value, bool ignoring_case) {
bool ignoring_case) {
Message msg; Message msg;
msg << "Expected equality of these values:"; msg << "Expected equality of these values:";
msg << "\n " << lhs_expression; msg << "\n " << lhs_expression;
...@@ -1579,10 +1564,8 @@ AssertionResult EqFailure(const char* lhs_expression, ...@@ -1579,10 +1564,8 @@ AssertionResult EqFailure(const char* lhs_expression,
} }
if (!lhs_value.empty() && !rhs_value.empty()) { if (!lhs_value.empty() && !rhs_value.empty()) {
const std::vector<std::string> lhs_lines = const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
const std::vector<std::string> rhs_lines =
SplitEscapedString(rhs_value);
if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
msg << "\nWith diff:\n" msg << "\nWith diff:\n"
<< edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
...@@ -1594,27 +1577,21 @@ AssertionResult EqFailure(const char* lhs_expression, ...@@ -1594,27 +1577,21 @@ AssertionResult EqFailure(const char* lhs_expression,
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
std::string GetBoolAssertionFailureMessage( std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result, const AssertionResult& assertion_result, const char* expression_text,
const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) {
const char* actual_predicate_value,
const char* expected_predicate_value) {
const char* actual_message = assertion_result.message(); const char* actual_message = assertion_result.message();
Message msg; Message msg;
msg << "Value of: " << expression_text msg << "Value of: " << expression_text
<< "\n Actual: " << actual_predicate_value; << "\n Actual: " << actual_predicate_value;
if (actual_message[0] != '\0') if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
msg << " (" << actual_message << ")";
msg << "\nExpected: " << expected_predicate_value; msg << "\nExpected: " << expected_predicate_value;
return msg.GetString(); return msg.GetString();
} }
// Helper function for implementing ASSERT_NEAR. // Helper function for implementing ASSERT_NEAR.
AssertionResult DoubleNearPredFormat(const char* expr1, AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
const char* expr2, const char* abs_error_expr, double val1,
const char* abs_error_expr, double val2, double abs_error) {
double val1,
double val2,
double abs_error) {
const double diff = fabs(val1 - val2); const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess(); if (diff <= abs_error) return AssertionSuccess();
...@@ -1644,20 +1621,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1, ...@@ -1644,20 +1621,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1,
"EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
} }
return AssertionFailure() return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2 << "The difference between " << expr1 << " and " << expr2 << " is "
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << diff << ", which exceeds " << abs_error_expr << ", where\n"
<< expr1 << " evaluates to " << val1 << ",\n" << expr1 << " evaluates to " << val1 << ",\n"
<< expr2 << " evaluates to " << val2 << ", and\n" << expr2 << " evaluates to " << val2 << ", and\n"
<< abs_error_expr << " evaluates to " << abs_error << "."; << abs_error_expr << " evaluates to " << abs_error << ".";
} }
// Helper template for implementing FloatLE() and DoubleLE(). // Helper template for implementing FloatLE() and DoubleLE().
template <typename RawType> template <typename RawType>
AssertionResult FloatingPointLE(const char* expr1, AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
const char* expr2, RawType val1, RawType val2) {
RawType val1,
RawType val2) {
// Returns success if val1 is less than val2, // Returns success if val1 is less than val2,
if (val1 < val2) { if (val1 < val2) {
return AssertionSuccess(); return AssertionSuccess();
...@@ -1682,24 +1656,24 @@ AssertionResult FloatingPointLE(const char* expr1, ...@@ -1682,24 +1656,24 @@ AssertionResult FloatingPointLE(const char* expr1,
<< val2; << val2;
return AssertionFailure() return AssertionFailure()
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
<< " Actual: " << StringStreamToString(&val1_ss) << " vs " << " Actual: " << StringStreamToString(&val1_ss) << " vs "
<< StringStreamToString(&val2_ss); << StringStreamToString(&val2_ss);
} }
} // namespace internal } // namespace internal
// Asserts that val1 is less than, or almost equal to, val2. Fails // Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN. // otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult FloatLE(const char* expr1, const char* expr2, AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
float val1, float val2) { float val2) {
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
} }
// Asserts that val1 is less than, or almost equal to, val2. Fails // Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN. // otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult DoubleLE(const char* expr1, const char* expr2, AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
double val1, double val2) { double val2) {
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
} }
...@@ -1707,62 +1681,51 @@ namespace internal { ...@@ -1707,62 +1681,51 @@ namespace internal {
// The helper function for {ASSERT|EXPECT}_STREQ. // The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* lhs_expression, AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const char* lhs,
const char* lhs,
const char* rhs) { const char* rhs) {
if (String::CStringEquals(lhs, rhs)) { if (String::CStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), false);
PrintToString(lhs),
PrintToString(rhs),
false);
} }
// The helper function for {ASSERT|EXPECT}_STRCASEEQ. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const char* lhs,
const char* lhs,
const char* rhs) { const char* rhs) {
if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), true);
PrintToString(lhs),
PrintToString(rhs),
true);
} }
// The helper function for {ASSERT|EXPECT}_STRNE. // The helper function for {ASSERT|EXPECT}_STRNE.
AssertionResult CmpHelperSTRNE(const char* s1_expression, AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const char* s1,
const char* s1,
const char* s2) { const char* s2) {
if (!String::CStringEquals(s1, s2)) { if (!String::CStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} else { } else {
return AssertionFailure() << "Expected: (" << s1_expression << ") != (" return AssertionFailure()
<< s2_expression << "), actual: \"" << "Expected: (" << s1_expression << ") != (" << s2_expression
<< s1 << "\" vs \"" << s2 << "\""; << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
} }
} }
// The helper function for {ASSERT|EXPECT}_STRCASENE. // The helper function for {ASSERT|EXPECT}_STRCASENE.
AssertionResult CmpHelperSTRCASENE(const char* s1_expression, AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const char* s1,
const char* s1,
const char* s2) { const char* s2) {
if (!String::CaseInsensitiveCStringEquals(s1, s2)) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} else { } else {
return AssertionFailure() return AssertionFailure()
<< "Expected: (" << s1_expression << ") != (" << "Expected: (" << s1_expression << ") != (" << s2_expression
<< s2_expression << ") (ignoring case), actual: \"" << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
<< s1 << "\" vs \"" << s2 << "\"";
} }
} }
...@@ -1790,8 +1753,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { ...@@ -1790,8 +1753,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
// StringType here can be either ::std::string or ::std::wstring. // StringType here can be either ::std::string or ::std::wstring.
template <typename StringType> template <typename StringType>
bool IsSubstringPred(const StringType& needle, bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
const StringType& haystack) {
return haystack.find(needle) != StringType::npos; return haystack.find(needle) != StringType::npos;
} }
...@@ -1800,21 +1762,22 @@ bool IsSubstringPred(const StringType& needle, ...@@ -1800,21 +1762,22 @@ bool IsSubstringPred(const StringType& needle,
// StringType here can be const char*, const wchar_t*, ::std::string, // StringType here can be const char*, const wchar_t*, ::std::string,
// or ::std::wstring. // or ::std::wstring.
template <typename StringType> template <typename StringType>
AssertionResult IsSubstringImpl( AssertionResult IsSubstringImpl(bool expected_to_be_substring,
bool expected_to_be_substring, const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const StringType& needle, const StringType& haystack) { const StringType& needle,
const StringType& haystack) {
if (IsSubstringPred(needle, haystack) == expected_to_be_substring) if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
return AssertionSuccess(); return AssertionSuccess();
const bool is_wide_string = sizeof(needle[0]) > 1; const bool is_wide_string = sizeof(needle[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure() return AssertionFailure()
<< "Value of: " << needle_expr << "\n" << "Value of: " << needle_expr << "\n"
<< " Actual: " << begin_string_quote << needle << "\"\n" << " Actual: " << begin_string_quote << needle << "\"\n"
<< "Expected: " << (expected_to_be_substring ? "" : "not ") << "Expected: " << (expected_to_be_substring ? "" : "not ")
<< "a substring of " << haystack_expr << "\n" << "a substring of " << haystack_expr << "\n"
<< "Which is: " << begin_string_quote << haystack << "\""; << "Which is: " << begin_string_quote << haystack << "\"";
} }
} // namespace } // namespace
...@@ -1823,52 +1786,52 @@ AssertionResult IsSubstringImpl( ...@@ -1823,52 +1786,52 @@ AssertionResult IsSubstringImpl(
// substring of haystack (NULL is considered a substring of itself // substring of haystack (NULL is considered a substring of itself
// only), and return an appropriate error message when they fail. // only), and return an appropriate error message when they fail.
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) {
const char* needle, const char* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) {
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr, const char* needle,
const char* needle, const char* haystack) { const char* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr, const wchar_t* needle,
const wchar_t* needle, const wchar_t* haystack) { const wchar_t* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const ::std::string& needle,
const ::std::string& needle, const ::std::string& haystack) { const ::std::string& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) { const ::std::string& needle,
const ::std::string& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle,
const ::std::wstring& needle, const ::std::wstring& haystack) { const ::std::wstring& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) { const ::std::wstring& needle,
const ::std::wstring& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
...@@ -1880,43 +1843,42 @@ namespace internal { ...@@ -1880,43 +1843,42 @@ namespace internal {
namespace { namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates // Helper function for IsHRESULT{SuccessFailure} predicates
AssertionResult HRESULTFailureHelper(const char* expr, AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
const char* expected,
long hr) { // NOLINT long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
// Windows CE doesn't support FormatMessage. // Windows CE doesn't support FormatMessage.
const char error_text[] = ""; const char error_text[] = "";
# else #else
// Looks up the human-readable system message for the HRESULT code // Looks up the human-readable system message for the HRESULT code
// and since we're not passing any params to FormatMessage, we don't // and since we're not passing any params to FormatMessage, we don't
// want inserts expanded. // want inserts expanded.
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | const DWORD kFlags =
FORMAT_MESSAGE_IGNORE_INSERTS; FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD kBufSize = 4096; const DWORD kBufSize = 4096;
// Gets the system's human readable message string for this HRESULT. // Gets the system's human readable message string for this HRESULT.
char error_text[kBufSize] = { '\0' }; char error_text[kBufSize] = {'\0'};
DWORD message_length = ::FormatMessageA(kFlags, DWORD message_length = ::FormatMessageA(kFlags,
0, // no source, we're asking system 0, // no source, we're asking system
static_cast<DWORD>(hr), // the error static_cast<DWORD>(hr), // the error
0, // no line width restrictions 0, // no line width restrictions
error_text, // output buffer error_text, // output buffer
kBufSize, // buf size kBufSize, // buf size
nullptr); // no arguments for inserts nullptr); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF) // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]); for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) { --message_length) {
error_text[message_length - 1] = '\0'; error_text[message_length - 1] = '\0';
} }
# endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
const std::string error_hex("0x" + String::FormatHexInt(hr)); const std::string error_hex("0x" + String::FormatHexInt(hr));
return ::testing::AssertionFailure() return ::testing::AssertionFailure()
<< "Expected: " << expr << " " << expected << ".\n" << "Expected: " << expr << " " << expected << ".\n"
<< " Actual: " << error_hex << " " << error_text << "\n"; << " Actual: " << error_hex << " " << error_text << "\n";
} }
} // namespace } // namespace
...@@ -1950,16 +1912,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT ...@@ -1950,16 +1912,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// The maximum code-point a one-byte UTF-8 sequence can represent. // The maximum code-point a one-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
// The maximum code-point a two-byte UTF-8 sequence can represent. // The maximum code-point a two-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1; constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent. // The maximum code-point a three-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1; constexpr uint32_t kMaxCodePoint3 =
(static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
// The maximum code-point a four-byte UTF-8 sequence can represent. // The maximum code-point a four-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1; constexpr uint32_t kMaxCodePoint4 =
(static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
// Chops off the n lowest bits from a bit pattern. Returns the n // Chops off the n lowest bits from a bit pattern. Returns the n
// lowest bits. As a side effect, the original bit pattern will be // lowest bits. As a side effect, the original bit pattern will be
...@@ -1984,7 +1948,7 @@ std::string CodePointToUtf8(uint32_t code_point) { ...@@ -1984,7 +1948,7 @@ std::string CodePointToUtf8(uint32_t code_point) {
char str[5]; // Big enough for the largest valid code point. char str[5]; // Big enough for the largest valid code point.
if (code_point <= kMaxCodePoint1) { if (code_point <= kMaxCodePoint1) {
str[1] = '\0'; str[1] = '\0';
str[0] = static_cast<char>(code_point); // 0xxxxxxx str[0] = static_cast<char>(code_point); // 0xxxxxxx
} else if (code_point <= kMaxCodePoint2) { } else if (code_point <= kMaxCodePoint2) {
str[2] = '\0'; str[2] = '\0';
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
...@@ -2012,8 +1976,8 @@ std::string CodePointToUtf8(uint32_t code_point) { ...@@ -2012,8 +1976,8 @@ std::string CodePointToUtf8(uint32_t code_point) {
// and thus should be combined into a single Unicode code point // and thus should be combined into a single Unicode code point
// using CreateCodePointFromUtf16SurrogatePair. // using CreateCodePointFromUtf16SurrogatePair.
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
return sizeof(wchar_t) == 2 && return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; (second & 0xFC00) == 0xDC00;
} }
// Creates a Unicode code point from UTF16 surrogate pair. // Creates a Unicode code point from UTF16 surrogate pair.
...@@ -2044,8 +2008,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, ...@@ -2044,8 +2008,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
// and contains invalid UTF-16 surrogate pairs, values in those pairs // and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane. // will be encoded as individual Unicode characters from Basic Normal Plane.
std::string WideStringToUtf8(const wchar_t* str, int num_chars) { std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (num_chars == -1) if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
num_chars = static_cast<int>(wcslen(str));
::std::stringstream stream; ::std::stringstream stream;
for (int i = 0; i < num_chars; ++i) { for (int i = 0; i < num_chars; ++i) {
...@@ -2054,8 +2017,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { ...@@ -2054,8 +2017,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (str[i] == L'\0') { if (str[i] == L'\0') {
break; break;
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], unicode_code_point =
str[i + 1]); CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
i++; i++;
} else { } else {
unicode_code_point = static_cast<uint32_t>(str[i]); unicode_code_point = static_cast<uint32_t>(str[i]);
...@@ -2068,7 +2031,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { ...@@ -2068,7 +2031,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
// Converts a wide C string to an std::string using the UTF-8 encoding. // Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)". // NULL will be converted to "(null)".
std::string String::ShowWideCString(const wchar_t * wide_c_str) { std::string String::ShowWideCString(const wchar_t* wide_c_str) {
if (wide_c_str == nullptr) return "(null)"; if (wide_c_str == nullptr) return "(null)";
return internal::WideStringToUtf8(wide_c_str, -1); return internal::WideStringToUtf8(wide_c_str, -1);
...@@ -2080,7 +2043,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { ...@@ -2080,7 +2043,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) {
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string, // C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
...@@ -2090,33 +2053,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { ...@@ -2090,33 +2053,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
// Helper function for *_STREQ on wide strings. // Helper function for *_STREQ on wide strings.
AssertionResult CmpHelperSTREQ(const char* lhs_expression, AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const wchar_t* lhs,
const wchar_t* lhs,
const wchar_t* rhs) { const wchar_t* rhs) {
if (String::WideCStringEquals(lhs, rhs)) { if (String::WideCStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), false);
PrintToString(lhs),
PrintToString(rhs),
false);
} }
// Helper function for *_STRNE on wide strings. // Helper function for *_STRNE on wide strings.
AssertionResult CmpHelperSTRNE(const char* s1_expression, AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const wchar_t* s1,
const wchar_t* s1,
const wchar_t* s2) { const wchar_t* s2) {
if (!String::WideCStringEquals(s1, s2)) { if (!String::WideCStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return AssertionFailure() << "Expected: (" << s1_expression << ") != (" return AssertionFailure()
<< s2_expression << "), actual: " << "Expected: (" << s1_expression << ") != (" << s2_expression
<< PrintToString(s1) << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
<< " vs " << PrintToString(s2);
} }
// Compares two C strings, ignoring case. Returns true if and only if they have // Compares two C strings, ignoring case. Returns true if and only if they have
...@@ -2125,7 +2082,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, ...@@ -2125,7 +2082,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression,
// Unlike strcasecmp(), this function can handle NULL argument(s). A // Unlike strcasecmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string, // NULL C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
return posix::StrCaseCmp(lhs, rhs) == 0; return posix::StrCaseCmp(lhs, rhs) == 0;
...@@ -2167,8 +2124,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, ...@@ -2167,8 +2124,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
// Returns true if and only if str ends with the given suffix, ignoring case. // Returns true if and only if str ends with the given suffix, ignoring case.
// Any string is considered to end with an empty suffix. // Any string is considered to end with an empty suffix.
bool String::EndsWithCaseInsensitive( bool String::EndsWithCaseInsensitive(const std::string& str,
const std::string& str, const std::string& suffix) { const std::string& suffix) {
const size_t str_len = str.length(); const size_t str_len = str.length();
const size_t suffix_len = suffix.length(); const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) && return (str_len >= suffix_len) &&
...@@ -2251,15 +2208,13 @@ TestResult::TestResult() ...@@ -2251,15 +2208,13 @@ TestResult::TestResult()
: death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
// D'tor. // D'tor.
TestResult::~TestResult() { TestResult::~TestResult() {}
}
// Returns the i-th test part result among all the results. i can // Returns the i-th test part result among all the results. i can
// range from 0 to total_part_count() - 1. If i is not in that range, // range from 0 to total_part_count() - 1. If i is not in that range,
// aborts the program. // aborts the program.
const TestPartResult& TestResult::GetTestPartResult(int i) const { const TestPartResult& TestResult::GetTestPartResult(int i) const {
if (i < 0 || i >= total_part_count()) if (i < 0 || i >= total_part_count()) internal::posix::Abort();
internal::posix::Abort();
return test_part_results_.at(static_cast<size_t>(i)); return test_part_results_.at(static_cast<size_t>(i));
} }
...@@ -2267,15 +2222,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const { ...@@ -2267,15 +2222,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const {
// test_property_count() - 1. If i is not in that range, aborts the // test_property_count() - 1. If i is not in that range, aborts the
// program. // program.
const TestProperty& TestResult::GetTestProperty(int i) const { const TestProperty& TestResult::GetTestProperty(int i) const {
if (i < 0 || i >= test_property_count()) if (i < 0 || i >= test_property_count()) internal::posix::Abort();
internal::posix::Abort();
return test_properties_.at(static_cast<size_t>(i)); return test_properties_.at(static_cast<size_t>(i));
} }
// Clears the test part results. // Clears the test part results.
void TestResult::ClearTestPartResults() { void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
test_part_results_.clear();
}
// Adds a test part result to the list. // Adds a test part result to the list.
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
...@@ -2304,15 +2256,8 @@ void TestResult::RecordProperty(const std::string& xml_element, ...@@ -2304,15 +2256,8 @@ void TestResult::RecordProperty(const std::string& xml_element,
// The list of reserved attributes used in the <testsuites> element of XML // The list of reserved attributes used in the <testsuites> element of XML
// output. // output.
static const char* const kReservedTestSuitesAttributes[] = { static const char* const kReservedTestSuitesAttributes[] = {
"disabled", "disabled", "errors", "failures", "name",
"errors", "random_seed", "tests", "time", "timestamp"};
"failures",
"name",
"random_seed",
"tests",
"time",
"timestamp"
};
// The list of reserved attributes used in the <testsuite> element of XML // The list of reserved attributes used in the <testsuite> element of XML
// output. // output.
...@@ -2322,8 +2267,8 @@ static const char* const kReservedTestSuiteAttributes[] = { ...@@ -2322,8 +2267,8 @@ static const char* const kReservedTestSuiteAttributes[] = {
// The list of reserved attributes used in the <testcase> element of XML output. // The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = { static const char* const kReservedTestCaseAttributes[] = {
"classname", "name", "status", "time", "type_param", "classname", "name", "status", "time",
"value_param", "file", "line"}; "type_param", "value_param", "file", "line"};
// Use a slightly different set for allowed output to ensure existing tests can // Use a slightly different set for allowed output to ensure existing tests can
// still RecordProperty("result") or "RecordProperty(timestamp") // still RecordProperty("result") or "RecordProperty(timestamp")
...@@ -2385,7 +2330,7 @@ static bool ValidateTestPropertyName( ...@@ -2385,7 +2330,7 @@ static bool ValidateTestPropertyName(
const std::string& property_name, const std::string& property_name,
const std::vector<std::string>& reserved_names) { const std::vector<std::string>& reserved_names) {
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
reserved_names.end()) { reserved_names.end()) {
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
<< " (" << FormatWordList(reserved_names) << " (" << FormatWordList(reserved_names)
<< " are reserved by " << GTEST_NAME_ << ")"; << " are reserved by " << GTEST_NAME_ << ")";
...@@ -2423,8 +2368,7 @@ bool TestResult::Skipped() const { ...@@ -2423,8 +2368,7 @@ bool TestResult::Skipped() const {
// Returns true if and only if the test failed. // Returns true if and only if the test failed.
bool TestResult::Failed() const { bool TestResult::Failed() const {
for (int i = 0; i < total_part_count(); ++i) { for (int i = 0; i < total_part_count(); ++i) {
if (GetTestPartResult(i).failed()) if (GetTestPartResult(i).failed()) return true;
return true;
} }
return false; return false;
} }
...@@ -2465,27 +2409,22 @@ int TestResult::test_property_count() const { ...@@ -2465,27 +2409,22 @@ int TestResult::test_property_count() const {
// Creates a Test object. // Creates a Test object.
// The c'tor saves the states of all flags. // The c'tor saves the states of all flags.
Test::Test() Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
: gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
}
// The d'tor restores the states of all flags. The actual work is // The d'tor restores the states of all flags. The actual work is
// done by the d'tor of the gtest_flag_saver_ field, and thus not // done by the d'tor of the gtest_flag_saver_ field, and thus not
// visible here. // visible here.
Test::~Test() { Test::~Test() {}
}
// Sets up the test fixture. // Sets up the test fixture.
// //
// A sub-class may override this. // A sub-class may override this.
void Test::SetUp() { void Test::SetUp() {}
}
// Tears down the test fixture. // Tears down the test fixture.
// //
// A sub-class may override this. // A sub-class may override this.
void Test::TearDown() { void Test::TearDown() {}
}
// Allows user supplied key value pairs to be recorded for later output. // Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, const std::string& value) { void Test::RecordProperty(const std::string& key, const std::string& value) {
...@@ -2590,8 +2529,8 @@ bool Test::HasSameFixtureClass() { ...@@ -2590,8 +2529,8 @@ bool Test::HasSameFixtureClass() {
static std::string* FormatSehExceptionMessage(DWORD exception_code, static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) { const char* location) {
Message message; Message message;
message << "SEH exception with code 0x" << std::setbase(16) << message << "SEH exception with code 0x" << std::setbase(16) << exception_code
exception_code << std::setbase(10) << " thrown in " << location << "."; << std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString()); return new std::string(message.GetString());
} }
...@@ -2634,8 +2573,8 @@ GoogleTestFailureException::GoogleTestFailureException( ...@@ -2634,8 +2573,8 @@ GoogleTestFailureException::GoogleTestFailureException(
// exceptions in the same function. Therefore, we provide a separate // exceptions in the same function. Therefore, we provide a separate
// wrapper function for handling SEH exceptions.) // wrapper function for handling SEH exceptions.)
template <class T, typename Result> template <class T, typename Result>
Result HandleSehExceptionsInMethodIfSupported( Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
T* object, Result (T::*method)(), const char* location) { const char* location) {
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
__try { __try {
return (object->*method)(); return (object->*method)();
...@@ -2644,8 +2583,8 @@ Result HandleSehExceptionsInMethodIfSupported( ...@@ -2644,8 +2583,8 @@ Result HandleSehExceptionsInMethodIfSupported(
// We create the exception message on the heap because VC++ prohibits // We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try // creation of objects with destructors on stack in functions using __try
// (see error C2712). // (see error C2712).
std::string* exception_message = FormatSehExceptionMessage( std::string* exception_message =
GetExceptionCode(), location); FormatSehExceptionMessage(GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message); *exception_message);
delete exception_message; delete exception_message;
...@@ -2661,8 +2600,8 @@ Result HandleSehExceptionsInMethodIfSupported( ...@@ -2661,8 +2600,8 @@ Result HandleSehExceptionsInMethodIfSupported(
// exceptions, if they are supported; returns the 0-value for type // exceptions, if they are supported; returns the 0-value for type
// Result in case of an SEH exception. // Result in case of an SEH exception.
template <class T, typename Result> template <class T, typename Result>
Result HandleExceptionsInMethodIfSupported( Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
T* object, Result (T::*method)(), const char* location) { const char* location) {
// NOTE: The user code can affect the way in which Google Test handles // NOTE: The user code can affect the way in which Google Test handles
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
// RUN_ALL_TESTS() starts. It is technically possible to check the flag // RUN_ALL_TESTS() starts. It is technically possible to check the flag
...@@ -2728,16 +2667,16 @@ void Test::Run() { ...@@ -2728,16 +2667,16 @@ void Test::Run() {
// GTEST_SKIP(). // GTEST_SKIP().
if (!HasFatalFailure() && !IsSkipped()) { if (!HasFatalFailure() && !IsSkipped()) {
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
this, &Test::TestBody, "the test body"); "the test body");
} }
// However, we want to clean up as much as possible. Hence we will // However, we want to clean up as much as possible. Hence we will
// always call TearDown(), even if SetUp() or the test body has // always call TearDown(), even if SetUp() or the test body has
// failed. // failed.
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
this, &Test::TearDown, "TearDown()"); "TearDown()");
} }
// Returns true if and only if the current test has a fatal failure. // Returns true if and only if the current test has a fatal failure.
...@@ -2747,8 +2686,9 @@ bool Test::HasFatalFailure() { ...@@ -2747,8 +2686,9 @@ bool Test::HasFatalFailure() {
// Returns true if and only if the current test has a non-fatal failure. // Returns true if and only if the current test has a non-fatal failure.
bool Test::HasNonfatalFailure() { bool Test::HasNonfatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()-> return internal::GetUnitTestImpl()
HasNonfatalFailure(); ->current_test_result()
->HasNonfatalFailure();
} }
// Returns true if and only if the current test was skipped. // Returns true if and only if the current test was skipped.
...@@ -2848,11 +2788,10 @@ class TestNameIs { ...@@ -2848,11 +2788,10 @@ class TestNameIs {
// Constructor. // Constructor.
// //
// TestNameIs has NO default constructor. // TestNameIs has NO default constructor.
explicit TestNameIs(const char* name) explicit TestNameIs(const char* name) : name_(name) {}
: name_(name) {}
// Returns true if and only if the test name of test_info matches name_. // Returns true if and only if the test name of test_info matches name_.
bool operator()(const TestInfo * test_info) const { bool operator()(const TestInfo* test_info) const {
return test_info && test_info->name() == name_; return test_info && test_info->name() == name_;
} }
...@@ -3145,11 +3084,10 @@ void TestSuite::UnshuffleTests() { ...@@ -3145,11 +3084,10 @@ void TestSuite::UnshuffleTests() {
// //
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books". // FormatCountableNoun(5, "book", "books") returns "5 books".
static std::string FormatCountableNoun(int count, static std::string FormatCountableNoun(int count, const char* singular_form,
const char * singular_form, const char* plural_form) {
const char * plural_form) {
return internal::StreamableToString(count) + " " + return internal::StreamableToString(count) + " " +
(count == 1 ? singular_form : plural_form); (count == 1 ? singular_form : plural_form);
} }
// Formats the count of tests. // Formats the count of tests.
...@@ -3166,7 +3104,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) { ...@@ -3166,7 +3104,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) {
// representation. Both kNonFatalFailure and kFatalFailure are translated // representation. Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference // to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result. // between the two when viewing the test result.
static const char * TestPartResultTypeToString(TestPartResult::Type type) { static const char* TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) { switch (type) {
case TestPartResult::kSkip: case TestPartResult::kSkip:
return "Skipped\n"; return "Skipped\n";
...@@ -3193,17 +3131,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow }; ...@@ -3193,17 +3131,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow };
// Prints a TestPartResult to an std::string. // Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString( static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) { const TestPartResult& test_part_result) {
return (Message() return (Message() << internal::FormatFileLocation(
<< internal::FormatFileLocation(test_part_result.file_name(), test_part_result.file_name(),
test_part_result.line_number()) test_part_result.line_number())
<< " " << TestPartResultTypeToString(test_part_result.type()) << " "
<< test_part_result.message()).GetString(); << TestPartResultTypeToString(test_part_result.type())
<< test_part_result.message())
.GetString();
} }
// Prints a TestPartResult. // Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) { static void PrintTestPartResult(const TestPartResult& test_part_result) {
const std::string& result = const std::string& result = PrintTestPartResultToString(test_part_result);
PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str()); printf("%s\n", result.c_str());
fflush(stdout); fflush(stdout);
// If the test program runs in Visual Studio or a debugger, the // If the test program runs in Visual Studio or a debugger, the
...@@ -3220,8 +3159,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { ...@@ -3220,8 +3159,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
} }
// class PrettyUnitTestResultPrinter // class PrettyUnitTestResultPrinter
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
// Returns the character attribute for the given color. // Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) { static WORD GetColorAttribute(GTestColor color) {
...@@ -3232,7 +3171,8 @@ static WORD GetColorAttribute(GTestColor color) { ...@@ -3232,7 +3171,8 @@ static WORD GetColorAttribute(GTestColor color) {
return FOREGROUND_GREEN; return FOREGROUND_GREEN;
case GTestColor::kYellow: case GTestColor::kYellow:
return FOREGROUND_RED | FOREGROUND_GREEN; return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0; default:
return 0;
} }
} }
...@@ -3316,9 +3256,9 @@ bool ShouldUseColor(bool stdout_is_tty) { ...@@ -3316,9 +3256,9 @@ bool ShouldUseColor(bool stdout_is_tty) {
} }
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
String::CStringEquals(gtest_color, "1"); String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the // We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to // value is neither one of these nor "auto", we treat it as "no" to
// be conservative. // be conservative.
...@@ -3330,7 +3270,7 @@ bool ShouldUseColor(bool stdout_is_tty) { ...@@ -3330,7 +3270,7 @@ bool ShouldUseColor(bool stdout_is_tty) {
// that would be colored when printed, as can be done on Linux. // that would be colored when printed, as can be done on Linux.
GTEST_ATTRIBUTE_PRINTF_(2, 3) GTEST_ATTRIBUTE_PRINTF_(2, 3)
static void ColoredPrintf(GTestColor color, const char *fmt, ...) { static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
...@@ -3349,8 +3289,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) { ...@@ -3349,8 +3289,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
return; return;
} }
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color. // Gets the current text color.
...@@ -3442,7 +3382,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener { ...@@ -3442,7 +3382,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
static void PrintSkippedTests(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test);
}; };
// Fired before each iteration of tests starts. // Fired before each iteration of tests starts.
void PrettyUnitTestResultPrinter::OnTestIterationStart( void PrettyUnitTestResultPrinter::OnTestIterationStart(
const UnitTest& unit_test, int iteration) { const UnitTest& unit_test, int iteration) {
if (GTEST_FLAG_GET(repeat) != 1) if (GTEST_FLAG_GET(repeat) != 1)
...@@ -3552,12 +3492,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ...@@ -3552,12 +3492,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
} }
PrintTestName(test_info.test_suite_name(), test_info.name()); PrintTestName(test_info.test_suite_name(), test_info.name());
if (test_info.result()->Failed()) if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
PrintFullTestCommentIfPresent(test_info);
if (GTEST_FLAG_GET(print_time)) { if (GTEST_FLAG_GET(print_time)) {
printf(" (%s ms)\n", internal::StreamableToString( printf(" (%s ms)\n",
test_info.result()->elapsed_time()).c_str()); internal::StreamableToString(test_info.result()->elapsed_time())
.c_str());
} else { } else {
printf("\n"); printf("\n");
} }
...@@ -3819,7 +3759,7 @@ class TestEventRepeater : public TestEventListener { ...@@ -3819,7 +3759,7 @@ class TestEventRepeater : public TestEventListener {
public: public:
TestEventRepeater() : forwarding_enabled_(true) {} TestEventRepeater() : forwarding_enabled_(true) {}
~TestEventRepeater() override; ~TestEventRepeater() override;
void Append(TestEventListener *listener); void Append(TestEventListener* listener);
TestEventListener* Release(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false // Controls whether events will be forwarded to listeners_. Set to false
...@@ -3864,11 +3804,11 @@ TestEventRepeater::~TestEventRepeater() { ...@@ -3864,11 +3804,11 @@ TestEventRepeater::~TestEventRepeater() {
ForEach(listeners_, Delete<TestEventListener>); ForEach(listeners_, Delete<TestEventListener>);
} }
void TestEventRepeater::Append(TestEventListener *listener) { void TestEventRepeater::Append(TestEventListener* listener) {
listeners_.push_back(listener); listeners_.push_back(listener);
} }
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
for (size_t i = 0; i < listeners_.size(); ++i) { for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) { if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + static_cast<int>(i)); listeners_.erase(listeners_.begin() + static_cast<int>(i));
...@@ -3881,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { ...@@ -3881,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
// Since most methods are very similar, use macros to reduce boilerplate. // Since most methods are very similar, use macros to reduce boilerplate.
// This defines a member that forwards the call to all listeners. // This defines a member that forwards the call to all listeners.
#define GTEST_REPEATER_METHOD_(Name, Type) \ #define GTEST_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \ void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \ if (forwarding_enabled_) { \
for (size_t i = 0; i < listeners_.size(); i++) { \ for (size_t i = 0; i < listeners_.size(); i++) { \
listeners_[i]->Name(parameter); \ listeners_[i]->Name(parameter); \
} \ } \
} \ } \
} }
// This defines a member that forwards the call to all listeners in reverse // This defines a member that forwards the call to all listeners in reverse
// order. // order.
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
...@@ -4075,8 +4015,8 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter( ...@@ -4075,8 +4015,8 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
// module will consist of ordinary English text. // module will consist of ordinary English text.
// If this module is ever modified to produce version 1.1 XML output, // If this module is ever modified to produce version 1.1 XML output,
// most invalid characters can be retained using character references. // most invalid characters can be retained using character references.
std::string XmlUnitTestResultPrinter::EscapeXml( std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
const std::string& str, bool is_attribute) { bool is_attribute) {
Message m; Message m;
for (size_t i = 0; i < str.size(); ++i) { for (size_t i = 0; i < str.size(); ++i) {
...@@ -4183,12 +4123,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { ...@@ -4183,12 +4123,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
return ""; return "";
// YYYY-MM-DDThh:mm:ss.sss // YYYY-MM-DDThh:mm:ss.sss
return StreamableToString(time_struct.tm_year + 1900) + "-" + return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec) + "." + String::FormatIntWidth2(time_struct.tm_sec) + "." +
String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
} }
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
...@@ -4199,8 +4139,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, ...@@ -4199,8 +4139,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
for (;;) { for (;;) {
const char* const next_segment = strstr(segment, "]]>"); const char* const next_segment = strstr(segment, "]]>");
if (next_segment != nullptr) { if (next_segment != nullptr) {
stream->write( stream->write(segment,
segment, static_cast<std::streamsize>(next_segment - segment)); static_cast<std::streamsize>(next_segment - segment));
*stream << "]]>]]&gt;<![CDATA["; *stream << "]]>]]&gt;<![CDATA[";
segment = next_segment + strlen("]]>"); segment = next_segment + strlen("]]>");
} else { } else {
...@@ -4212,15 +4152,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, ...@@ -4212,15 +4152,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
} }
void XmlUnitTestResultPrinter::OutputXmlAttribute( void XmlUnitTestResultPrinter::OutputXmlAttribute(
std::ostream* stream, std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name, const std::string& value) {
const std::string& name,
const std::string& value) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Attribute " << name << " is not allowed for element <" << element_name << "Attribute " << name << " is not allowed for element <" << element_name
<< ">."; << ">.";
...@@ -4325,8 +4263,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, ...@@ -4325,8 +4263,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
internal::FormatCompilerIndependentFileLocation(part.file_name(), internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number()); part.line_number());
const std::string summary = location + "\n" + part.summary(); const std::string summary = location + "\n" + part.summary();
*stream << " <failure message=\"" *stream << " <failure message=\"" << EscapeXmlAttribute(summary)
<< EscapeXmlAttribute(summary)
<< "\" type=\"\">"; << "\" type=\"\">";
const std::string detail = location + "\n" + part.message(); const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
...@@ -4467,7 +4404,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( ...@@ -4467,7 +4404,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
for (int i = 0; i < result.test_property_count(); ++i) { for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i); const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "=" attributes << " " << property.key() << "="
<< "\"" << EscapeXmlAttribute(property.value()) << "\""; << "\"" << EscapeXmlAttribute(property.value()) << "\"";
} }
return attributes.GetString(); return attributes.GetString();
} }
...@@ -4513,16 +4450,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { ...@@ -4513,16 +4450,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
//// streams the attribute as JSON. //// streams the attribute as JSON.
static void OutputJsonKey(std::ostream* stream, static void OutputJsonKey(std::ostream* stream,
const std::string& element_name, const std::string& element_name,
const std::string& name, const std::string& name, const std::string& value,
const std::string& value, const std::string& indent, bool comma = true);
const std::string& indent,
bool comma = true);
static void OutputJsonKey(std::ostream* stream, static void OutputJsonKey(std::ostream* stream,
const std::string& element_name, const std::string& element_name,
const std::string& name, const std::string& name, int value,
int value, const std::string& indent, bool comma = true);
const std::string& indent,
bool comma = true);
// Streams a test suite JSON stanza containing the given test result. // Streams a test suite JSON stanza containing the given test result.
// //
...@@ -4567,7 +4500,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) ...@@ -4567,7 +4500,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
} }
void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) { int /*iteration*/) {
FILE* jsonout = OpenFileForWriting(output_file_); FILE* jsonout = OpenFileForWriting(output_file_);
std::stringstream stream; std::stringstream stream;
PrintJsonUnitTest(&stream, unit_test); PrintJsonUnitTest(&stream, unit_test);
...@@ -4633,55 +4566,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { ...@@ -4633,55 +4566,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
return ""; return "";
// YYYY-MM-DDThh:mm:ss // YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct.tm_year + 1900) + "-" + return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec) + "Z"; String::FormatIntWidth2(time_struct.tm_sec) + "Z";
} }
static inline std::string Indent(size_t width) { static inline std::string Indent(size_t width) {
return std::string(width, ' '); return std::string(width, ' ');
} }
void JsonUnitTestResultPrinter::OutputJsonKey( void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name,
const std::string& name, const std::string& value,
const std::string& value, const std::string& indent,
const std::string& indent, bool comma) {
bool comma) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name << "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\"."; << "\".";
*stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
if (comma) if (comma) *stream << ",\n";
*stream << ",\n";
} }
void JsonUnitTestResultPrinter::OutputJsonKey( void JsonUnitTestResultPrinter::OutputJsonKey(
std::ostream* stream, std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma) {
const std::string& name,
int value,
const std::string& indent,
bool comma) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name << "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\"."; << "\".";
*stream << indent << "\"" << name << "\": " << StreamableToString(value); *stream << indent << "\"" << name << "\": " << StreamableToString(value);
if (comma) if (comma) *stream << ",\n";
*stream << ",\n";
} }
// Streams a test suite JSON stanza containing the given test result. // Streams a test suite JSON stanza containing the given test result.
...@@ -4784,7 +4710,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, ...@@ -4784,7 +4710,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
if (part.failed()) { if (part.failed()) {
*stream << ",\n"; *stream << ",\n";
if (++failures == 1) { if (++failures == 1) {
*stream << kIndent << "\"" << "failures" << "\": [\n"; *stream << kIndent << "\""
<< "failures"
<< "\": [\n";
} }
const std::string location = const std::string location =
internal::FormatCompilerIndependentFileLocation(part.file_name(), internal::FormatCompilerIndependentFileLocation(part.file_name(),
...@@ -4797,8 +4725,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, ...@@ -4797,8 +4725,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
} }
} }
if (failures > 0) if (failures > 0) *stream << "\n" << kIndent << "]";
*stream << "\n" << kIndent << "]";
*stream << "\n" << Indent(8) << "}"; *stream << "\n" << Indent(8) << "}";
} }
...@@ -4894,7 +4821,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, ...@@ -4894,7 +4821,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
} }
*stream << "\n" << kIndent << "]\n" << "}\n"; *stream << "\n"
<< kIndent << "]\n"
<< "}\n";
} }
void JsonUnitTestResultPrinter::PrintJsonTestList( void JsonUnitTestResultPrinter::PrintJsonTestList(
...@@ -4929,7 +4858,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( ...@@ -4929,7 +4858,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
Message attributes; Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) { for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i); const TestProperty& property = result.GetTestProperty(i);
attributes << ",\n" << indent << "\"" << property.key() << "\": " attributes << ",\n"
<< indent << "\"" << property.key() << "\": "
<< "\"" << EscapeJson(property.value()) << "\""; << "\"" << EscapeJson(property.value()) << "\"";
} }
return attributes.GetString(); return attributes.GetString();
...@@ -4969,14 +4899,14 @@ void StreamingListener::SocketWriter::MakeConnection() { ...@@ -4969,14 +4899,14 @@ void StreamingListener::SocketWriter::MakeConnection() {
addrinfo hints; addrinfo hints;
memset(&hints, 0, sizeof(hints)); memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
addrinfo* servinfo = nullptr; addrinfo* servinfo = nullptr;
// Use the getaddrinfo() to get a linked list of IP addresses for // Use the getaddrinfo() to get a linked list of IP addresses for
// the given host name. // the given host name.
const int error_num = getaddrinfo( const int error_num =
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
if (error_num != 0) { if (error_num != 0) {
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
<< gai_strerror(error_num); << gai_strerror(error_num);
...@@ -4985,8 +4915,8 @@ void StreamingListener::SocketWriter::MakeConnection() { ...@@ -4985,8 +4915,8 @@ void StreamingListener::SocketWriter::MakeConnection() {
// Loop through all the results and connect to the first we can. // Loop through all the results and connect to the first we can.
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
cur_addr = cur_addr->ai_next) { cur_addr = cur_addr->ai_next) {
sockfd_ = socket( sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); cur_addr->ai_protocol);
if (sockfd_ != -1) { if (sockfd_ != -1) {
// Connect the client socket to the server socket. // Connect the client socket to the server socket.
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
...@@ -5055,7 +4985,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) ...@@ -5055,7 +4985,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
return result; return result;
#else // !GTEST_HAS_ABSL #else // !GTEST_HAS_ABSL
static_cast<void>(max_depth); static_cast<void>(max_depth);
static_cast<void>(skip_count); static_cast<void>(skip_count);
return ""; return "";
...@@ -5079,8 +5009,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { ...@@ -5079,8 +5009,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
class ScopedPrematureExitFile { class ScopedPrematureExitFile {
public: public:
explicit ScopedPrematureExitFile(const char* premature_exit_filepath) explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
: premature_exit_filepath_(premature_exit_filepath ? : premature_exit_filepath_(
premature_exit_filepath : "") { premature_exit_filepath ? premature_exit_filepath : "") {
// If a path to the premature-exit file is specified... // If a path to the premature-exit file is specified...
if (!premature_exit_filepath_.empty()) { if (!premature_exit_filepath_.empty()) {
// create the file with a single "0" character in it. I/O // create the file with a single "0" character in it. I/O
...@@ -5282,7 +5212,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } ...@@ -5282,7 +5212,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
// Gets the time of the test program start, in ms from the start of the // Gets the time of the test program start, in ms from the start of the
// UNIX epoch. // UNIX epoch.
internal::TimeInMillis UnitTest::start_timestamp() const { internal::TimeInMillis UnitTest::start_timestamp() const {
return impl()->start_timestamp(); return impl()->start_timestamp();
} }
// Gets the elapsed time, in milliseconds. // Gets the elapsed time, in milliseconds.
...@@ -5325,9 +5255,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) { ...@@ -5325,9 +5255,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) {
// Returns the list of event listeners that can be used to track events // Returns the list of event listeners that can be used to track events
// inside Google Test. // inside Google Test.
TestEventListeners& UnitTest::listeners() { TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
return *impl()->listeners();
}
// Registers and returns a global test environment. When a test // Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in the // program is run, all global test environments will be set-up in the
...@@ -5352,12 +5280,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) { ...@@ -5352,12 +5280,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) {
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
// this to report their results. The user code should use the // this to report their results. The user code should use the
// assertion macros instead of calling this directly. // assertion macros instead of calling this directly.
void UnitTest::AddTestPartResult( void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
TestPartResult::Type result_type, const char* file_name, int line_number,
const char* file_name, const std::string& message,
int line_number, const std::string& os_stack_trace)
const std::string& message, GTEST_LOCK_EXCLUDED_(mutex_) {
const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg; Message msg;
msg << message; msg << message;
...@@ -5367,8 +5294,9 @@ void UnitTest::AddTestPartResult( ...@@ -5367,8 +5294,9 @@ void UnitTest::AddTestPartResult(
for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) msg << "\n"
<< " " << trace.message; << internal::FormatFileLocation(trace.file, trace.line) << " "
<< trace.message;
} }
} }
...@@ -5378,8 +5306,8 @@ void UnitTest::AddTestPartResult( ...@@ -5378,8 +5306,8 @@ void UnitTest::AddTestPartResult(
const TestPartResult result = TestPartResult( const TestPartResult result = TestPartResult(
result_type, file_name, line_number, msg.GetString().c_str()); result_type, file_name, line_number, msg.GetString().c_str());
impl_->GetTestPartResultReporterForCurrentThread()-> impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
ReportTestPartResult(result); result);
if (result_type != TestPartResult::kSuccess && if (result_type != TestPartResult::kSuccess &&
result_type != TestPartResult::kSkip) { result_type != TestPartResult::kSkip) {
...@@ -5472,20 +5400,20 @@ int UnitTest::Run() { ...@@ -5472,20 +5400,20 @@ int UnitTest::Run() {
// process. In either case the user does not want to see pop-up dialogs // process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected. // about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) { if (impl()->catch_exceptions() || in_death_test_child_process) {
# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
// SetErrorMode doesn't exist on CE. // SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
# endif // !GTEST_OS_WINDOWS_MOBILE #endif // !GTEST_OS_WINDOWS_MOBILE
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
// Death test children can be terminated with _abort(). On Windows, // Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the // _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead. // abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR); _set_error_mode(_OUT_TO_STDERR);
# endif #endif
# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE #if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog // In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress // offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
...@@ -5505,14 +5433,15 @@ int UnitTest::Run() { ...@@ -5505,14 +5433,15 @@ int UnitTest::Run() {
_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
(void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
} }
# endif #endif
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return internal::HandleExceptionsInMethodIfSupported( return internal::HandleExceptionsInMethodIfSupported(
impl(), impl(), &internal::UnitTestImpl::RunAllTests,
&internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)")
"auxiliary test code (environments or event listeners)") ? 0 : 1; ? 0
: 1;
} }
// Returns the working directory when the first TEST() or TEST_F() was // Returns the working directory when the first TEST() or TEST_F() was
...@@ -5557,14 +5486,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { ...@@ -5557,14 +5486,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
} }
// Creates an empty UnitTest. // Creates an empty UnitTest.
UnitTest::UnitTest() { UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
impl_ = new internal::UnitTestImpl(this);
}
// Destructor of UnitTest. // Destructor of UnitTest.
UnitTest::~UnitTest() { UnitTest::~UnitTest() { delete impl_; }
delete impl_;
}
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack. // Google Test trace stack.
...@@ -5575,8 +5500,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) ...@@ -5575,8 +5500,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
} }
// Pops a trace from the per-thread Google Test trace stack. // Pops a trace from the per-thread Google Test trace stack.
void UnitTest::PopGTestTrace() void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back(); impl_->gtest_trace_stack().pop_back();
} }
...@@ -5677,8 +5601,8 @@ void UnitTestImpl::ConfigureStreamingOutput() { ...@@ -5677,8 +5601,8 @@ void UnitTestImpl::ConfigureStreamingOutput() {
if (!target.empty()) { if (!target.empty()) {
const size_t pos = target.find(':'); const size_t pos = target.find(':');
if (pos != std::string::npos) { if (pos != std::string::npos) {
listeners()->Append(new StreamingListener(target.substr(0, pos), listeners()->Append(
target.substr(pos+1))); new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
} else { } else {
GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
<< "\" ignored."; << "\" ignored.";
...@@ -5823,8 +5747,7 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5823,8 +5747,7 @@ bool UnitTestImpl::RunAllTests() {
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
// Do not run any test if the --help flag was specified. // Do not run any test if the --help flag was specified.
if (g_help_flag) if (g_help_flag) return true;
return true;
// Repeats the call to the post-flag parsing initialization in case the // Repeats the call to the post-flag parsing initialization in case the
// user didn't call InitGoogleTest. // user didn't call InitGoogleTest.
...@@ -5842,11 +5765,11 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5842,11 +5765,11 @@ bool UnitTestImpl::RunAllTests() {
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
in_subprocess_for_death_test = in_subprocess_for_death_test =
(internal_run_death_test_flag_.get() != nullptr); (internal_run_death_test_flag_.get() != nullptr);
# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
if (in_subprocess_for_death_test) { if (in_subprocess_for_death_test) {
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
} }
# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
...@@ -5854,9 +5777,9 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5854,9 +5777,9 @@ bool UnitTestImpl::RunAllTests() {
// Compares the full test names with the filter to decide which // Compares the full test names with the filter to decide which
// tests to run. // tests to run.
const bool has_tests_to_run = FilterTests(should_shard const bool has_tests_to_run =
? HONOR_SHARDING_PROTOCOL FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
: IGNORE_SHARDING_PROTOCOL) > 0; : IGNORE_SHARDING_PROTOCOL) > 0;
// Lists the tests and exits if the --gtest_list_tests flag was specified. // Lists the tests and exits if the --gtest_list_tests flag was specified.
if (GTEST_FLAG_GET(list_tests)) { if (GTEST_FLAG_GET(list_tests)) {
...@@ -6039,8 +5962,7 @@ void WriteToShardStatusFileIfNeeded() { ...@@ -6039,8 +5962,7 @@ void WriteToShardStatusFileIfNeeded() {
// an error and exits. If in_subprocess_for_death_test, sharding is // an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test // disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute. // process. Otherwise, we could filter out death tests we intended to execute.
bool ShouldShard(const char* total_shards_env, bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
const char* shard_index_env,
bool in_subprocess_for_death_test) { bool in_subprocess_for_death_test) {
if (in_subprocess_for_death_test) { if (in_subprocess_for_death_test) {
return false; return false;
...@@ -6052,27 +5974,27 @@ bool ShouldShard(const char* total_shards_env, ...@@ -6052,27 +5974,27 @@ bool ShouldShard(const char* total_shards_env,
if (total_shards == -1 && shard_index == -1) { if (total_shards == -1 && shard_index == -1) {
return false; return false;
} else if (total_shards == -1 && shard_index != -1) { } else if (total_shards == -1 && shard_index != -1) {
const Message msg = Message() const Message msg = Message() << "Invalid environment variables: you have "
<< "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index
<< kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards
<< ", but have left " << kTestTotalShards << " unset.\n"; << " unset.\n";
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) { } else if (total_shards != -1 && shard_index == -1) {
const Message msg = Message() const Message msg = Message()
<< "Invalid environment variables: you have " << "Invalid environment variables: you have "
<< kTestTotalShards << " = " << total_shards << kTestTotalShards << " = " << total_shards
<< ", but have left " << kTestShardIndex << " unset.\n"; << ", but have left " << kTestShardIndex << " unset.\n";
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) { } else if (shard_index < 0 || shard_index >= total_shards) {
const Message msg = Message() const Message msg =
<< "Invalid environment variables: we require 0 <= " Message() << "Invalid environment variables: we require 0 <= "
<< kTestShardIndex << " < " << kTestTotalShards << kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index << ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n"; << ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
...@@ -6114,10 +6036,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { ...@@ -6114,10 +6036,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
// . Returns the number of tests that should run. // . Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
Int32FromEnvOrDie(kTestTotalShards, -1) : -1; ? Int32FromEnvOrDie(kTestTotalShards, -1)
const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? : -1;
Int32FromEnvOrDie(kTestShardIndex, -1) : -1; const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
? Int32FromEnvOrDie(kTestShardIndex, -1)
: -1;
const PositiveAndNegativeUnitTestFilter gtest_flag_filter( const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
GTEST_FLAG_GET(filter)); GTEST_FLAG_GET(filter));
...@@ -6327,7 +6251,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { ...@@ -6327,7 +6251,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {
// suppress unreachable code warnings. // suppress unreachable code warnings.
namespace { namespace {
class ClassUniqueToAlwaysTrue {}; class ClassUniqueToAlwaysTrue {};
} } // namespace
bool IsTrue(bool condition) { return condition; } bool IsTrue(bool condition) { return condition; }
...@@ -6335,8 +6259,7 @@ bool AlwaysTrue() { ...@@ -6335,8 +6259,7 @@ bool AlwaysTrue() {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
// This condition is always false so AlwaysTrue() never actually throws, // This condition is always false so AlwaysTrue() never actually throws,
// but it makes the compiler think that it may throw. // but it makes the compiler think that it may throw.
if (IsTrue(false)) if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
throw ClassUniqueToAlwaysTrue();
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
return true; return true;
} }
...@@ -6448,8 +6371,7 @@ static bool ParseFlag(const char* str, const char* flag_name, String* value) { ...@@ -6448,8 +6371,7 @@ static bool ParseFlag(const char* str, const char* flag_name, String* value) {
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
// internal flags and do not trigger the help message. // internal flags and do not trigger the help message.
static bool HasGoogleTestFlagPrefix(const char* str) { static bool HasGoogleTestFlagPrefix(const char* str) {
return (SkipPrefix("--", &str) || return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
SkipPrefix("-", &str) ||
SkipPrefix("/", &str)) && SkipPrefix("/", &str)) &&
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) || (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
...@@ -6553,18 +6475,18 @@ static const char kColorEncodedHelpMessage[] = ...@@ -6553,18 +6475,18 @@ static const char kColorEncodedHelpMessage[] =
" Generate a JSON or XML report in the given directory or with the " " Generate a JSON or XML report in the given directory or with the "
"given\n" "given\n"
" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"stream_result_to=@YHOST@G:@YPORT@D\n" "stream_result_to=@YHOST@G:@YPORT@D\n"
" Stream test results to the given server.\n" " Stream test results to the given server.\n"
# endif // GTEST_CAN_STREAM_RESULTS_ #endif // GTEST_CAN_STREAM_RESULTS_
"\n" "\n"
"Assertion Behavior:\n" "Assertion Behavior:\n"
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
" Set the default death test style.\n" " Set the default death test style.\n"
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"break_on_failure@D\n" "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\n" " Turn assertion failures into debugger break-points.\n"
...@@ -6641,10 +6563,8 @@ static void LoadFlagsFromFile(const std::string& path) { ...@@ -6641,10 +6563,8 @@ static void LoadFlagsFromFile(const std::string& path) {
std::vector<std::string> lines; std::vector<std::string> lines;
SplitString(contents, '\n', &lines); SplitString(contents, '\n', &lines);
for (size_t i = 0; i < lines.size(); ++i) { for (size_t i = 0; i < lines.size(); ++i) {
if (lines[i].empty()) if (lines[i].empty()) continue;
continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
if (!ParseGoogleTestFlag(lines[i].c_str()))
g_help_flag = true;
} }
} }
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
...@@ -6762,7 +6682,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { ...@@ -6762,7 +6682,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
void InitGoogleTest(int* argc, char** argv) { void InitGoogleTest(int* argc, char** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv); internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6772,7 +6692,7 @@ void InitGoogleTest(int* argc, char** argv) { ...@@ -6772,7 +6692,7 @@ void InitGoogleTest(int* argc, char** argv) {
void InitGoogleTest(int* argc, wchar_t** argv) { void InitGoogleTest(int* argc, wchar_t** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv); internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6788,7 +6708,7 @@ void InitGoogleTest() { ...@@ -6788,7 +6708,7 @@ void InitGoogleTest() {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(&argc, argv); internal::InitGoogleTestImpl(&argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6840,8 +6760,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) { ...@@ -6840,8 +6760,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
} }
// Pops the info pushed by the c'tor. // Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace() ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace(); UnitTest::GetInstance()->PopGTestTrace();
} }
......
...@@ -28,15 +28,14 @@ ...@@ -28,15 +28,14 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio> #include <cstdio>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266 #if GTEST_OS_ESP8266
extern "C" { extern "C" {
#endif #endif
void setup() { void setup() { testing::InitGoogleTest(); }
testing::InitGoogleTest();
}
void loop() { RUN_ALL_TESTS(); } void loop() { RUN_ALL_TESTS(); }
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's break-on-failure mode. // Unit test for Google Test's break-on-failure mode.
// //
// A user can ask Google Test to seg-fault when an assertion fails, using // A user can ask Google Test to seg-fault when an assertion fails, using
...@@ -41,34 +40,32 @@ ...@@ -41,34 +40,32 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <stdlib.h>
# include <stdlib.h> #include <windows.h>
#endif #endif
namespace { namespace {
// A test that's expected to fail. // A test that's expected to fail.
TEST(Foo, Bar) { TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
EXPECT_EQ(2, 3);
}
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// On Windows Mobile global exception handlers are not supported. // On Windows Mobile global exception handlers are not supported.
LONG WINAPI ExitWithExceptionCode( LONG WINAPI
struct _EXCEPTION_POINTERS* exception_pointers) { ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
exit(exception_pointers->ExceptionRecord->ExceptionCode); exit(exception_pointers->ExceptionRecord->ExceptionCode);
} }
#endif #endif
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Suppresses display of the Windows error dialog upon encountering // Suppresses display of the Windows error dialog upon encountering
// a general protection fault (segment violation). // a general protection fault (segment violation).
SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// The default unhandled exception filter does not always exit // The default unhandled exception filter does not always exit
// with the exception code as exit code - for example it exits with // with the exception code as exit code - for example it exits with
...@@ -78,7 +75,7 @@ int main(int argc, char **argv) { ...@@ -78,7 +75,7 @@ int main(int argc, char **argv) {
// exceptions. // exceptions.
SetUnhandledExceptionFilter(ExitWithExceptionCode); SetUnhandledExceptionFilter(ExitWithExceptionCode);
# endif #endif
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment