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
...@@ -32,18 +32,18 @@ ...@@ -32,18 +32,18 @@
// exceptions, and the output is verified by // exceptions, and the output is verified by
// googletest-catch-exceptions-test.py. // googletest-catch-exceptions-test.py.
#include <stdio.h> // NOLINT #include <stdio.h> // NOLINT
#include <stdlib.h> // For exit(). #include <stdlib.h> // For exit().
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> #include <windows.h>
#endif #endif
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <exception> // For set_terminate(). #include <exception> // For set_terminate().
# include <stdexcept> #include <stdexcept>
#endif #endif
using testing::Test; using testing::Test;
...@@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test { ...@@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test {
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {} TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
TEST(SehExceptionTest, ThrowsSehException) { TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }
RaiseException(42, 0, 0, NULL);
}
#endif // GTEST_HAS_SEH #endif // GTEST_HAS_SEH
...@@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) { ...@@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
throw std::runtime_error("Standard C++ exception"); throw std::runtime_error("Standard C++ exception");
} }
TEST(CxxExceptionTest, ThrowsNonStdCxxException) { TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; }
throw "C-string";
}
// This terminate handler aborts the program using exit() rather than abort(). // This terminate handler aborts the program using exit() rather than abort().
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like // This avoids showing pop-ups on Windows systems and core dumps on Unix-like
......
...@@ -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.
// A helper program for testing how Google Test determines whether to use // A helper program for testing how Google Test determines whether to use
// colors in the output. It prints "YES" and returns 1 if Google Test // colors in the output. It prints "YES" and returns 1 if Google Test
// decides to use colors, and prints "NO" and returns 0 otherwise. // decides to use colors, and prints "NO" and returns 0 otherwise.
...@@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor; ...@@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor;
// created before main() is entered, and thus that ShouldUseColor() // created before main() is entered, and thus that ShouldUseColor()
// works the same way as in a real Google-Test-based test. We don't actual // works the same way as in a real Google-Test-based test. We don't actual
// run the TEST itself. // run the TEST itself.
TEST(GTestColorTest, Dummy) { TEST(GTestColorTest, Dummy) {}
}
int main(int argc, char** argv) { int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
......
...@@ -31,7 +31,6 @@ ...@@ -31,7 +31,6 @@
// Tests for death tests. // Tests for death tests.
#include "gtest/gtest-death-test.h" #include "gtest/gtest-death-test.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
...@@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue; ...@@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue;
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <fcntl.h> // For O_BINARY #include <direct.h> // For chdir().
# include <direct.h> // For chdir(). #include <fcntl.h> // For O_BINARY
# include <io.h> #include <io.h>
# else #else
# include <unistd.h> #include <sys/wait.h> // For waitpid.
# include <sys/wait.h> // For waitpid. #include <unistd.h>
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# include <limits.h> #include <limits.h>
# include <signal.h> #include <signal.h>
# include <stdio.h> #include <stdio.h>
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <sys/time.h> #include <sys/time.h>
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
# include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
namespace posix = ::testing::internal::posix; namespace posix = ::testing::internal::posix;
...@@ -90,6 +89,7 @@ class ReplaceDeathTestFactory { ...@@ -90,6 +89,7 @@ class ReplaceDeathTestFactory {
unit_test_impl_->death_test_factory_.release(); unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(old_factory_); unit_test_impl_->death_test_factory_.reset(old_factory_);
} }
private: private:
// Prevents copying ReplaceDeathTestFactory objects. // Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
...@@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) { ...@@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) {
// Some compilers can recognize that _exit() never returns and issue the // Some compilers can recognize that _exit() never returns and issue the
// 'unreachable code' warning for code following this function, unless // 'unreachable code' warning for code following this function, unless
// fooled by a fake condition. // fooled by a fake condition.
if (AlwaysTrue()) if (AlwaysTrue()) _exit(1);
_exit(1);
} }
void DieInside(const ::std::string& function) { void DieInside(const ::std::string& function) {
...@@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test { ...@@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test {
// A method of the test fixture that may die. // A method of the test fixture that may die.
void MemberFunction() { void MemberFunction() {
if (should_die_) if (should_die_) DieInside("MemberFunction");
DieInside("MemberFunction");
} }
// True if and only if MemberFunction() should die. // True if and only if MemberFunction() should die.
...@@ -153,8 +151,7 @@ class MayDie { ...@@ -153,8 +151,7 @@ class MayDie {
// A member function that may die. // A member function that may die.
void MemberFunction() const { void MemberFunction() const {
if (should_die_) if (should_die_) DieInside("MayDie::MemberFunction");
DieInside("MayDie::MemberFunction");
} }
private: private:
...@@ -173,8 +170,7 @@ int NonVoidFunction() { ...@@ -173,8 +170,7 @@ int NonVoidFunction() {
// A unary function that may die. // A unary function that may die.
void DieIf(bool should_die) { void DieIf(bool should_die) {
if (should_die) if (should_die) DieInside("DieIf");
DieInside("DieIf");
} }
// A binary function that may die. // A binary function that may die.
...@@ -195,16 +191,16 @@ void DeathTestSubroutine() { ...@@ -195,16 +191,16 @@ void DeathTestSubroutine() {
int DieInDebugElse12(int* sideeffect) { int DieInDebugElse12(int* sideeffect) {
if (sideeffect) *sideeffect = 12; if (sideeffect) *sideeffect = 12;
# ifndef NDEBUG #ifndef NDEBUG
DieInside("DieInDebugElse12"); DieInside("DieInDebugElse12");
# endif // NDEBUG #endif // NDEBUG
return 12; return 12;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Death in dbg due to Windows CRT assertion failure, not opt. // Death in dbg due to Windows CRT assertion failure, not opt.
int DieInCRTDebugElse12(int* sideeffect) { int DieInCRTDebugElse12(int* sideeffect) {
...@@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) { ...@@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
...@@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) { ...@@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) {
EXPECT_FALSE(testing::ExitedWithCode(1)(0)); EXPECT_FALSE(testing::ExitedWithCode(1)(0));
} }
# else #else
// Returns the exit status of a process that calls _exit(2) with a // Returns the exit status of a process that calls _exit(2) with a
// given exit code. This is a helper function for the // given exit code. This is a helper function for the
...@@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) { ...@@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) {
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
const int status0 = NormalExitStatus(0); const int status0 = NormalExitStatus(0);
const int status1 = NormalExitStatus(1); const int status1 = NormalExitStatus(1);
const int status42 = NormalExitStatus(42); const int status42 = NormalExitStatus(42);
const testing::ExitedWithCode pred0(0); const testing::ExitedWithCode pred0(0);
const testing::ExitedWithCode pred1(1); const testing::ExitedWithCode pred1(1);
const testing::ExitedWithCode pred42(42); const testing::ExitedWithCode pred42(42);
EXPECT_PRED1(pred0, status0); EXPECT_PRED1(pred0, status0);
EXPECT_PRED1(pred1, status1); EXPECT_PRED1(pred1, status1);
EXPECT_PRED1(pred42, status42); EXPECT_PRED1(pred42, status42);
EXPECT_FALSE(pred0(status1)); EXPECT_FALSE(pred0(status1));
EXPECT_FALSE(pred42(status0)); EXPECT_FALSE(pred42(status0));
...@@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { ...@@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
EXPECT_FALSE(pred_kill(status_segv)); EXPECT_FALSE(pred_kill(status_segv));
} }
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// The following code intentionally tests a suboptimal syntax. // The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__ #ifdef __GNUC__
...@@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) { ...@@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; ;
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; ;
...@@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) { ...@@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
# if GTEST_USES_PCRE #if GTEST_USES_PCRE
void DieWithEmbeddedNul() { void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cmy null world.\n", '\0'); fprintf(stderr, "Hello%cmy null world.\n", '\0');
...@@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) { ...@@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
} }
# endif // GTEST_USES_PCRE #endif // GTEST_USES_PCRE
// Tests that death test macros expand to code which interacts well with switch // Tests that death test macros expand to code which interacts well with switch
// statements. // statements.
...@@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) { ...@@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH(_exit(1), "") << "exit in switch case"; EXPECT_DEATH(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
...@@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { ...@@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
ASSERT_DEATH(_exit(1), ""); ASSERT_DEATH(_exit(1), "");
} }
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */ } void SigprofAction(int, siginfo_t*, void*) { /* no op */
}
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() { void SetSigprofActionAndTimer() {
...@@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { ...@@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
DisableSigprofActionAndTimer(&old_signal_action); DisableSigprofActionAndTimer(&old_signal_action);
EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
} }
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
// Repeats a representative sample of death tests in the "threadsafe" style: // Repeats a representative sample of death tests in the "threadsafe" style:
...@@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) { ...@@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) {
EXPECT_DEATH(_exit(1), ""); EXPECT_DEATH(_exit(1), "");
} }
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
bool pthread_flag; bool pthread_flag;
void SetPthreadFlag() { void SetPthreadFlag() { pthread_flag = true; }
pthread_flag = true;
}
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!GTEST_FLAG_GET(death_test_use_fork)) { if (!GTEST_FLAG_GET(death_test_use_fork)) {
...@@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { ...@@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
} }
} }
# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD #endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
// Tests that a method of another class can be used in a death test. // Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) { TEST_F(TestForDeathTest, MethodOfAnotherClass) {
...@@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const testing::internal::RE regex(regex_c_str); const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex); EXPECT_DEATH(GlobalFunction(), regex);
# if !GTEST_USES_PCRE #if !GTEST_USES_PCRE
const ::std::string regex_std_str(regex_c_str); const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str); EXPECT_DEATH(GlobalFunction(), regex_std_str);
...@@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
// lifetime extension of the pointer is not sufficient. // lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
# endif // !GTEST_USES_PCRE #endif // !GTEST_USES_PCRE
} }
// Tests that a non-void function can be used in a death test. // Tests that a non-void function can be used in a death test.
...@@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) { ...@@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) {
} }
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) { TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
DeathTestSubroutine();
}
// Tests that death tests can be done inside a loop. // Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) { TEST_F(TestForDeathTest, InsideLoop) {
...@@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) { ...@@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) {
// Tests that a compound statement can be used in a death test. // Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) { TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT EXPECT_DEATH(
const int x = 2; { // NOLINT
const int y = x + 1; const int x = 2;
DieIfLessThan(x, y); const int y = x + 1;
}, DieIfLessThan(x, y);
"DieIfLessThan"); },
"DieIfLessThan");
} }
// Tests that code that doesn't die causes a death test to fail. // Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) { TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
"failed to die");
} }
// Tests that a death test fails when the error message isn't expected. // Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) { TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; { // NOLINT
}, "died but not with expected error"); EXPECT_DEATH(DieIf(true), "DieIfLessThan")
<< "End of death test message.";
},
"died but not with expected error");
} }
// On exit, *aborted will be true if and only if the EXPECT_DEATH() // On exit, *aborted will be true if and only if the EXPECT_DEATH()
...@@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) { ...@@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) {
// Tests that EXPECT_DEATH doesn't abort the test on failure. // Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) { TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true; bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
"failed to die");
EXPECT_FALSE(aborted); EXPECT_FALSE(aborted);
} }
// Tests that ASSERT_DEATH does abort the test on failure. // Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) { TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted; static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
aborted = true; { // NOLINT
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. aborted = true;
aborted = false; ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
}, "failed to die"); aborted = false;
},
"failed to die");
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
...@@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) { ...@@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) {
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect); EXPECT_EQ(0, sideeffect);
# endif #endif
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
...@@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) { ...@@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) {
} }
#endif // _DEBUG #endif // _DEBUG
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it: // message to it, and in debug mode it:
...@@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) { ...@@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) {
ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect); EXPECT_EQ(0, sideeffect);
# endif #endif
} }
# ifndef NDEBUG #ifndef NDEBUG
void ExpectDebugDeathHelper(bool* aborted) { void ExpectDebugDeathHelper(bool* aborted) {
*aborted = true; *aborted = true;
...@@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) { ...@@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) {
*aborted = false; *aborted = false;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf("This test should be considered failing if it shows " printf(
"any pop-up dialogs.\n"); "This test should be considered failing if it shows "
"any pop-up dialogs.\n");
fflush(stdout); fflush(stdout);
EXPECT_DEATH( EXPECT_DEATH(
...@@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { ...@@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
}, },
""); "");
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function. // the function.
...@@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { ...@@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
# endif // _NDEBUG #endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates. // Tests the *_EXIT family of macros, using a variety of predicates.
static void TestExitMacros() { static void TestExitMacros() {
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Of all signals effects on the process exit code, only those of SIGABRT // Of all signals effects on the process exit code, only those of SIGABRT
// are documented on Windows. // are documented on Windows.
// See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
# elif !GTEST_OS_FUCHSIA #elif !GTEST_OS_FUCHSIA
// Fuchsia has no unix signals. // Fuchsia has no unix signals.
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") { // NOLINT
<< "This failure is expected, too."; ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
}, "This failure is expected, too."); << "This failure is expected, too.";
},
"This failure is expected, too.");
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") { // NOLINT
<< "This failure is expected."; EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
}, "This failure is expected."); << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, ExitMacros) { TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
TestExitMacros();
}
TEST_F(TestForDeathTest, ExitMacrosUsingFork) { TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
GTEST_FLAG_SET(death_test_use_fork, true); GTEST_FLAG_SET(death_test_use_fork, true);
...@@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) { ...@@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
TEST_F(TestForDeathTest, InvalidStyle) { TEST_F(TestForDeathTest, InvalidStyle) {
GTEST_FLAG_SET(death_test_style, "rococo"); GTEST_FLAG_SET(death_test_style, "rococo");
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "This failure is expected."; { // NOLINT
}, "This failure is expected."); EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, DeathTestFailedOutput) { TEST_F(TestForDeathTest, DeathTestFailedOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("death\n"), EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
"expected message"),
"Actual msg:\n" "Actual msg:\n"
"[ DEATH ] death\n"); "[ DEATH ] death\n");
} }
TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
EXPECT_DEATH({ {
fprintf(stderr, "returning\n"); fprintf(stderr, "returning\n");
fflush(stderr); fflush(stderr);
return; return;
}, ""), },
" Result: illegal return in test statement.\n" ""),
" Error msg:\n" " Result: illegal return in test statement.\n"
"[ DEATH ] returning\n"); " Error msg:\n"
"[ DEATH ] returning\n");
} }
TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
testing::ExitedWithCode(3), testing::ExitedWithCode(3), "expected message"),
"expected message"),
" Result: died but not with expected exit code:\n" " Result: died but not with expected exit code:\n"
" Exited with exit status 1\n" " Exited with exit status 1\n"
"Actual msg:\n" "Actual msg:\n"
...@@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory { ...@@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory {
int line, DeathTest** test) override; int line, DeathTest** test) override;
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role, void SetParameters(bool create, DeathTest::TestRole role, int status,
int status, bool passed); bool passed);
// Accessors. // Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; } int AssumeRoleCalls() const { return assume_role_calls_; }
...@@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory { ...@@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory {
bool test_deleted_; bool test_deleted_;
}; };
// A DeathTest implementation useful in testing. It returns values set // A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and // at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory // reports calls to those methods to its parent MockDeathTestFactory
// object. // object.
class MockDeathTest : public DeathTest { class MockDeathTest : public DeathTest {
public: public:
MockDeathTest(MockDeathTestFactory *parent, MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
TestRole role, int status, bool passed) : bool passed)
parent_(parent), role_(role), status_(status), passed_(passed) { : parent_(parent), role_(role), status_(status), passed_(passed) {}
}
~MockDeathTest() override { parent_->test_deleted_ = true; } ~MockDeathTest() override { parent_->test_deleted_ = true; }
TestRole AssumeRole() override { TestRole AssumeRole() override {
++parent_->assume_role_calls_; ++parent_->assume_role_calls_;
...@@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest { ...@@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest {
const bool passed_; const bool passed_;
}; };
// MockDeathTestFactory constructor. // MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory() MockDeathTestFactory::MockDeathTestFactory()
: create_(true), : create_(true),
...@@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory() ...@@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory()
assume_role_calls_(0), assume_role_calls_(0),
wait_calls_(0), wait_calls_(0),
passed_args_(), passed_args_(),
abort_args_() { abort_args_() {}
}
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create, void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
DeathTest::TestRole role,
int status, bool passed) { int status, bool passed) {
create_ = create; create_ = create;
role_ = role; role_ = role;
...@@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create, ...@@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create,
abort_args_.clear(); abort_args_.clear();
} }
// Sets test to NULL (if create_ is false) or to the address of a new // Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call // MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true. // to SetParameters (if create_ is true). Always returns true.
...@@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test { ...@@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test {
// test cannot be run directly from a test routine that uses a // test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed. // MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) { static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT ASSERT_DEATH(
*flag = true; { // NOLINT
return; *flag = true;
}, ""); return;
},
"");
} }
}; };
...@@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { ...@@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
// _exit(2) is called in that case by ForkingDeathTest, but not by // _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest. // our MockDeathTest.
ASSERT_EQ(2U, factory_->AbortCalls()); ASSERT_EQ(2U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1)); factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted()); EXPECT_TRUE(factory_->TestDeleted());
...@@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) { ...@@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
TEST(StreamingAssertionsDeathTest, DeathTest) { TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(_exit(1), "") << "unexpected failure"; EXPECT_DEATH(_exit(1), "") << "unexpected failure";
ASSERT_DEATH(_exit(1), "") << "unexpected failure"; ASSERT_DEATH(_exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "expected failure"; { // NOLINT
}, "expected failure"); EXPECT_DEATH(_exit(0), "") << "expected failure";
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_DEATH(_exit(0), "") << "expected failure"; "expected failure");
}, "expected failure"); EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_DEATH(_exit(0), "") << "expected failure";
},
"expected failure");
} }
// Tests that GetLastErrnoDescription returns an empty string when the // Tests that GetLastErrnoDescription returns an empty string when the
...@@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { ...@@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
EXPECT_STREQ("", GetLastErrnoDescription().c_str()); EXPECT_STREQ("", GetLastErrnoDescription().c_str());
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) { TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle); ASSERT_NE(INVALID_HANDLE_VALUE, handle);
...@@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) { ...@@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) {
testing::internal::AutoHandle auto_handle2; testing::internal::AutoHandle auto_handle2;
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
typedef unsigned __int64 BiggestParsable; typedef unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable; typedef signed __int64 BiggestSignedParsable;
# else #else
typedef unsigned long long BiggestParsable; typedef unsigned long long BiggestParsable;
typedef signed long long BiggestSignedParsable; typedef signed long long BiggestSignedParsable;
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// We cannot use std::numeric_limits<T>::max() as it clashes with the // We cannot use std::numeric_limits<T>::max() as it clashes with the
// max() macro defined by <windows.h>. // max() macro defined by <windows.h>.
...@@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { ...@@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
EXPECT_EQ(123, char_result); EXPECT_EQ(123, char_result);
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(EnvironmentTest, HandleFitsIntoSizeT) { TEST(EnvironmentTest, HandleFitsIntoSizeT) {
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
// failures when death tests are available on the system. // failures when death tests are available on the system.
...@@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { ...@@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
GTEST_FLAG_SET(death_test_style, "threadsafe"); GTEST_FLAG_SET(death_test_style, "threadsafe");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
void DieWithMessage(const char* message) { void DieWithMessage(const char* message) {
...@@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { ...@@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; // NOLINT ; // NOLINT
...@@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { ...@@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
<< "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
// Tests that a test case whose name ends with "DeathTest" works fine // Tests that a test case whose name ends with "DeathTest" works fine
// on Windows. // on Windows.
TEST(NotADeathTest, Test) { TEST(NotADeathTest, Test) { SUCCEED(); }
SUCCEED();
}
} // namespace } // namespace
...@@ -35,15 +35,15 @@ ...@@ -35,15 +35,15 @@
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> // For RaiseException(). #include <windows.h> // For RaiseException().
# endif #endif
# include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
# if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <exception> // For std::exception. #include <exception> // For std::exception.
// Tests that death tests report thrown exceptions as failures and that the // Tests that death tests report thrown exceptions as failures and that the
// exceptions do not escape death test macros. // exceptions do not escape death test macros.
...@@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { ...@@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
"exceptional message"); "exceptional message");
// Verifies that the location is mentioned in the failure text. // Verifies that the location is mentioned in the failure text.
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__);
__FILE__);
} }
# endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
# if GTEST_HAS_SEH #if GTEST_HAS_SEH
// Tests that enabling interception of SEH exceptions with the // Tests that enabling interception of SEH exceptions with the
// catch_exceptions flag does not interfere with SEH exceptions being // catch_exceptions flag does not interfere with SEH exceptions being
// treated as death by death tests. // treated as death by death tests.
...@@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { ...@@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
<< "with catch_exceptions " << "with catch_exceptions "
<< (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled");
} }
# endif #endif
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
......
...@@ -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.
// A helper program for testing that Google Test parses the environment // A helper program for testing that Google Test parses the environment
// variables correctly. // variables correctly.
...@@ -43,8 +42,7 @@ namespace testing { ...@@ -43,8 +42,7 @@ namespace testing {
// The purpose of this is to make the test more realistic by ensuring // The purpose of this is to make the test more realistic by ensuring
// that the UnitTest singleton is created before main() is entered. // that the UnitTest singleton is created before main() is entered.
// We don't actual run the TEST itself. // We don't actual run the TEST itself.
TEST(GTestEnvVarTest, Dummy) { TEST(GTestEnvVarTest, Dummy) {}
}
void PrintFlag(const char* flag) { void PrintFlag(const char* flag) {
if (strcmp(flag, "break_on_failure") == 0) { if (strcmp(flag, "break_on_failure") == 0) {
......
...@@ -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 test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // A user can specify which test(s) in a Google Test program to run via
...@@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; } ...@@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener()); ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
......
...@@ -35,15 +35,15 @@ ...@@ -35,15 +35,15 @@
// This file is #included from gtest-internal.h. // This file is #included from gtest-internal.h.
// Do not #include this file anywhere else! // Do not #include this file anywhere else!
#include "gtest/internal/gtest-filepath.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> // NOLINT #include <direct.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
namespace testing { namespace testing {
namespace internal { namespace internal {
...@@ -55,16 +55,16 @@ namespace { ...@@ -55,16 +55,16 @@ namespace {
int remove(const char* path) { int remove(const char* path) {
LPCWSTR wpath = String::AnsiToUtf16(path); LPCWSTR wpath = String::AnsiToUtf16(path);
int ret = DeleteFile(wpath) ? 0 : -1; int ret = DeleteFile(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
// Windows CE doesn't have the _rmdir C function. // Windows CE doesn't have the _rmdir C function.
int _rmdir(const char* path) { int _rmdir(const char* path) {
FilePath filepath(path); FilePath filepath(path);
LPCWSTR wpath = String::AnsiToUtf16( LPCWSTR wpath =
filepath.RemoveTrailingPathSeparator().c_str()); String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());
int ret = RemoveDirectory(wpath) ? 0 : -1; int ret = RemoveDirectory(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
...@@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { ...@@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir(); const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str()); posix::ChDir(original_dir.c_str());
# if GTEST_OS_WINDOWS || GTEST_OS_OS2 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
// Skips the ":". // Skips the ":".
const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
ASSERT_TRUE(cwd_without_drive != NULL); ASSERT_TRUE(cwd_without_drive != NULL);
EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
# else #else
EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
# endif #endif
} }
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
...@@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) { ...@@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) {
// RemoveDirectoryName "afile" -> "afile" // RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) { TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_EQ("afile", EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string());
FilePath("afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "/afile" -> "afile" // RemoveDirectoryName "/afile" -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/" -> "" // RemoveDirectoryName "adir/" -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
EXPECT_EQ("", EXPECT_EQ("",
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/afile" -> "afile" // RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ(
"afile",
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/subdir/afile" -> "afile" // RemoveDirectoryName "adir/subdir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveDirectoryName().string()); .RemoveDirectoryName()
.string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) { ...@@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) {
// RemoveFileName "adir/" -> "adir/" // RemoveFileName "adir/" -> "adir/"
TEST(RemoveFileNameTest, ButNoFile) { TEST(RemoveFileNameTest, ButNoFile) {
EXPECT_EQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
} }
// RemoveFileName "adir/afile" -> "adir/" // RemoveFileName "adir/afile" -> "adir/"
...@@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) { ...@@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) {
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" // RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirName) { TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveFileName().string()); .RemoveFileName()
.string());
} }
// RemoveFileName "/afile" -> "/" // RemoveFileName "/afile" -> "/"
TEST(RemoveFileNameTest, GivesRootDir) { TEST(RemoveFileNameTest, GivesRootDir) {
EXPECT_EQ(GTEST_PATH_SEP_, EXPECT_EQ(GTEST_PATH_SEP_,
FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { ...@@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
#endif #endif
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
12, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 0, "xml"); FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 12, "xml"); FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml");
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
14, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml");
EXPECT_EQ("bar_14.xml", actual.string()); EXPECT_EQ("bar_14.xml", actual.string());
} }
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
...@@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { ...@@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
} }
TEST(ConcatPathsTest, Path1BeingEmpty) { TEST(ConcatPathsTest, Path1BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
...@@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) { ...@@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) {
} }
TEST(ConcatPathsTest, BothPathBeingEmpty) { TEST(ConcatPathsTest, BothPathBeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath(""));
FilePath(""));
EXPECT_EQ("", actual.string()); EXPECT_EQ("", actual.string());
} }
...@@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) { ...@@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) {
} }
TEST(ConcatPathsTest, Path2ContainsPathSep) { TEST(ConcatPathsTest, Path2ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths( FilePath actual =
FilePath("foo" GTEST_PATH_SEP_), FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
actual.string()); actual.string());
} }
TEST(ConcatPathsTest, Path2EndsWithPathSep) { TEST(ConcatPathsTest, Path2EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual =
FilePath("bar" GTEST_PATH_SEP_)); FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
} }
...@@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { ...@@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
// RemoveTrailingPathSeparator "foo/" -> "foo" // RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_EQ("foo", EXPECT_EQ(
"foo",
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
...@@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { ...@@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
.RemoveTrailingPathSeparator().string()); .RemoveTrailingPathSeparator()
.string());
} }
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar")
FilePath("foo" GTEST_PATH_SEP_ "bar") .RemoveTrailingPathSeparator()
.RemoveTrailingPathSeparator().string()); .string());
} }
TEST(DirectoryTest, RootDirectoryExists) { TEST(DirectoryTest, RootDirectoryExists) {
#if GTEST_OS_WINDOWS // We are on Windows. #if GTEST_OS_WINDOWS // We are on Windows.
char current_drive[_MAX_PATH]; // NOLINT char current_drive[_MAX_PATH]; // NOLINT
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1); current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
current_drive[1] = ':'; current_drive[1] = ':';
...@@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { ...@@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
TEST(DirectoryTest, CurrentDirectoryExists) { TEST(DirectoryTest, CurrentDirectoryExists) {
#if GTEST_OS_WINDOWS // We are on Windows. #if GTEST_OS_WINDOWS // We are on Windows.
# ifndef _WIN32_CE // Windows CE doesn't have a current directory. #ifndef _WIN32_CE // Windows CE doesn't have a current directory.
EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".").DirectoryExists());
EXPECT_TRUE(FilePath(".\\").DirectoryExists()); EXPECT_TRUE(FilePath(".\\").DirectoryExists());
# endif // _WIN32_CE #endif // _WIN32_CE
#else #else
EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".").DirectoryExists());
EXPECT_TRUE(FilePath("./").DirectoryExists()); EXPECT_TRUE(FilePath("./").DirectoryExists());
...@@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { ...@@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
FilePath("foo" GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "foo" GTEST_PATH_SEP_ "bar",
GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar")
.string());
} }
// "/bar" == //bar" == "///bar" // "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ "bar").string()); FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); GTEST_PATH_SEP_ "bar",
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
} }
// "foo/" == foo//" == "foo///" // "foo/" == foo//" == "foo///"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_).string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); "foo" GTEST_PATH_SEP_,
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { ...@@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
// regardless of their combination (e.g. "foo\" =="foo/\" == // regardless of their combination (e.g. "foo\" =="foo/\" ==
// "foo\\/"). // "foo\\/").
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string());
FilePath("foo/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ "/").string()); FilePath("foo" GTEST_PATH_SEP_ "/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string());
FilePath("foo//" GTEST_PATH_SEP_).string());
} }
#endif #endif
...@@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { ...@@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
class DirectoryCreationTest : public Test { class DirectoryCreationTest : public Test {
protected: protected:
void SetUp() override { void SetUp() override {
testdata_path_.Set(FilePath( testdata_path_.Set(
TempDir() + GetCurrentExecutableName().string() + FilePath(TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file0_.Set(
0, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt"));
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file1_.Set(
1, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt"));
remove(testdata_file_.c_str()); remove(testdata_file_.c_str());
remove(unique_file0_.c_str()); remove(unique_file0_.c_str());
...@@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test { ...@@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test {
// a directory named 'test' from a file named 'test'. Example names: // a directory named 'test' from a file named 'test'. Example names:
FilePath testdata_path_; // "/tmp/directory_creation/test/" FilePath testdata_path_; // "/tmp/directory_creation/test/"
FilePath testdata_file_; // "/tmp/directory_creation/test" FilePath testdata_file_; // "/tmp/directory_creation/test"
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
}; };
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
...@@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { ...@@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
} }
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file0_.string(), file_path.string()); EXPECT_EQ(unique_file0_.string(), file_path.string());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
...@@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { ...@@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
CreateTextFile(file_path.c_str()); CreateTextFile(file_path.c_str());
EXPECT_TRUE(file_path.FileOrDirectoryExists()); EXPECT_TRUE(file_path.FileOrDirectoryExists());
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path2(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file1_.string(), file_path2.string()); EXPECT_EQ(unique_file1_.string(), file_path2.string());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str()); CreateTextFile(file_path2.c_str());
...@@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) { ...@@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) {
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_FALSE(FilePath("").IsAbsolutePath()); EXPECT_FALSE(FilePath("").IsAbsolutePath());
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
#else #else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath()); .IsAbsolutePath());
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} }
......
...@@ -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 test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // A user can specify which test(s) in a Google Test program to run via
...@@ -43,87 +42,57 @@ namespace { ...@@ -43,87 +42,57 @@ namespace {
// Test case FooTest. // Test case FooTest.
class FooTest : public testing::Test { class FooTest : public testing::Test {};
};
TEST_F(FooTest, Abc) { TEST_F(FooTest, Abc) {}
}
TEST_F(FooTest, Xyz) { TEST_F(FooTest, Xyz) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BarTest. // Test case BarTest.
TEST(BarTest, TestOne) { TEST(BarTest, TestOne) {}
}
TEST(BarTest, TestTwo) { TEST(BarTest, TestTwo) {}
}
TEST(BarTest, TestThree) { TEST(BarTest, TestThree) {}
}
TEST(BarTest, DISABLED_TestFour) { TEST(BarTest, DISABLED_TestFour) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BarTest, DISABLED_TestFive) { TEST(BarTest, DISABLED_TestFive) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BazTest. // Test case BazTest.
TEST(BazTest, TestOne) { TEST(BazTest, TestOne) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BazTest, TestA) { TEST(BazTest, TestA) {}
}
TEST(BazTest, TestB) { TEST(BazTest, TestB) {}
}
TEST(BazTest, DISABLED_TestC) { TEST(BazTest, DISABLED_TestC) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case HasDeathTest // Test case HasDeathTest
TEST(HasDeathTest, Test1) { TEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// We need at least two death tests to make sure that the all death tests // We need at least two death tests to make sure that the all death tests
// aren't on the first shard. // aren't on the first shard.
TEST(HasDeathTest, Test2) { TEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// Test case FoobarTest // Test case FoobarTest
TEST(DISABLED_FoobarTest, Test1) { TEST(DISABLED_FoobarTest, Test1) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(DISABLED_FoobarTest, DISABLED_Test2) { TEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case FoobarbazTest // Test case FoobarbazTest
TEST(DISABLED_FoobarbazTest, TestA) { TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
class ParamTest : public testing::TestWithParam<int> { class ParamTest : public testing::TestWithParam<int> {};
};
TEST_P(ParamTest, TestX) { TEST_P(ParamTest, TestX) {}
}
TEST_P(ParamTest, TestY) { TEST_P(ParamTest, TestY) {}
}
INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2)); INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2));
INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6)); INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6));
......
...@@ -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 --gtest_list_tests flag. // Unit test for Google Test's --gtest_list_tests flag.
// //
// A user can ask Google Test to list all tests that will run // A user can ask Google Test to list all tests that will run
...@@ -40,38 +39,27 @@ ...@@ -40,38 +39,27 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Several different test cases and tests that will be listed. // Several different test cases and tests that will be listed.
TEST(Foo, Bar1) { TEST(Foo, Bar1) {}
}
TEST(Foo, Bar2) { TEST(Foo, Bar2) {}
}
TEST(Foo, DISABLED_Bar3) { TEST(Foo, DISABLED_Bar3) {}
}
TEST(Abc, Xyz) { TEST(Abc, Xyz) {}
}
TEST(Abc, Def) { TEST(Abc, Def) {}
}
TEST(FooBar, Baz) { TEST(FooBar, Baz) {}
}
class FooTest : public testing::Test { class FooTest : public testing::Test {};
};
TEST_F(FooTest, Test1) { TEST_F(FooTest, Test1) {}
}
TEST_F(FooTest, DISABLED_Test2) { TEST_F(FooTest, DISABLED_Test2) {}
}
TEST_F(FooTest, Test3) { TEST_F(FooTest, Test3) {}
}
TEST(FooDeathTest, Test1) { TEST(FooDeathTest, Test1) {}
}
// A group of value-parameterized tests. // A group of value-parameterized tests.
...@@ -86,70 +74,66 @@ class MyType { ...@@ -86,70 +74,66 @@ class MyType {
}; };
// Teaches Google Test how to print a MyType. // Teaches Google Test how to print a MyType.
void PrintTo(const MyType& x, std::ostream* os) { void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }
*os << x.value();
}
class ValueParamTest : public testing::TestWithParam<MyType> { class ValueParamTest : public testing::TestWithParam<MyType> {};
};
TEST_P(ValueParamTest, TestA) { TEST_P(ValueParamTest, TestA) {}
}
TEST_P(ValueParamTest, TestB) { TEST_P(ValueParamTest, TestB) {}
}
INSTANTIATE_TEST_SUITE_P( INSTANTIATE_TEST_SUITE_P(
MyInstantiation, ValueParamTest, MyInstantiation, ValueParamTest,
testing::Values(MyType("one line"), testing::Values(
MyType("two\nlines"), MyType("one line"), MyType("two\nlines"),
MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT MyType("a "
"very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooong line"))); // NOLINT
// A group of typed tests. // A group of typed tests.
// A deliberately long type name for testing the line-truncating // A deliberately long type name for testing the line-truncating
// behavior when printing a type parameter. // behavior when printing a type parameter.
class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT class
VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT
}; };
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
template <typename T, int kSize> template <typename T, int kSize>
class MyArray { class MyArray {};
};
typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT typedef testing::Types<
int*, MyArray<bool, 42> > MyTypes; VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT
int*, MyArray<bool, 42> >
MyTypes;
TYPED_TEST_SUITE(TypedTest, MyTypes); TYPED_TEST_SUITE(TypedTest, MyTypes);
TYPED_TEST(TypedTest, TestA) { TYPED_TEST(TypedTest, TestA) {}
}
TYPED_TEST(TypedTest, TestB) { TYPED_TEST(TypedTest, TestB) {}
}
// A group of type-parameterized tests. // A group of type-parameterized tests.
template <typename T> template <typename T>
class TypeParamTest : public testing::Test { class TypeParamTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypeParamTest); TYPED_TEST_SUITE_P(TypeParamTest);
TYPED_TEST_P(TypeParamTest, TestA) { TYPED_TEST_P(TypeParamTest, TestA) {}
}
TYPED_TEST_P(TypeParamTest, TestB) { TYPED_TEST_P(TypeParamTest, TestB) {}
}
REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB); REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes);
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
......
...@@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment; ...@@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment;
using ::testing::Environment; using ::testing::Environment;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestSuite;
using ::testing::TestEventListener; using ::testing::TestEventListener;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest; using ::testing::UnitTest;
// Used by tests to register their events. // Used by tests to register their events.
...@@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener { ...@@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationStart(const UnitTest& /*unit_test*/, void OnTestIterationStart(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationStart") message << GetFullMethodName("OnTestIterationStart") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
...@@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener { ...@@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationEnd(const UnitTest& /*unit_test*/, void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationEnd") message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
...@@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener { ...@@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener {
} }
private: private:
std::string GetFullMethodName(const char* name) { std::string GetFullMethodName(const char* name) { return name_ + "." + name; }
return name_ + "." + name;
}
std::string name_; std::string name_;
}; };
...@@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data, ...@@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data,
EXPECT_EQ(expected_data_size, actual_size); EXPECT_EQ(expected_data_size, actual_size);
// Compares the common prefix. // Compares the common prefix.
const size_t shorter_size = expected_data_size <= actual_size ? const size_t shorter_size =
expected_data_size : actual_size; expected_data_size <= actual_size ? expected_data_size : actual_size;
size_t i = 0; size_t i = 0;
for (; i < shorter_size; ++i) { for (; i < shorter_size; ++i) {
ASSERT_STREQ(expected_data[i], data[i].c_str()) ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i;
<< "at position " << i;
} }
// Prints extra elements in the actual data. // Prints extra elements in the actual data.
for (; i < actual_size; ++i) { for (; i < actual_size; ++i) {
printf(" Actual event #%lu: %s\n", printf(" Actual event #%lu: %s\n", static_cast<unsigned long>(i),
static_cast<unsigned long>(i), data[i].c_str()); data[i].c_str());
} }
} }
int main(int argc, char **argv) { int main(int argc, char** argv) {
std::vector<std::string> events; std::vector<std::string> events;
g_events = &events; g_events = &events;
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
...@@ -506,14 +503,12 @@ int main(int argc, char **argv) { ...@@ -506,14 +503,12 @@ int main(int argc, char **argv) {
"1st.OnTestProgramEnd"}; "1st.OnTestProgramEnd"};
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
VerifyResults(events, VerifyResults(events, expected_events,
expected_events, sizeof(expected_events) / sizeof(expected_events[0]));
sizeof(expected_events)/sizeof(expected_events[0]));
// We need to check manually for ad hoc test failures that happen after // We need to check manually for ad hoc test failures that happen after
// RUN_ALL_TESTS finishes. // RUN_ALL_TESTS finishes.
if (UnitTest::GetInstance()->Failed()) if (UnitTest::GetInstance()->Failed()) ret_val = 1;
ret_val = 1;
return ret_val; return ret_val;
} }
...@@ -31,7 +31,6 @@ ...@@ -31,7 +31,6 @@
// Tests for the Message class. // Tests for the Message class.
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
...@@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) { ...@@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) {
// Tests streaming a double. // Tests streaming a double.
TEST(MessageTest, StreamsDouble) { TEST(MessageTest, StreamsDouble) {
const std::string s = (Message() << 1260570880.4555497 << " " const std::string s =
<< 1260572265.1954534).GetString(); (Message() << 1260570880.4555497 << " " << 1260572265.1954534)
.GetString();
// Both numbers should be printed with enough precision. // Both numbers should be printed with enough precision.
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
...@@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) { ...@@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) {
// Tests that we can output strings containing embedded NULs. // Tests that we can output strings containing embedded NULs.
TEST(MessageTest, StreamsStringWithEmbeddedNUL) { TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
const char char_array_with_nul[] = const char char_array_with_nul[] = "Here's a NUL\0 and some more string";
"Here's a NUL\0 and some more string";
const ::std::string string_with_nul(char_array_with_nul, const ::std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul) - 1); sizeof(char_array_with_nul) - 1);
EXPECT_EQ("Here's a NUL\\0 and some more string", EXPECT_EQ("Here's a NUL\\0 and some more string",
...@@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) { ...@@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) {
// Tests that basic IO manipulators (endl, ends, and flush) can be // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message. // streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) { TEST(MessageTest, StreamsBasicIoManip) {
EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", EXPECT_EQ(
(Message() << "Line 1." << std::endl "Line 1.\nA NUL char \\0 in line 2.",
<< "A NUL char " << std::ends << std::flush (Message() << "Line 1." << std::endl
<< " in line 2.").GetString()); << "A NUL char " << std::ends << std::flush << " in line 2.")
.GetString());
} }
// Tests Message::GetString() // Tests Message::GetString()
......
...@@ -39,9 +39,9 @@ ...@@ -39,9 +39,9 @@
#include "gtest/gtest.h" #include "gtest/gtest.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>
#elif GTEST_OS_OS2 #elif GTEST_OS_OS2
// For strcasecmp on OS/2 // For strcasecmp on OS/2
#include <strings.h> #include <strings.h>
...@@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) { ...@@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) {
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_);
const std::string expected_output_file = const std::string expected_output_file =
GetAbsolutePathOf( GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ +
FilePath(std::string("path") + GTEST_PATH_SEP_ + GetCurrentExecutableName().string() + ".xml"))
GetCurrentExecutableName().string() + ".xml")).string(); .string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
...@@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { ...@@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const bool success = exe_str == "app"; const bool success = exe_str == "app";
#else #else
const bool success = const bool success =
exe_str == "googletest-options-test" || exe_str == "googletest-options-test" || exe_str == "gtest_all_test" ||
exe_str == "gtest_all_test" || exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test";
exe_str == "lt-gtest_all_test" ||
exe_str == "gtest_dll_test";
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
if (!success) if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str;
FAIL() << "GetCurrentExecutableName() returns " << exe_str;
} }
#if !GTEST_OS_FUCHSIA #if !GTEST_OS_FUCHSIA
...@@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test { ...@@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test {
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
GTEST_FLAG_SET(output, ""); GTEST_FLAG_SET(output, "");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
GTEST_FLAG_SET(output, "xml"); GTEST_FLAG_SET(output, "xml");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
GTEST_FLAG_SET(output, "xml:filename.abc"); GTEST_FLAG_SET(output, "xml:filename.abc");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("filename.abc")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
...@@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { ...@@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
FilePath::ConcatPaths( FilePath::ConcatPaths(
original_working_dir_, original_working_dir_,
FilePath(std::string("path") + GTEST_PATH_SEP_ + FilePath(std::string("path") + GTEST_PATH_SEP_ +
GetCurrentExecutableName().string() + ".xml")).string(); GetCurrentExecutableName().string() + ".xml"))
.string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
......
...@@ -33,12 +33,12 @@ ...@@ -33,12 +33,12 @@
// desired messages. Therefore, most tests in this file are MEANT TO // desired messages. Therefore, most tests in this file are MEANT TO
// FAIL. // FAIL.
#include <stdlib.h>
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#include <stdlib.h>
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
#endif // _MSC_VER #endif // _MSC_VER
...@@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix; ...@@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix;
// Tests catching fatal failures. // Tests catching fatal failures.
// A subroutine used by the following test. // A subroutine used by the following test.
void TestEq1(int x) { void TestEq1(int x) { ASSERT_EQ(1, x); }
ASSERT_EQ(1, x);
}
// This function calls a test subroutine, catches the fatal failure it // This function calls a test subroutine, catches the fatal failure it
// generates, and then returns early. // generates, and then returns early.
...@@ -76,24 +74,19 @@ void TryTestSubroutine() { ...@@ -76,24 +74,19 @@ void TryTestSubroutine() {
FAIL() << "This should never be reached."; FAIL() << "This should never be reached.";
} }
TEST(PassingTest, PassingTest1) { TEST(PassingTest, PassingTest1) {}
}
TEST(PassingTest, PassingTest2) { TEST(PassingTest, PassingTest2) {}
}
// Tests that parameters of failing parameterized tests are printed in the // Tests that parameters of failing parameterized tests are printed in the
// failing test summary. // failing test summary.
class FailingParamTest : public testing::TestWithParam<int> {}; class FailingParamTest : public testing::TestWithParam<int> {};
TEST_P(FailingParamTest, Fails) { TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
EXPECT_EQ(1, GetParam());
}
// This generates a test which will fail. Google Test is expected to print // This generates a test which will fail. Google Test is expected to print
// its parameter when it outputs the list of all failed tests. // its parameter when it outputs the list of all failed tests.
INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,
FailingParamTest,
testing::Values(2)); testing::Values(2));
// Tests that an empty value for the test suite basename yields just // Tests that an empty value for the test suite basename yields just
...@@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { ...@@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
// Tests HasFatalFailure() after a failed EXPECT check. // Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest, NonfatalFailureInSubroutine) { TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
printf("(expecting a failure on false)\n"); printf("(expecting a failure on false)\n");
EXPECT_TRUE(false); // Generates a nonfatal failure EXPECT_TRUE(false); // Generates a nonfatal failure
ASSERT_FALSE(HasFatalFailure()); // This should succeed. ASSERT_FALSE(HasFatalFailure()); // This should succeed.
} }
// Tests interleaving user logging and Google Test assertions. // Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest, InterleavingLoggingAndAssertions) { TEST(LoggingTest, InterleavingLoggingAndAssertions) {
static const int a[4] = { static const int a[4] = {3, 9, 2, 6};
3, 9, 2, 6
};
printf("(expecting 2 failures on (3) >= (a[i]))\n"); printf("(expecting 2 failures on (3) >= (a[i]))\n");
for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) { for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {
printf("i == %d\n", i); printf("i == %d\n", i);
EXPECT_GE(3, a[i]); EXPECT_GE(3, a[i]);
} }
...@@ -297,16 +288,14 @@ struct CheckPoints { ...@@ -297,16 +288,14 @@ struct CheckPoints {
static void ThreadWithScopedTrace(CheckPoints* check_points) { static void ThreadWithScopedTrace(CheckPoints* check_points) {
{ {
SCOPED_TRACE("Trace B"); SCOPED_TRACE("Trace B");
ADD_FAILURE() ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive).";
<< "Expected failure #1 (in thread B, only trace B alive).";
check_points->n1.Notify(); check_points->n1.Notify();
check_points->n2.WaitForNotification(); check_points->n2.WaitForNotification();
ADD_FAILURE() ADD_FAILURE()
<< "Expected failure #3 (in thread B, trace A & B both alive)."; << "Expected failure #3 (in thread B, trace A & B both alive).";
} // Trace B dies here. } // Trace B dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive).";
<< "Expected failure #4 (in thread B, only trace A alive).";
check_points->n3.Notify(); check_points->n3.Notify();
} }
...@@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { ...@@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) {
check_points.n2.Notify(); check_points.n2.Notify();
check_points.n3.WaitForNotification(); check_points.n3.WaitForNotification();
ADD_FAILURE() ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive).";
<< "Expected failure #5 (in thread A, only trace A alive).";
} // Trace A dies here. } // Trace A dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive).";
<< "Expected failure #6 (in thread A, no trace alive).";
thread.Join(); thread.Join();
} }
#endif // GTEST_IS_THREADSAFE #endif // GTEST_IS_THREADSAFE
...@@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { ...@@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test {
} }
private: private:
void Init() { void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
FAIL() << "Expected failure #1, in the test fixture c'tor.";
}
}; };
TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
...@@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test { ...@@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
FAIL() << "Expected failure #4, in the test fixture d'tor.";
}
}; };
TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
...@@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test { ...@@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
}; };
TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
...@@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) { ...@@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
namespace foo { namespace foo {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteWithSameTestNameTest, TEST_F(MixedUpTestSuiteWithSameTestNameTest,
TheSecondTestWithThisNameShouldFail) {} TheSecondTestWithThisNameShouldFail) {}
...@@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, ...@@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
namespace bar { namespace bar {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
// The following two tests are expected to fail. We rely on the // The following two tests are expected to fail. We rely on the
// golden file to check that Google Test generates the right error message. // golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
};
// Expected to fail. We rely on the golden file to check that Google Test // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // generates the right error message.
...@@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, ...@@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
// test case checks the scenario where TEST_F appears before TEST, and // test case checks the scenario where TEST_F appears before TEST, and
// the second one checks where TEST appears before TEST_F. // the second one checks where TEST appears before TEST_F.
class TEST_F_before_TEST_in_same_test_case : public testing::Test { class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
};
TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
...@@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} ...@@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
// generates the right error message. // generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
class TEST_before_TEST_F_in_same_test_case : public testing::Test { class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
};
TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
// Expected to fail. We rely on the golden file to check that Google Test // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // generates the right error message.
TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}
}
// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
int global_integer = 0; int global_integer = 0;
...@@ -552,9 +526,9 @@ int global_integer = 0; ...@@ -552,9 +526,9 @@ int global_integer = 0;
// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
}, "Expected non-fatal failure."); "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
...@@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { ...@@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
int m = 0; int m = 0;
static int n; static int n;
n = 1; n = 1;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
EXPECT_EQ(m, n) << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
// one non-fatal failure and no fatal failure. // one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
ADD_FAILURE() << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
// non-fatal failure. // non-fatal failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({}, "");
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
// non-fatal failures. // non-fatal failures.
TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
ADD_FAILURE() << "Expected non-fatal failure 1."; {
ADD_FAILURE() << "Expected non-fatal failure 2."; ADD_FAILURE() << "Expected non-fatal failure 1.";
}, ""); ADD_FAILURE() << "Expected non-fatal failure 2.";
},
"");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
// failure. // failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
FAIL() << "Expected fatal failure.";
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
...@@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { ...@@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
...@@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { ...@@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
// Tests that EXPECT_FATAL_FAILURE() can reference global variables. // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
ASSERT_EQ(1, global_integer) << "Expected fatal failure."; { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
}, "Expected fatal failure."); "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() can reference local static // Tests that EXPECT_FATAL_FAILURE() can reference local static
...@@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { ...@@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
static int n; static int n;
n = 1; n = 1;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
ASSERT_EQ(0, n) << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
// one fatal failure and no non-fatal failure. // one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
FAIL() << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({}, "");
}, "");
} }
// A helper for generating a fatal failure. // A helper for generating a fatal failure.
void FatalFailure() { void FatalFailure() { FAIL() << "Expected fatal failure."; }
FAIL() << "Expected fatal failure.";
}
// Tests that EXPECT_FATAL_FAILURE() fails when there are two // Tests that EXPECT_FATAL_FAILURE() fails when there are two
// fatal failures. // fatal failures.
TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
FatalFailure(); {
FatalFailure(); FatalFailure();
}, ""); FatalFailure();
},
"");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
ADD_FAILURE() << "Expected non-fatal failure.";
}, "");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when the statement being // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
...@@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { ...@@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
...@@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) { ...@@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
return info.param; return info.param;
} }
class ParamTest : public testing::TestWithParam<std::string> { class ParamTest : public testing::TestWithParam<std::string> {};
};
TEST_P(ParamTest, Success) { TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
EXPECT_EQ("a", GetParam());
}
TEST_P(ParamTest, Failure) { TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
EXPECT_EQ("b", GetParam()) << "Expected failure";
}
INSTANTIATE_TEST_SUITE_P(PrintingStrings, INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
ParamTest, testing::Values(std::string("a")), ParamNameFunc);
testing::Values(std::string("a")),
ParamNameFunc);
// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P. // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
using NoTests = ParamTest; using NoTests = ParamTest;
...@@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello")); ...@@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
// fails under kErrorOnUninstantiatedParameterizedTest=true // fails under kErrorOnUninstantiatedParameterizedTest=true
class DetectNotInstantiatedTest : public testing::TestWithParam<int> {}; class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
TEST_P(DetectNotInstantiatedTest, Used) { } TEST_P(DetectNotInstantiatedTest, Used) {}
// This would make the test failure from the above go away. // This would make the test failure from the above go away.
// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
TYPED_TEST_SUITE(TypedTest, testing::Types<int>); TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
TYPED_TEST(TypedTest, Success) { TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
EXPECT_EQ(0, TypeParam());
}
TYPED_TEST(TypedTest, Failure) { TYPED_TEST(TypedTest, Failure) {
EXPECT_EQ(1, TypeParam()) << "Expected failure"; EXPECT_EQ(1, TypeParam()) << "Expected failure";
...@@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {} ...@@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {}
TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
template <typename T> template <typename T>
class TypedTestP : public testing::Test { class TypedTestP : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, Success) { TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
EXPECT_EQ(0U, TypeParam());
}
TYPED_TEST_P(TypedTestP, Failure) { TYPED_TEST_P(TypedTestP, Failure) {
EXPECT_EQ(1U, TypeParam()) << "Expected failure"; EXPECT_EQ(1U, TypeParam()) << "Expected failure";
...@@ -813,7 +758,7 @@ class TypedTestPNames { ...@@ -813,7 +758,7 @@ class TypedTestPNames {
}; };
INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
TypedTestPNames); TypedTestPNames);
template <typename T> template <typename T>
class DetectNotInstantiatedTypesTest : public testing::Test {}; class DetectNotInstantiatedTypesTest : public testing::Test {};
...@@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used); ...@@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
// We rely on the golden file to verify that tests whose test case // We rely on the golden file to verify that tests whose test case
// name ends with DeathTest are run first. // name ends with DeathTest are run first.
TEST(ADeathTest, ShouldRunFirst) { TEST(ADeathTest, ShouldRunFirst) {}
}
// We rely on the golden file to verify that typed tests whose test // We rely on the golden file to verify that typed tests whose test
// case name ends with DeathTest are run first. // case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypedDeathTest : public testing::Test { class ATypedDeathTest : public testing::Test {};
};
typedef testing::Types<int, double> NumericTypes; typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes); TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
}
// We rely on the golden file to verify that type-parameterized tests // We rely on the golden file to verify that type-parameterized tests
// whose test case name ends with DeathTest are run first. // whose test case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypeParamDeathTest : public testing::Test { class ATypeParamDeathTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(ATypeParamDeathTest); TYPED_TEST_SUITE_P(ATypeParamDeathTest);
TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
}
REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst); REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
...@@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes); ...@@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
class ExpectFailureTest : public testing::Test { class ExpectFailureTest : public testing::Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2. public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode { enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) { static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) { if (failure == FATAL_FAILURE) {
FAIL() << "Expected fatal failure."; FAIL() << "Expected fatal failure.";
...@@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) { ...@@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) {
EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
// Expected fatal failure, but got a non-fatal failure. // Expected fatal failure, but got a non-fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
"Expected non-fatal "
"failure."); "failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
"Some other fatal failure "
"expected."); "expected.");
} }
...@@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { ...@@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
"Some other non-fatal "
"failure."); "failure.");
} }
...@@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { ...@@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
// Expected non-fatal failure, but succeeds. // Expected non-fatal failure, but succeeds.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),
"Expected non-fatal "
"failure."); "failure.");
// Expected non-fatal failure, but got a fatal failure. // Expected non-fatal failure, but got a fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
...@@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test { ...@@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test {
public: public:
static void SetUpTestSuite() { EXPECT_TRUE(false); } static void SetUpTestSuite() { EXPECT_TRUE(false); }
}; };
TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
std::abort();
}
// The main function. // The main function.
// //
// The idea is to use Google Test to run all the tests we have defined (some // The idea is to use Google Test to run all the tests we have defined (some
// of them are intended to fail), and then compare the test results // of them are intended to fail), and then compare the test results
// with the "golden" file. // with the "golden" file.
int main(int argc, char **argv) { int main(int argc, char** argv) {
GTEST_FLAG_SET(print_time, false); GTEST_FLAG_SET(print_time, false);
// We just run the tests, knowing some of them are intended to fail. // We just run the tests, knowing some of them are intended to fail.
...@@ -1092,17 +1030,16 @@ int main(int argc, char **argv) { ...@@ -1092,17 +1030,16 @@ int main(int argc, char **argv) {
if (GTEST_FLAG_GET(internal_run_death_test) != "") { if (GTEST_FLAG_GET(internal_run_death_test) != "") {
// Skip the usual output capturing if we're running as the child // Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test. // process of an threadsafe-style death test.
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
posix::FReopen("nul:", "w", stdout); posix::FReopen("nul:", "w", stdout);
# else #else
posix::FReopen("/dev/null", "w", stdout); posix::FReopen("/dev/null", "w", stdout);
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
if (internal_skip_environment_and_ad_hoc_tests) if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
return RUN_ALL_TESTS();
// Registers two global test environments. // Registers two global test environments.
// The golden file verifies that they are set up in the order they // The golden file verifies that they are set up in the order they
...@@ -1110,7 +1047,7 @@ int main(int argc, char **argv) { ...@@ -1110,7 +1047,7 @@ int main(int argc, char **argv) {
testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment);
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
#endif // _MSC_VER #endif // _MSC_VER
return RunAllTests(); return RunAllTests();
} }
...@@ -27,17 +27,14 @@ ...@@ -27,17 +27,14 @@
// (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.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(InvalidTestName, INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest,
DummyTest,
::testing::Values("InvalidWithQuotes"), ::testing::Values("InvalidWithQuotes"),
::testing::PrintToStringParamName()); ::testing::PrintToStringParamName());
...@@ -47,4 +44,3 @@ int main(int argc, char *argv[]) { ...@@ -47,4 +44,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
...@@ -27,22 +27,19 @@ ...@@ -27,22 +27,19 @@
// (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.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
std::string StringParamTestSuffix( std::string StringParamTestSuffix(
const testing::TestParamInfo<const char*>& info) { const testing::TestParamInfo<const char *> &info) {
return std::string(info.param); return std::string(info.param);
} }
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest,
DummyTest,
::testing::Values("a", "b", "a", "c"), ::testing::Values("a", "b", "a", "c"),
StringParamTestSuffix); StringParamTestSuffix);
} // namespace } // namespace
...@@ -51,5 +48,3 @@ int main(int argc, char *argv[]) { ...@@ -51,5 +48,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
...@@ -32,21 +32,21 @@ ...@@ -32,21 +32,21 @@
// generators objects produce correct parameter sequences and that // generators objects produce correct parameter sequences and that
// Google Test runtime instantiates correct tests from those sequences. // Google Test runtime instantiates correct tests from those sequences.
#include "gtest/gtest.h" #include "test/googletest-param-test-test.h"
# include <algorithm> #include <algorithm>
# include <iostream> #include <iostream>
# include <list> #include <list>
# include <set> #include <set>
# include <sstream> #include <sstream>
# include <string> #include <string>
# include <vector> #include <vector>
# include "src/gtest-internal-inl.h" // for UnitTestOptions #include "gtest/gtest.h"
# include "test/googletest-param-test-test.h" #include "src/gtest-internal-inl.h" // for UnitTestOptions
using ::std::vector;
using ::std::sort; using ::std::sort;
using ::std::vector;
using ::testing::AddGlobalTestEnvironment; using ::testing::AddGlobalTestEnvironment;
using ::testing::Bool; using ::testing::Bool;
...@@ -85,15 +85,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator, ...@@ -85,15 +85,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
// We cannot use EXPECT_EQ() here as the values may be tuples, // We cannot use EXPECT_EQ() here as the values may be tuples,
// which don't support <<. // which don't support <<.
EXPECT_TRUE(expected_values[i] == *it) EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i << "where i is " << i << ", expected_values[i] is "
<< ", expected_values[i] is " << PrintValue(expected_values[i]) << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n"; << ", and 'it' is an iterator created with the copy constructor.\n";
++it; ++it;
} }
EXPECT_TRUE(it == generator.end()) EXPECT_TRUE(it == generator.end())
<< "At the presumed end of sequence when accessing via an iterator " << "At the presumed end of sequence when accessing via an iterator "
<< "created with the copy constructor.\n"; << "created with the copy constructor.\n";
// Test the iterator assignment. The following lines verify that // Test the iterator assignment. The following lines verify that
// the sequence accessed via an iterator initialized via the // the sequence accessed via an iterator initialized via the
...@@ -105,15 +104,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator, ...@@ -105,15 +104,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
<< "At element " << i << " when accessing via an iterator " << "At element " << i << " when accessing via an iterator "
<< "created with the assignment operator.\n"; << "created with the assignment operator.\n";
EXPECT_TRUE(expected_values[i] == *it) EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i << "where i is " << i << ", expected_values[i] is "
<< ", expected_values[i] is " << PrintValue(expected_values[i]) << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n"; << ", and 'it' is an iterator created with the copy constructor.\n";
++it; ++it;
} }
EXPECT_TRUE(it == generator.end()) EXPECT_TRUE(it == generator.end())
<< "At the presumed end of sequence when accessing via an iterator " << "At the presumed end of sequence when accessing via an iterator "
<< "created with the assignment operator.\n"; << "created with the assignment operator.\n";
} }
template <typename T> template <typename T>
...@@ -216,8 +214,7 @@ class DogAdder { ...@@ -216,8 +214,7 @@ class DogAdder {
DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
DogAdder operator=(const DogAdder& other) { DogAdder operator=(const DogAdder& other) {
if (this != &other) if (this != &other) value_ = other.value_;
value_ = other.value_;
return *this; return *this;
} }
DogAdder operator+(const DogAdder& other) const { DogAdder operator+(const DogAdder& other) const {
...@@ -225,9 +222,7 @@ class DogAdder { ...@@ -225,9 +222,7 @@ class DogAdder {
msg << value_.c_str() << other.value_.c_str(); msg << value_.c_str() << other.value_.c_str();
return DogAdder(msg.GetString().c_str()); return DogAdder(msg.GetString().c_str());
} }
bool operator<(const DogAdder& other) const { bool operator<(const DogAdder& other) const { return value_ < other.value_; }
return value_ < other.value_;
}
const std::string& value() const { return value_; } const std::string& value() const { return value_; }
private: private:
...@@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { ...@@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
} }
TEST(ValuesTest, ValuesWorksForMaxLengthList) { TEST(ValuesTest, ValuesWorksForMaxLengthList) {
const ParamGenerator<int> gen = Values( const ParamGenerator<int> gen =
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 420, 430, 440, 450, 460, 470, 480, 490, 500);
410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
const int expected_values[] = { const int expected_values[] = {
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
...@@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) { ...@@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end()); EXPECT_TRUE(it == gen.end());
} }
// Tests that an generator produces correct sequence after being // Tests that an generator produces correct sequence after being
// assigned from another generator. // assigned from another generator.
TEST(ParamGeneratorTest, AssignmentWorks) { TEST(ParamGeneratorTest, AssignmentWorks) {
...@@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment { ...@@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
Message msg; Message msg;
msg << "TestsExpandedAndRun/" << i; msg << "TestsExpandedAndRun/" << i;
if (UnitTestOptions::FilterMatchesTest( if (UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest", "TestExpansionModule/MultipleTestGenerationTest",
msg.GetString().c_str())) { msg.GetString().c_str())) {
perform_check = true; perform_check = true;
} }
...@@ -595,8 +587,11 @@ class TestGenerationEnvironment : public ::testing::Environment { ...@@ -595,8 +587,11 @@ class TestGenerationEnvironment : public ::testing::Environment {
} }
private: private:
TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), TestGenerationEnvironment()
tear_down_count_(0), test_body_count_(0) {} : fixture_constructor_count_(0),
set_up_count_(0),
tear_down_count_(0),
test_body_count_(0) {}
int fixture_constructor_count_; int fixture_constructor_count_;
int set_up_count_; int set_up_count_;
...@@ -612,7 +607,7 @@ class TestGenerationTest : public TestWithParam<int> { ...@@ -612,7 +607,7 @@ class TestGenerationTest : public TestWithParam<int> {
public: public:
enum { enum {
PARAMETER_COUNT = PARAMETER_COUNT =
sizeof(test_generation_params)/sizeof(test_generation_params[0]) sizeof(test_generation_params) / sizeof(test_generation_params[0])
}; };
typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment; typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
...@@ -636,9 +631,9 @@ class TestGenerationTest : public TestWithParam<int> { ...@@ -636,9 +631,9 @@ class TestGenerationTest : public TestWithParam<int> {
for (int i = 0; i < PARAMETER_COUNT; ++i) { for (int i = 0; i < PARAMETER_COUNT; ++i) {
Message test_name; Message test_name;
test_name << "TestsExpandedAndRun/" << i; test_name << "TestsExpandedAndRun/" << i;
if ( !UnitTestOptions::FilterMatchesTest( if (!UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest", "TestExpansionModule/MultipleTestGenerationTest",
test_name.GetString())) { test_name.GetString())) {
all_tests_in_test_case_selected = false; all_tests_in_test_case_selected = false;
} }
} }
...@@ -729,8 +724,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) { ...@@ -729,8 +724,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
// Tests that a parameterized test case can be instantiated with multiple // Tests that a parameterized test case can be instantiated with multiple
// generators. // generators.
class MultipleInstantiationTest : public TestWithParam<int> {}; class MultipleInstantiationTest : public TestWithParam<int> {};
TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}
}
INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
...@@ -780,7 +774,7 @@ class NamingTest : public TestWithParam<int> {}; ...@@ -780,7 +774,7 @@ class NamingTest : public TestWithParam<int> {};
TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name()); EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name());
...@@ -801,7 +795,7 @@ class MacroNamingTest : public TestWithParam<int> {}; ...@@ -801,7 +795,7 @@ class MacroNamingTest : public TestWithParam<int> {};
TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name());
EXPECT_STREQ("FooSomeTestName/0", test_info->name()); EXPECT_STREQ("FooSomeTestName/0", test_info->name());
...@@ -815,7 +809,7 @@ class MacroNamingTestNonParametrized : public ::testing::Test {}; ...@@ -815,7 +809,7 @@ class MacroNamingTestNonParametrized : public ::testing::Test {};
TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized),
PREFIX_WITH_FOO(SomeTestName)) { PREFIX_WITH_FOO(SomeTestName)) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name()); EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name());
EXPECT_STREQ("FooSomeTestName", test_info->name()); EXPECT_STREQ("FooSomeTestName", test_info->name());
...@@ -839,9 +833,8 @@ TEST(MacroNameing, LookupNames) { ...@@ -839,9 +833,8 @@ TEST(MacroNameing, LookupNames) {
EXPECT_NE( // EXPECT_NE( //
know_suite_names.find("FortyTwo/MacroNamingTest"), know_suite_names.find("FortyTwo/MacroNamingTest"),
know_suite_names.end()); know_suite_names.end());
EXPECT_NE( EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
know_suite_names.find("MacroNamingTestNonParametrized"), know_suite_names.end());
know_suite_names.end());
// Check that the expected form of the test name actually exists. // Check that the expected form of the test name actually exists.
EXPECT_NE( // EXPECT_NE( //
know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
...@@ -924,7 +917,7 @@ class CustomIntegerNamingTest : public TestWithParam<int> {}; ...@@ -924,7 +917,7 @@ class CustomIntegerNamingTest : public TestWithParam<int> {};
TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << GetParam(); test_name_stream << "TestsReportCorrectNames/" << GetParam();
EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
...@@ -949,7 +942,7 @@ class CustomStructNamingTest : public TestWithParam<CustomStruct> {}; ...@@ -949,7 +942,7 @@ class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << GetParam(); test_name_stream << "TestsReportCorrectNames/" << GetParam();
EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
...@@ -979,7 +972,7 @@ class StatefulNamingTest : public ::testing::TestWithParam<int> { ...@@ -979,7 +972,7 @@ class StatefulNamingTest : public ::testing::TestWithParam<int> {
TEST_P(StatefulNamingTest, TestsReportCorrectNames) { TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
sum_ += GetParam(); sum_ += GetParam();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << sum_; test_name_stream << "TestsReportCorrectNames/" << sum_;
...@@ -1007,7 +1000,7 @@ class CommentTest : public TestWithParam<Unstreamable> {}; ...@@ -1007,7 +1000,7 @@ class CommentTest : public TestWithParam<Unstreamable> {};
TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
} }
...@@ -1021,7 +1014,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest, ...@@ -1021,7 +1014,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
// perform simple tests on both. // perform simple tests on both.
class NonParameterizedBaseTest : public ::testing::Test { class NonParameterizedBaseTest : public ::testing::Test {
public: public:
NonParameterizedBaseTest() : n_(17) { } NonParameterizedBaseTest() : n_(17) {}
protected: protected:
int n_; int n_;
}; };
...@@ -1029,16 +1023,14 @@ class NonParameterizedBaseTest : public ::testing::Test { ...@@ -1029,16 +1023,14 @@ class NonParameterizedBaseTest : public ::testing::Test {
class ParameterizedDerivedTest : public NonParameterizedBaseTest, class ParameterizedDerivedTest : public NonParameterizedBaseTest,
public ::testing::WithParamInterface<int> { public ::testing::WithParamInterface<int> {
protected: protected:
ParameterizedDerivedTest() : count_(0) { } ParameterizedDerivedTest() : count_(0) {}
int count_; int count_;
static int global_count_; static int global_count_;
}; };
int ParameterizedDerivedTest::global_count_ = 0; int ParameterizedDerivedTest::global_count_ = 0;
TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
EXPECT_EQ(17, n_);
}
TEST_P(ParameterizedDerivedTest, SeesSequence) { TEST_P(ParameterizedDerivedTest, SeesSequence) {
EXPECT_EQ(17, n_); EXPECT_EQ(17, n_);
...@@ -1046,11 +1038,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) { ...@@ -1046,11 +1038,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) {
EXPECT_EQ(GetParam(), global_count_++); EXPECT_EQ(GetParam(), global_count_++);
} }
class ParameterizedDeathTest : public ::testing::TestWithParam<int> { }; class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
EXPECT_DEATH_IF_SUPPORTED(GetParam(), EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
".* value-parameterized test .*");
} }
INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest, INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
...@@ -1084,11 +1075,11 @@ class NotInstantiatedTest : public testing::TestWithParam<int> {}; ...@@ -1084,11 +1075,11 @@ class NotInstantiatedTest : public testing::TestWithParam<int> {};
// ... we mark is as allowed. // ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
TEST_P(NotInstantiatedTest, Used) { } TEST_P(NotInstantiatedTest, Used) {}
using OtherName = NotInstantiatedTest; using OtherName = NotInstantiatedTest;
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
TEST_P(OtherName, Used) { } TEST_P(OtherName, Used) {}
// Used but not instantiated, this would fail. but... // Used but not instantiated, this would fail. but...
template <typename T> template <typename T>
...@@ -1097,11 +1088,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest); ...@@ -1097,11 +1088,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
// ... we mark is as allowed. // ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
TYPED_TEST_P(NotInstantiatedTypeTest, Used) { } TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used); REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
} // namespace works_here } // namespace works_here
int main(int argc, char **argv) { int main(int argc, char** argv) {
// Used in TestGenerationTest test suite. // Used in TestGenerationTest test suite.
AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
// Used in GeneratorEvaluationTest test suite. Tests that the updated value // Used in GeneratorEvaluationTest test suite. Tests that the updated value
......
...@@ -39,13 +39,11 @@ ...@@ -39,13 +39,11 @@
// Test fixture for testing definition and instantiation of a test // Test fixture for testing definition and instantiation of a test
// in separate translation units. // in separate translation units.
class ExternalInstantiationTest : public ::testing::TestWithParam<int> { class ExternalInstantiationTest : public ::testing::TestWithParam<int> {};
};
// Test fixture for testing instantiation of a test in multiple // Test fixture for testing instantiation of a test in multiple
// translation units. // translation units.
class InstantiationInMultipleTranslationUnitsTest class InstantiationInMultipleTranslationUnitsTest
: public ::testing::TestWithParam<int> { : public ::testing::TestWithParam<int> {};
};
#endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_ #endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
...@@ -46,8 +46,7 @@ ParamGenerator<int> extern_gen = Values(33); ...@@ -46,8 +46,7 @@ ParamGenerator<int> extern_gen = Values(33);
// and instantiated in another. The test is defined in // and instantiated in another. The test is defined in
// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is // googletest-param-test-test.cc and ExternalInstantiationTest fixture class is
// defined in gtest-param-test_test.h. // defined in gtest-param-test_test.h.
INSTANTIATE_TEST_SUITE_P(MultiplesOf33, INSTANTIATE_TEST_SUITE_P(MultiplesOf33, ExternalInstantiationTest,
ExternalInstantiationTest,
Values(33, 66)); Values(33, 66));
// Tests that a parameterized test case can be instantiated // Tests that a parameterized test case can be instantiated
...@@ -55,7 +54,5 @@ INSTANTIATE_TEST_SUITE_P(MultiplesOf33, ...@@ -55,7 +54,5 @@ INSTANTIATE_TEST_SUITE_P(MultiplesOf33,
// in googletest-param-test-test.cc and // in googletest-param-test-test.cc and
// InstantiationInMultipleTranslationUnitsTest fixture is defined in // InstantiationInMultipleTranslationUnitsTest fixture is defined in
// gtest-param-test_test.h // gtest-param-test_test.h
INSTANTIATE_TEST_SUITE_P(Sequence2, INSTANTIATE_TEST_SUITE_P(Sequence2, InstantiationInMultipleTranslationUnitsTest,
InstantiationInMultipleTranslationUnitsTest, Values(42 * 3, 42 * 4, 42 * 5));
Values(42*3, 42*4, 42*5));
...@@ -33,18 +33,18 @@ ...@@ -33,18 +33,18 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_MAC #if GTEST_OS_MAC
# include <time.h> #include <time.h>
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#include <chrono> // NOLINT #include <chrono> // NOLINT
#include <list> #include <list>
#include <memory> #include <memory>
#include <thread> // NOLINT #include <thread> // NOLINT
#include <utility> // For std::pair and std::make_pair. #include <utility> // For std::pair and std::make_pair.
#include <vector> #include <vector>
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
using std::make_pair; using std::make_pair;
...@@ -238,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) { ...@@ -238,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
} }
switch (0) switch (0)
case 0: case 0:
GTEST_CHECK_(true) << "Check failed in switch case"; GTEST_CHECK_(true) << "Check failed in switch case";
} }
// Verifies behavior of FormatFileLocation. // Verifies behavior of FormatFileLocation.
...@@ -281,7 +281,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { ...@@ -281,7 +281,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
} }
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
void* ThreadFunc(void* data) { void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data); internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
...@@ -357,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { ...@@ -357,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const bool a_false_condition = false; const bool a_false_condition = false;
const char regex[] = const char regex[] =
#ifdef _MSC_VER #ifdef _MSC_VER
"googletest-port-test\\.cc\\(\\d+\\):" "googletest-port-test\\.cc\\(\\d+\\):"
#elif GTEST_USES_POSIX_RE #elif GTEST_USES_POSIX_RE
"googletest-port-test\\.cc:[0-9]+" "googletest-port-test\\.cc:[0-9]+"
#else #else
"googletest-port-test\\.cc:\\d+" "googletest-port-test\\.cc:\\d+"
#endif // _MSC_VER #endif // _MSC_VER
".*a_false_condition.*Extra info.*"; ".*a_false_condition.*Extra info.*";
EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
regex); regex);
...@@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { ...@@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
EXPECT_EXIT({ EXPECT_EXIT(
GTEST_CHECK_(true) << "Extra info"; {
::std::cerr << "Success\n"; GTEST_CHECK_(true) << "Extra info";
exit(0); }, ::std::cerr << "Success\n";
exit(0);
},
::testing::ExitedWithCode(0), "Success"); ::testing::ExitedWithCode(0), "Success");
} }
...@@ -386,15 +388,15 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { ...@@ -386,15 +388,15 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
// For simplicity, we only cover the most important platforms here. // For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#if !GTEST_USES_PCRE #if !GTEST_USES_PCRE
# if GTEST_HAS_POSIX_RE #if GTEST_HAS_POSIX_RE
EXPECT_TRUE(GTEST_USES_POSIX_RE); EXPECT_TRUE(GTEST_USES_POSIX_RE);
# else #else
EXPECT_TRUE(GTEST_USES_SIMPLE_RE); EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
# endif #endif
#endif // !GTEST_USES_PCRE #endif // !GTEST_USES_PCRE
} }
...@@ -423,9 +425,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) { ...@@ -423,9 +425,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions. // Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest, RejectsInvalidRegex) { TYPED_TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
const RE invalid(TypeParam("?")); { const RE invalid(TypeParam("?")); },
}, "\"?\" is not a valid POSIX Extended regular expression."); "\"?\" is not a valid POSIX Extended regular expression.");
} }
// Tests RE::FullMatch(). // Tests RE::FullMatch().
...@@ -819,8 +821,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { ...@@ -819,8 +821,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
} }
TEST(MatchRegexAtHeadTest, TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
...@@ -876,17 +877,14 @@ TEST(RETest, ImplicitConstructorWorks) { ...@@ -876,17 +877,14 @@ TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions. // Tests that RE's constructors reject invalid regular expressions.
TEST(RETest, RejectsInvalidRegex) { TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
const RE normal(NULL); "NULL is not a valid simple regular expression");
}, "NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
const RE normal(".*(\\w+"); "'(' is unsupported");
}, "'(' is unsupported");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
const RE invalid("^?"); "'?' can only follow a repeatable token");
}, "'?' can only follow a repeatable token");
} }
// Tests RE::FullMatch(). // Tests RE::FullMatch().
...@@ -1028,12 +1026,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { ...@@ -1028,12 +1026,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
// AssertHeld() is flaky only in the presence of multiple threads accessing // AssertHeld() is flaky only in the presence of multiple threads accessing
// the lock. In this case, the test is robust. // the lock. In this case, the test is robust.
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
Mutex m; {
{ MutexLock lock(&m); } Mutex m;
m.AssertHeld(); { MutexLock lock(&m); }
}, m.AssertHeld();
"thread .*hold"); },
"thread .*hold");
} }
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
...@@ -1044,8 +1043,8 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { ...@@ -1044,8 +1043,8 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
class AtomicCounterWithMutex { class AtomicCounterWithMutex {
public: public:
explicit AtomicCounterWithMutex(Mutex* mutex) : explicit AtomicCounterWithMutex(Mutex* mutex)
value_(0), mutex_(mutex), random_(42) {} : value_(0), mutex_(mutex), random_(42) {}
void Increment() { void Increment() {
MutexLock lock(mutex_); MutexLock lock(mutex_);
...@@ -1076,7 +1075,7 @@ class AtomicCounterWithMutex { ...@@ -1076,7 +1075,7 @@ class AtomicCounterWithMutex {
std::chrono::milliseconds(random_.Generate(30))); std::chrono::milliseconds(random_.Generate(30)));
::InterlockedIncrement(&dummy); ::InterlockedIncrement(&dummy);
#else #else
# error "Memory barrier not implemented on this platform." #error "Memory barrier not implemented on this platform."
#endif // GTEST_HAS_PTHREAD #endif // GTEST_HAS_PTHREAD
} }
value_ = temp + 1; value_ = temp + 1;
...@@ -1086,12 +1085,11 @@ class AtomicCounterWithMutex { ...@@ -1086,12 +1085,11 @@ class AtomicCounterWithMutex {
private: private:
volatile int value_; volatile int value_;
Mutex* const mutex_; // Protects value_. Mutex* const mutex_; // Protects value_.
Random random_; Random random_;
}; };
void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) { void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
for (int i = 0; i < param.second; ++i) for (int i = 0; i < param.second; ++i) param.first->Increment();
param.first->Increment();
} }
// Tests that the mutex only lets one thread at a time to lock it. // Tests that the mutex only lets one thread at a time to lock it.
...@@ -1107,14 +1105,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { ...@@ -1107,14 +1105,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
// Creates and runs kThreadCount threads that increment locked_counter // Creates and runs kThreadCount threads that increment locked_counter
// kCycleCount times each. // kCycleCount times each.
for (int i = 0; i < kThreadCount; ++i) { for (int i = 0; i < kThreadCount; ++i) {
counting_threads[i].reset(new ThreadType(&CountingThreadFunc, counting_threads[i].reset(new ThreadType(
make_pair(&locked_counter, &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
kCycleCount), &threads_can_start));
&threads_can_start));
} }
threads_can_start.Notify(); threads_can_start.Notify();
for (int i = 0; i < kThreadCount; ++i) for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
counting_threads[i]->Join();
// If the mutex lets more than one thread to increment the counter at a // If the mutex lets more than one thread to increment the counter at a
// time, they are likely to encounter a race condition and have some // time, they are likely to encounter a race condition and have some
...@@ -1124,7 +1120,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { ...@@ -1124,7 +1120,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
} }
template <typename T> template <typename T>
void RunFromThread(void (func)(T), T param) { void RunFromThread(void(func)(T), T param) {
ThreadWithParam<T> thread(func, param, nullptr); ThreadWithParam<T> thread(func, param, nullptr);
thread.Join(); thread.Join();
} }
......
...@@ -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 tests the universal value printer. // This file tests the universal value printer.
...@@ -56,30 +55,20 @@ ...@@ -56,30 +55,20 @@
// Some user-defined types for testing the universal value printer. // Some user-defined types for testing the universal value printer.
// An anonymous enum type. // An anonymous enum type.
enum AnonymousEnum { enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
kAE1 = -1,
kAE2 = 1
};
// An enum without a user-defined printer. // An enum without a user-defined printer.
enum EnumWithoutPrinter { enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
kEWP1 = -2,
kEWP2 = 42
};
// An enum with a << operator. // An enum with a << operator.
enum EnumWithStreaming { enum EnumWithStreaming { kEWS1 = 10 };
kEWS1 = 10
};
std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
return os << (e == kEWS1 ? "kEWS1" : "invalid"); return os << (e == kEWS1 ? "kEWS1" : "invalid");
} }
// An enum with a PrintTo() function. // An enum with a PrintTo() function.
enum EnumWithPrintTo { enum EnumWithPrintTo { kEWPT1 = 1 };
kEWPT1 = 1
};
void PrintTo(EnumWithPrintTo e, std::ostream* os) { void PrintTo(EnumWithPrintTo e, std::ostream* os) {
*os << (e == kEWPT1 ? "kEWPT1" : "invalid"); *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
...@@ -108,6 +97,7 @@ template <typename T> ...@@ -108,6 +97,7 @@ template <typename T>
class UnprintableTemplateInGlobal { class UnprintableTemplateInGlobal {
public: public:
UnprintableTemplateInGlobal() : value_() {} UnprintableTemplateInGlobal() : value_() {}
private: private:
T value_; T value_;
}; };
...@@ -133,6 +123,7 @@ class UnprintableInFoo { ...@@ -133,6 +123,7 @@ class UnprintableInFoo {
public: public:
UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
double z() const { return z_; } double z() const { return z_; }
private: private:
char xy_[8]; char xy_[8];
double z_; double z_;
...@@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { ...@@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
} }
// A type with a user-defined << for printing its pointer. // A type with a user-defined << for printing its pointer.
struct PointerPrintable { struct PointerPrintable {};
};
::std::ostream& operator<<(::std::ostream& os, ::std::ostream& operator<<(::std::ostream& os,
const PointerPrintable* /* x */) { const PointerPrintable* /* x */) {
...@@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate { ...@@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate {
explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
const T& value() const { return value_; } const T& value() const { return value_; }
private: private:
T value_; T value_;
}; };
...@@ -180,6 +171,7 @@ class StreamableTemplateInFoo { ...@@ -180,6 +171,7 @@ class StreamableTemplateInFoo {
StreamableTemplateInFoo() : value_() {} StreamableTemplateInFoo() : value_() {}
const T& value() const { return value_; } const T& value() const { return value_; }
private: private:
T value_; T value_;
}; };
...@@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> { ...@@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> {
}; };
} // namespace internal } // namespace internal
namespace gtest_printers_test { namespace gtest_printers_test {
using ::std::deque; using ::std::deque;
...@@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) { ...@@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) {
// signed char. // signed char.
TEST(PrintCharTest, SignedChar) { TEST(PrintCharTest, SignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0'))); EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
EXPECT_EQ("'\\xCE' (-50)", EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
Print(static_cast<signed char>(-50)));
} }
// unsigned char. // unsigned char.
TEST(PrintCharTest, UnsignedChar) { TEST(PrintCharTest, UnsignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
EXPECT_EQ("'b' (98, 0x62)", EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
Print(static_cast<unsigned char>('b')));
} }
TEST(PrintCharTest, Char16) { TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
EXPECT_EQ("U+0041", Print(u'A'));
}
TEST(PrintCharTest, Char32) { TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
EXPECT_EQ("U+0041", Print(U'A'));
}
#ifdef __cpp_char8_t #ifdef __cpp_char8_t
TEST(PrintCharTest, Char8) { TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
EXPECT_EQ("U+0041", Print(u8'A'));
}
#endif #endif
// Tests printing other simple, built-in types. // Tests printing other simple, built-in types.
...@@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) { ...@@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) {
TEST(PrintBuiltInTypeTest, Integer) { TEST(PrintBuiltInTypeTest, Integer) {
EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16 EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16
EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16 EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16
EXPECT_EQ("4294967295", EXPECT_EQ("4294967295",
Print(std::numeric_limits<uint32_t>::max())); // uint32 Print(std::numeric_limits<uint32_t>::max())); // uint32
EXPECT_EQ("-2147483648", EXPECT_EQ("-2147483648",
...@@ -446,7 +429,7 @@ TEST(PrintBuiltInTypeTest, Size_t) { ...@@ -446,7 +429,7 @@ TEST(PrintBuiltInTypeTest, Size_t) {
#if !GTEST_OS_WINDOWS #if !GTEST_OS_WINDOWS
// Windows has no ssize_t type. // Windows has no ssize_t type.
EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t. EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
#endif // !GTEST_OS_WINDOWS #endif // !GTEST_OS_WINDOWS
} }
// gcc/clang __{u,}int128_t values. // gcc/clang __{u,}int128_t values.
...@@ -516,8 +499,9 @@ TEST(PrintCStringTest, Null) { ...@@ -516,8 +499,9 @@ TEST(PrintCStringTest, Null) {
// Tests that C strings are escaped properly. // Tests that C strings are escaped properly.
TEST(PrintCStringTest, EscapesProperly) { TEST(PrintCStringTest, EscapesProperly) {
const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" EXPECT_EQ(PrintPointer(p) +
"\\n\\r\\t\\v\\x7F\\xFF a\"", " pointing to \"'\\\"?\\\\\\a\\b\\f"
"\\n\\r\\t\\v\\x7F\\xFF a\"",
Print(p)); Print(p));
} }
...@@ -636,10 +620,12 @@ TEST(PrintWideCStringTest, Null) { ...@@ -636,10 +620,12 @@ TEST(PrintWideCStringTest, Null) {
// Tests that wide C strings are escaped properly. // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest, EscapesProperly) { TEST(PrintWideCStringTest, EscapesProperly) {
const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b',
'\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; '\f', '\n', '\r', '\t', '\v', 0xD3,
EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
"\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", EXPECT_EQ(PrintPointer(s) +
" pointing to L\"'\\\"?\\\\\\a\\b\\f"
"\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
Print(static_cast<const wchar_t*>(s))); Print(static_cast<const wchar_t*>(s)));
} }
#endif // native wchar_t #endif // native wchar_t
...@@ -721,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { ...@@ -721,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// standard disallows casting between pointers to functions and // standard disallows casting between pointers to functions and
// pointers to objects, and some compilers (e.g. GCC 3.4) enforce // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
// this limitation. // this limitation.
EXPECT_EQ( EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
PrintPointer(reinterpret_cast<const void*>( reinterpret_cast<internal::BiggestInt>(&MyFunction))),
reinterpret_cast<internal::BiggestInt>(&MyFunction))), Print(&MyFunction));
Print(&MyFunction));
int (*p)(bool) = NULL; // NOLINT int (*p)(bool) = NULL; // NOLINT
EXPECT_EQ("NULL", Print(p)); EXPECT_EQ("NULL", Print(p));
} }
...@@ -733,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { ...@@ -733,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// another. // another.
template <typename StringType> template <typename StringType>
AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
if (str.find(prefix, 0) == 0) if (str.find(prefix, 0) == 0) return AssertionSuccess();
return AssertionSuccess();
const bool is_wide_string = sizeof(prefix[0]) > 1; const bool is_wide_string = sizeof(prefix[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()
<< begin_string_quote << prefix << "\" is not a prefix of " << begin_string_quote << prefix << "\" is not a prefix of "
<< begin_string_quote << str << "\"\n"; << begin_string_quote << str << "\"\n";
} }
// Tests printing member variable pointers. Although they are called // Tests printing member variable pointers. Although they are called
...@@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) { ...@@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) {
EXPECT_TRUE(HasPrefix(Print(&Foo::value), EXPECT_TRUE(HasPrefix(Print(&Foo::value),
Print(sizeof(&Foo::value)) + "-byte object ")); Print(sizeof(&Foo::value)) + "-byte object "));
int Foo::*p = NULL; // NOLINT int Foo::*p = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p), EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
} }
// Tests printing member function pointers. Although they are called // Tests printing member function pointers. Although they are called
...@@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) { ...@@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) {
HasPrefix(Print(&Foo::MyVirtualMethod), HasPrefix(Print(&Foo::MyVirtualMethod),
Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
int (Foo::*p)(char) = NULL; // NOLINT int (Foo::*p)(char) = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p), EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
} }
// Tests printing C arrays. // Tests printing C arrays.
...@@ -791,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) { ...@@ -791,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) {
// One-dimensional array. // One-dimensional array.
TEST(PrintArrayTest, OneDimensionalArray) { TEST(PrintArrayTest, OneDimensionalArray) {
int a[5] = { 1, 2, 3, 4, 5 }; int a[5] = {1, 2, 3, 4, 5};
EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
} }
// Two-dimensional array. // Two-dimensional array.
TEST(PrintArrayTest, TwoDimensionalArray) { TEST(PrintArrayTest, TwoDimensionalArray) {
int a[2][5] = { int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 0 }
};
EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
} }
// Array of const elements. // Array of const elements.
TEST(PrintArrayTest, ConstArray) { TEST(PrintArrayTest, ConstArray) {
const bool a[1] = { false }; const bool a[1] = {false};
EXPECT_EQ("{ false }", PrintArrayHelper(a)); EXPECT_EQ("{ false }", PrintArrayHelper(a));
} }
// char array without terminating NUL. // char array without terminating NUL.
TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
// Array a contains '\0' in the middle and doesn't end with '\0'. // Array a contains '\0' in the middle and doesn't end with '\0'.
char a[] = { 'H', '\0', 'i' }; char a[] = {'H', '\0', 'i'};
EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
} }
...@@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) { ...@@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
// char8_t array with terminating NUL. // char8_t array with terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) { TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
const char8_t a[] = u8"\0世界"; const char8_t a[] = u8"\0世界";
EXPECT_EQ( EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
"u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
PrintArrayHelper(a));
} }
#endif #endif
...@@ -889,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) { ...@@ -889,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) {
// Array with many elements. // Array with many elements.
TEST(PrintArrayTest, BigArray) { TEST(PrintArrayTest, BigArray) {
int a[100] = { 1, 2, 3 }; int a[100] = {1, 2, 3};
EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
PrintArrayHelper(a)); PrintArrayHelper(a));
} }
...@@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) { ...@@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) {
// '\x6', '\x6B', or '\x6BA'. // '\x6', '\x6B', or '\x6BA'.
// a hex escaping sequence following by a decimal digit // a hex escaping sequence following by a decimal digit
EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
"3")));
// a hex escaping sequence following by a hex digit (lower-case) // a hex escaping sequence following by a hex digit (lower-case)
EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
"bananas")));
// a hex escaping sequence following by a hex digit (upper-case) // a hex escaping sequence following by a hex digit (upper-case)
EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
"BANANA")));
// a hex escaping sequence following by a non-xdigit // a hex escaping sequence following by a non-xdigit
EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
} }
...@@ -923,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) { ...@@ -923,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) {
// ::std::wstring. // ::std::wstring.
TEST(PrintWideStringTest, StringInStdNamespace) { TEST(PrintWideStringTest, StringInStdNamespace) {
const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" EXPECT_EQ(
"\\xD3\\x576\\x8D3\\xC74D a\\0\"", "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
Print(str)); "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
Print(str));
} }
TEST(PrintWideStringTest, StringAmbiguousHex) { TEST(PrintWideStringTest, StringAmbiguousHex) {
// same for wide strings. // same for wide strings.
EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", L"3")));
Print(::std::wstring(L"mm\x6" L"bananas"))); EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", L"bananas")));
Print(::std::wstring(L"NOM\x6" L"BANANA"))); EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
L"BANANA")));
EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
...@@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { ...@@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
EXPECT_EQ("{ 1, 3 }", Print(non_empty)); EXPECT_EQ("{ 1, 3 }", Print(non_empty));
} }
TEST(PrintStlContainerTest, OneElementHashMap) { TEST(PrintStlContainerTest, OneElementHashMap) {
::std::unordered_map<int, char> map1; ::std::unordered_map<int, char> map1;
map1[1] = 'a'; map1[1] = 'a';
...@@ -1065,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) { ...@@ -1065,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) {
const std::string result = Print(map1); const std::string result = Print(map1);
EXPECT_TRUE(result == "{ (5, true), (5, false) }" || EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
result == "{ (5, false), (5, true) }") result == "{ (5, false), (5, true) }")
<< " where Print(map1) returns \"" << result << "\"."; << " where Print(map1) returns \"" << result << "\".";
} }
TEST(PrintStlContainerTest, HashSet) { TEST(PrintStlContainerTest, HashSet) {
::std::unordered_set<int> set1; ::std::unordered_set<int> set1;
set1.insert(1); set1.insert(1);
...@@ -1078,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) { ...@@ -1078,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) {
TEST(PrintStlContainerTest, HashMultiSet) { TEST(PrintStlContainerTest, HashMultiSet) {
const int kSize = 5; const int kSize = 5;
int a[kSize] = { 1, 1, 2, 5, 1 }; int a[kSize] = {1, 1, 2, 5, 1};
::std::unordered_multiset<int> set1(a, a + kSize); ::std::unordered_multiset<int> set1(a, a + kSize);
// Elements of hash_multiset can be printed in any order. // Elements of hash_multiset can be printed in any order.
...@@ -1094,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) { ...@@ -1094,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) {
ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0); ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
numbers.push_back(result[i] - '0'); numbers.push_back(result[i] - '0');
} else { } else {
EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " EXPECT_EQ(expected_pattern[i], result[i])
<< result; << " where result is " << result;
} }
} }
...@@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { ...@@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) {
EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
} }
TEST(PrintStlContainerTest, List) { TEST(PrintStlContainerTest, List) {
const std::string a[] = {"hello", "world"}; const std::string a[] = {"hello", "world"};
const list<std::string> strings(a, a + 2); const list<std::string> strings(a, a + 2);
...@@ -1135,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) { ...@@ -1135,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) {
} }
TEST(PrintStlContainerTest, Set) { TEST(PrintStlContainerTest, Set) {
const unsigned int a[] = { 3, 0, 5 }; const unsigned int a[] = {3, 0, 5};
set<unsigned int> set1(a, a + 3); set<unsigned int> set1(a, a + 3);
EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
} }
TEST(PrintStlContainerTest, MultiSet) { TEST(PrintStlContainerTest, MultiSet) {
const int a[] = { 1, 1, 2, 5, 1 }; const int a[] = {1, 1, 2, 5, 1};
multiset<int> set1(a, a + 5); multiset<int> set1(a, a + 5);
EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
} }
TEST(PrintStlContainerTest, SinglyLinkedList) { TEST(PrintStlContainerTest, SinglyLinkedList) {
int a[] = { 9, 2, 8 }; int a[] = {9, 2, 8};
const std::forward_list<int> ints(a, a + 3); const std::forward_list<int> ints(a, a + 3);
EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
} }
...@@ -1166,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) { ...@@ -1166,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) {
} }
TEST(PrintStlContainerTest, LongSequence) { TEST(PrintStlContainerTest, LongSequence) {
const int a[100] = { 1, 2, 3 }; const int a[100] = {1, 2, 3};
const vector<int> v(a, a + 100); const vector<int> v(a, a + 100);
EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " EXPECT_EQ(
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
Print(v));
} }
TEST(PrintStlContainerTest, NestedContainer) { TEST(PrintStlContainerTest, NestedContainer) {
const int a1[] = { 1, 2 }; const int a1[] = {1, 2};
const int a2[] = { 3, 4, 5 }; const int a2[] = {3, 4, 5};
const list<int> l1(a1, a1 + 2); const list<int> l1(a1, a1 + 2);
const list<int> l2(a2, a2 + 3); const list<int> l2(a2, a2 + 3);
vector<list<int> > v; vector<list<int>> v;
v.push_back(l1); v.push_back(l1);
v.push_back(l2); v.push_back(l2);
EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
} }
TEST(PrintStlContainerTest, OneDimensionalNativeArray) { TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
const int a[3] = { 1, 2, 3 }; const int a[3] = {1, 2, 3};
NativeArray<int> b(a, 3, RelationToSourceReference()); NativeArray<int> b(a, 3, RelationToSourceReference());
EXPECT_EQ("{ 1, 2, 3 }", Print(b)); EXPECT_EQ("{ 1, 2, 3 }", Print(b));
} }
TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
NativeArray<int[3]> b(a, 2, RelationToSourceReference()); NativeArray<int[3]> b(a, 2, RelationToSourceReference());
EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
} }
...@@ -1243,20 +1222,18 @@ TEST(PrintStdTupleTest, VariousSizes) { ...@@ -1243,20 +1222,18 @@ TEST(PrintStdTupleTest, VariousSizes) {
t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
nullptr, "10"); nullptr, "10");
EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
" pointing to \"8\", NULL, \"10\")", " pointing to \"8\", NULL, \"10\")",
Print(t10)); Print(t10));
} }
// Nested tuples. // Nested tuples.
TEST(PrintStdTupleTest, NestedTuple) { TEST(PrintStdTupleTest, NestedTuple) {
::std::tuple< ::std::tuple<int, bool>, char> nested( ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
::std::make_tuple(5, true), 'a'); 'a');
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
} }
TEST(PrintNullptrT, Basic) { TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
EXPECT_EQ("(nullptr)", Print(nullptr));
}
TEST(PrintReferenceWrapper, Printable) { TEST(PrintReferenceWrapper, Printable) {
int x = 5; int x = 5;
...@@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) { ...@@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) {
// Unprintable types in the global namespace. // Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest, InGlobalNamespace) { TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
EXPECT_EQ("1-byte object <00>", EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
Print(UnprintableTemplateInGlobal<char>()));
} }
// Unprintable types in a user namespace. // Unprintable types in a user namespace.
...@@ -1298,14 +1274,15 @@ struct Big { ...@@ -1298,14 +1274,15 @@ struct Big {
}; };
TEST(PrintUnpritableTypeTest, BigObject) { TEST(PrintUnpritableTypeTest, BigObject) {
EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " EXPECT_EQ(
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
Print(Big())); "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
Print(Big()));
} }
// Tests printing user-defined streamable types. // Tests printing user-defined streamable types.
...@@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { ...@@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
// Tests printing user-defined types that have a PrintTo() function. // Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest, InUserNamespace) { TEST(PrintPrintableTypeTest, InUserNamespace) {
EXPECT_EQ("PrintableViaPrintTo: 0", EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
Print(::foo::PrintableViaPrintTo()));
} }
// Tests printing a pointer to a user-defined type that has a << // Tests printing a pointer to a user-defined type that has a <<
...@@ -1371,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) { ...@@ -1371,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) {
int n = 5; int n = 5;
EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
int a[2][3] = { int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
{ 0, 1, 2 },
{ 3, 4, 5 }
};
EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
PrintByRef(a)); PrintByRef(a));
const ::foo::UnprintableInFoo x; const ::foo::UnprintableInFoo x;
EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " EXPECT_EQ("@" + PrintPointer(&x) +
"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", " 16-byte object "
"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
PrintByRef(x)); PrintByRef(x));
} }
...@@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) { ...@@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) {
// this limitation. // this limitation.
const std::string fp_string = PrintPointer(reinterpret_cast<const void*>( const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
reinterpret_cast<internal::BiggestInt>(fp))); reinterpret_cast<internal::BiggestInt>(fp)));
EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
PrintByRef(fp));
} }
// Tests that the universal printer prints a member function pointer // Tests that the universal printer prints a member function pointer
// passed by reference. // passed by reference.
TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
int (Foo::*p)(char ch) = &Foo::MyMethod; int (Foo::*p)(char ch) = &Foo::MyMethod;
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p),
PrintByRef(p), "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
"@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " + " " + Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p2),
PrintByRef(p2), "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
"@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " + " " + Print(sizeof(p2)) + "-byte object "));
Print(sizeof(p2)) + "-byte object "));
} }
// Tests that the universal printer prints a member variable pointer // Tests that the universal printer prints a member variable pointer
// passed by reference. // passed by reference.
TEST(PrintReferenceTest, HandlesMemberVariablePointer) { TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
int Foo::*p = &Foo::value; // NOLINT int Foo::*p = &Foo::value; // NOLINT
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
PrintByRef(p), Print(sizeof(p)) + "-byte object "));
"@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
} }
// Tests that FormatForComparisonFailureMessage(), which is used to print // Tests that FormatForComparisonFailureMessage(), which is used to print
...@@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) { ...@@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
// scalar // scalar
TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
EXPECT_STREQ("123", EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
FormatForComparisonFailureMessage(123, 124).c_str());
} }
// non-char pointer // non-char pointer
...@@ -1446,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { ...@@ -1446,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
// In expression 'array == x', 'array' is compared by pointer. // In expression 'array == x', 'array' is compared by pointer.
// Therefore we want to print an array operand as a pointer. // Therefore we want to print an array operand as a pointer.
int n[] = { 1, 2, 3 }; int n[] = {1, 2, 3};
EXPECT_EQ(PrintPointer(n), EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
FormatForComparisonFailureMessage(n, n).c_str());
} }
// Tests formatting a char pointer when it's compared with another pointer. // Tests formatting a char pointer when it's compared with another pointer.
...@@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { ...@@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
// const char* // const char*
const char* s = "hello"; const char* s = "hello";
EXPECT_EQ(PrintPointer(s), EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
FormatForComparisonFailureMessage(s, s).c_str());
// char* // char*
char ch = 'a'; char ch = 'a';
...@@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { ...@@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
// const wchar_t* // const wchar_t*
const wchar_t* s = L"hello"; const wchar_t* s = L"hello";
EXPECT_EQ(PrintPointer(s), EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
FormatForComparisonFailureMessage(s, s).c_str());
// wchar_t* // wchar_t*
wchar_t ch = L'a'; wchar_t ch = L'a';
...@@ -1580,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { ...@@ -1580,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
// Useful for testing PrintToString(). We cannot use EXPECT_EQ() // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
// there as its implementation uses PrintToString(). The caller must // there as its implementation uses PrintToString(). The caller must
// ensure that 'value' has no side effect. // ensure that 'value' has no side effect.
#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
EXPECT_TRUE(PrintToString(value) == (expected_string)) \ EXPECT_TRUE(PrintToString(value) == (expected_string)) \
<< " where " #value " prints as " << (PrintToString(value)) << " where " #value " prints as " << (PrintToString(value))
TEST(PrintToStringTest, WorksForScalar) { TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
EXPECT_PRINT_TO_STRING_(123, "123");
}
TEST(PrintToStringTest, WorksForPointerToConstChar) { TEST(PrintToStringTest, WorksForPointerToConstChar) {
const char* p = "hello"; const char* p = "hello";
...@@ -1611,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { ...@@ -1611,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
} }
TEST(PrintToStringTest, WorksForArray) { TEST(PrintToStringTest, WorksForArray) {
int n[3] = { 1, 2, 3 }; int n[3] = {1, 2, 3};
EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
} }
...@@ -1628,7 +1592,7 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { ...@@ -1628,7 +1592,7 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
} }
TEST(PrintToStringTest, ContainsNonLatin) { TEST(PrintToStringTest, ContainsNonLatin) {
// Sanity test with valid UTF-8. Prints both in hex and as text. // Sanity test with valid UTF-8. Prints both in hex and as text.
std::string non_ascii_str = ::std::string("오전 4:30"); std::string non_ascii_str = ::std::string("오전 4:30");
EXPECT_PRINT_TO_STRING_(non_ascii_str, EXPECT_PRINT_TO_STRING_(non_ascii_str,
...@@ -1645,57 +1609,58 @@ TEST(IsValidUTF8Test, IllFormedUTF8) { ...@@ -1645,57 +1609,58 @@ TEST(IsValidUTF8Test, IllFormedUTF8) {
// as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
// expected to fail, thus output does not contain "As Text:". // expected to fail, thus output does not contain "As Text:".
static const char *const kTestdata[][2] = { static const char* const kTestdata[][2] = {
// 2-byte lead byte followed by a single-byte character. // 2-byte lead byte followed by a single-byte character.
{"\xC3\x74", "\"\\xC3t\""}, {"\xC3\x74", "\"\\xC3t\""},
// Valid 2-byte character followed by an orphan trail byte. // Valid 2-byte character followed by an orphan trail byte.
{"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
// Lead byte without trail byte. // Lead byte without trail byte.
{"abc\xC3", "\"abc\\xC3\""}, {"abc\xC3", "\"abc\\xC3\""},
// 3-byte lead byte, single-byte character, orphan trail byte. // 3-byte lead byte, single-byte character, orphan trail byte.
{"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
// Truncated 3-byte character. // Truncated 3-byte character.
{"\xE2\x80", "\"\\xE2\\x80\""}, {"\xE2\x80", "\"\\xE2\\x80\""},
// Truncated 3-byte character followed by valid 2-byte char. // Truncated 3-byte character followed by valid 2-byte char.
{"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
// Truncated 3-byte character followed by a single-byte character. // Truncated 3-byte character followed by a single-byte character.
{"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
// 3-byte lead byte followed by valid 3-byte character. // 3-byte lead byte followed by valid 3-byte character.
{"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
// 4-byte lead byte followed by valid 3-byte character. // 4-byte lead byte followed by valid 3-byte character.
{"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
// Truncated 4-byte character. // Truncated 4-byte character.
{"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
// Invalid UTF-8 byte sequences embedded in other chars. // Invalid UTF-8 byte sequences embedded in other chars.
{"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
{"abc\xC3\x84\xE2\x80\xC3\x84xyz", {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
"\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
// Non-shortest UTF-8 byte sequences are also ill-formed. // Non-shortest UTF-8 byte sequences are also ill-formed.
// The classics: xC0, xC1 lead byte. // The classics: xC0, xC1 lead byte.
{"\xC0\x80", "\"\\xC0\\x80\""}, {"\xC0\x80", "\"\\xC0\\x80\""},
{"\xC1\x81", "\"\\xC1\\x81\""}, {"\xC1\x81", "\"\\xC1\\x81\""},
// Non-shortest sequences. // Non-shortest sequences.
{"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
{"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
// Last valid code point before surrogate range, should be printed as text, // Last valid code point before surrogate range, should be printed as
// too. // text,
{"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""}, // too.
// Start of surrogate lead. Surrogates are not printed as text. {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
{"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, // Start of surrogate lead. Surrogates are not printed as text.
// Last non-private surrogate lead. {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
{"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, // Last non-private surrogate lead.
// First private-use surrogate lead. {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
{"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, // First private-use surrogate lead.
// Last private-use surrogate lead. {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
{"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, // Last private-use surrogate lead.
// Mid-point of surrogate trail. {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
{"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, // Mid-point of surrogate trail.
// First valid code point after surrogate range, should be printed as text, {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
// too. // First valid code point after surrogate range, should be printed as
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} // text,
}; // too.
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
} }
} }
...@@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { ...@@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
} }
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings( Strings result =
::std::make_tuple(1)); UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
ASSERT_EQ(1u, result.size()); ASSERT_EQ(1u, result.size());
EXPECT_EQ("1", result[0]); EXPECT_EQ("1", result[0]);
} }
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings( Strings result =
::std::make_tuple(1, 'a')); UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
ASSERT_EQ(2u, result.size()); ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]); EXPECT_EQ("1", result[0]);
EXPECT_EQ("'a' (97, 0x61)", result[1]); EXPECT_EQ("'a' (97, 0x61)", result[1]);
......
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