diff options
author | evan@chromium.org <evan@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-09-16 19:50:59 +0000 |
---|---|---|
committer | evan@chromium.org <evan@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-09-16 19:50:59 +0000 |
commit | eac1cd26a7fec8261bbe60f2aed21e01368e4af6 (patch) | |
tree | 133bdf2b91537dffe84dcf90cfaf712ce7259c32 /testing/gmock/test | |
parent | bb415723ffe8794f16c6639738066061d4f97288 (diff) | |
download | chromium_src-eac1cd26a7fec8261bbe60f2aed21e01368e4af6.zip chromium_src-eac1cd26a7fec8261bbe60f2aed21e01368e4af6.tar.gz chromium_src-eac1cd26a7fec8261bbe60f2aed21e01368e4af6.tar.bz2 |
clang: update gtest to r435 and gmock to r300.
This picks up some clang-specific fixes.
Unfortunately, the gtest update cascaded into a gmock update.
So I picked the earliest gmock version that mentioned a specific
gtest version so that they are more likely to work together.
gtest changelog:
- Fixes a leak in ThreadLocal.
- CMake 2.8/Visual Age compatibility patch by Hady Zalek.
- C++ Builder compatibility patch by Josh Kelley.
- Fixes gtest_filter_unittest and gtest_help_test on systems without death tests.
- Simplifies Makefile.am (by Zhanyong Wan and Vlad Losev).
- Adds alternative spellings for FAIL, SUCCEED, and TEST.
- Over-hauls README, and fixes Makefile.
- Fixes gtest-port_test on MinGW.
- Implements color output in GNU Screen sessions (issue 277).
- Minor improvement to hermetic build support in the CMake script, by Vlad Losev.
- Improves support for building Google Test as Windows DLL.
- Silence a Clang warning about an unused variable.
- Moves the universal printer from gmock to gtest and refactors the cmake script for reusing in gmock (by Vlad Losev).
- Suppresses some Clang warnings (by Chandler Carruth, Jeffrey Yasskin, and Zhanyong Wan).
- Renames CMake build script options.
- Lucid autotools compatibility patch by Jeffrey Yasskin.
- Replaces UniversalPrinter<T>::Print(x, os) with UniversalPrint(x, os) as appropriate (by Zhanyong Wan).
- Comment tweaks in CMakeLists.txt.
- Renames test script flags.
- Fixes a typo in comments.
- Adds GTEST_REMOVE_REFERENCE_AND_CONST_.
- Introduces gtest_force_shared_crt option for CMake build scripts.
- Implements printing parameters of failed parameterized tests (issue 71).
gmock changelog:
- Improves Makefile.am (by Vlad Losev); fixes Makefile and updates README (by Zhanyong Wan).
- Fixes a typo in README.
- Adds Each(m) (by Wojtek Moczydlowski); removes scripts/test/Makefile (by Zhanyong Wan); pulls in gtest r424.
- Adds a synchronization test.
- Fixes tests leaking altered values of GMOCK_FLAG(verbose) (issue 110).
- Moves the universal printer from gmock to gtest (by Vlad Losev).
- Renames test script flags.
- Adds CMake build script.
- Implements Pointwise().
- Fixes build failure on Windows/CMake (issue 111).
- Pulls r435 of gtest. This brings in the gtest_force_shared_crt option in CMake.
TEST=all existing tests should still pass
Review URL: http://codereview.chromium.org/3427004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@59701 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'testing/gmock/test')
-rw-r--r-- | testing/gmock/test/gmock-actions_test.cc | 8 | ||||
-rw-r--r-- | testing/gmock/test/gmock-generated-matchers_test.cc | 9 | ||||
-rw-r--r-- | testing/gmock/test/gmock-internal-utils_test.cc | 311 | ||||
-rw-r--r-- | testing/gmock/test/gmock-matchers_test.cc | 304 | ||||
-rw-r--r-- | testing/gmock/test/gmock-nice-strict_test.cc | 2 | ||||
-rw-r--r-- | testing/gmock/test/gmock-port_test.cc | 123 | ||||
-rw-r--r-- | testing/gmock/test/gmock-printers_test.cc | 1118 | ||||
-rw-r--r-- | testing/gmock/test/gmock-spec-builders_test.cc | 54 | ||||
-rw-r--r-- | testing/gmock/test/gmock_all_test.cc | 1 | ||||
-rwxr-xr-x | testing/gmock/test/gmock_output_test.py | 2 | ||||
-rw-r--r-- | testing/gmock/test/gmock_output_test_golden.txt | 6 | ||||
-rwxr-xr-x | testing/gmock/test/gmock_test_utils.py | 60 |
12 files changed, 317 insertions, 1681 deletions
diff --git a/testing/gmock/test/gmock-actions_test.cc b/testing/gmock/test/gmock-actions_test.cc index a2c6fe1..8391e5f 100644 --- a/testing/gmock/test/gmock-actions_test.cc +++ b/testing/gmock/test/gmock-actions_test.cc @@ -74,9 +74,9 @@ using testing::SetArgumentPointee; using testing::SetErrnoAndReturn; #endif -#if GMOCK_HAS_PROTOBUF_ +#if GTEST_HAS_PROTOBUF_ using testing::internal::TestMessage; -#endif // GMOCK_HAS_PROTOBUF_ +#endif // GTEST_HAS_PROTOBUF_ // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { @@ -689,7 +689,7 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { EXPECT_EQ('a', ch); } -#if GMOCK_HAS_PROTOBUF_ +#if GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. @@ -786,7 +786,7 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { EXPECT_EQ("hi", dest.string_field()); } -#endif // GMOCK_HAS_PROTOBUF_ +#endif // GTEST_HAS_PROTOBUF_ // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } diff --git a/testing/gmock/test/gmock-generated-matchers_test.cc b/testing/gmock/test/gmock-generated-matchers_test.cc index 12479af..eebca8a 100644 --- a/testing/gmock/test/gmock-generated-matchers_test.cc +++ b/testing/gmock/test/gmock-generated-matchers_test.cc @@ -192,7 +192,8 @@ TEST(ArgsTest, AcceptsTenTemplateArgs) { TEST(ArgsTest, DescirbesSelfCorrectly) { const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt()); - EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair (x, y) where x < y", + EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " + "the first < the second", Describe(m)); } @@ -200,14 +201,14 @@ TEST(ArgsTest, DescirbesNestedArgsCorrectly) { const Matcher<const tuple<int, bool, char, int>&> m = Args<0, 2, 3>(Args<2, 0>(Lt())); EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " - "whose fields (#2, #0) are a pair (x, y) where x < y", + "whose fields (#2, #0) are a pair where the first < the second", Describe(m)); } TEST(ArgsTest, DescribesNegationCorrectly) { const Matcher<tuple<int, char> > m = Args<1, 0>(Gt()); - EXPECT_EQ("are a tuple whose fields (#1, #0) are a pair (x, y) " - "where x > y is false", + EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " + "where the first > the second", DescribeNegation(m)); } diff --git a/testing/gmock/test/gmock-internal-utils_test.cc b/testing/gmock/test/gmock-internal-utils_test.cc index fc5d9e5..4309f7c 100644 --- a/testing/gmock/test/gmock-internal-utils_test.cc +++ b/testing/gmock/test/gmock-internal-utils_test.cc @@ -96,102 +96,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { ConvertIdentifierNameToWords("_Chapter11Section_1_")); } -// Tests that CompileAssertTypesEqual compiles when the type arguments are -// equal. -TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { - CompileAssertTypesEqual<void, void>(); - CompileAssertTypesEqual<int*, int*>(); -} - -// Tests that RemoveReference does not affect non-reference types. -TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { - CompileAssertTypesEqual<int, RemoveReference<int>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char>::type>(); -} - -// Tests that RemoveReference removes reference from reference types. -TEST(RemoveReferenceTest, RemovesReference) { - CompileAssertTypesEqual<int, RemoveReference<int&>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>(); -} - -// Tests GMOCK_REMOVE_REFERENCE_. - -template <typename T1, typename T2> -void TestGMockRemoveReference() { - CompileAssertTypesEqual<T1, GMOCK_REMOVE_REFERENCE_(T2)>(); -} - -TEST(RemoveReferenceTest, MacroVersion) { - TestGMockRemoveReference<int, int>(); - TestGMockRemoveReference<const char, const char&>(); -} - - -// Tests that RemoveConst does not affect non-const types. -TEST(RemoveConstTest, DoesNotAffectNonConstType) { - CompileAssertTypesEqual<int, RemoveConst<int>::type>(); - CompileAssertTypesEqual<char&, RemoveConst<char&>::type>(); -} - -// Tests that RemoveConst removes const from const types. -TEST(RemoveConstTest, RemovesConst) { - CompileAssertTypesEqual<int, RemoveConst<const int>::type>(); - CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>(); - CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>(); -} - -// Tests GMOCK_REMOVE_CONST_. - -template <typename T1, typename T2> -void TestGMockRemoveConst() { - CompileAssertTypesEqual<T1, GMOCK_REMOVE_CONST_(T2)>(); -} - -TEST(RemoveConstTest, MacroVersion) { - TestGMockRemoveConst<int, int>(); - TestGMockRemoveConst<double&, double&>(); - TestGMockRemoveConst<char, const char>(); -} - -// Tests that AddReference does not affect reference types. -TEST(AddReferenceTest, DoesNotAffectReferenceType) { - CompileAssertTypesEqual<int&, AddReference<int&>::type>(); - CompileAssertTypesEqual<const char&, AddReference<const char&>::type>(); -} - -// Tests that AddReference adds reference to non-reference types. -TEST(AddReferenceTest, AddsReference) { - CompileAssertTypesEqual<int&, AddReference<int>::type>(); - CompileAssertTypesEqual<const char&, AddReference<const char>::type>(); -} - -// Tests GMOCK_ADD_REFERENCE_. - -template <typename T1, typename T2> -void TestGMockAddReference() { - CompileAssertTypesEqual<T1, GMOCK_ADD_REFERENCE_(T2)>(); -} - -TEST(AddReferenceTest, MacroVersion) { - TestGMockAddReference<int&, int>(); - TestGMockAddReference<const char&, const char&>(); -} - -// Tests GMOCK_REFERENCE_TO_CONST_. - -template <typename T1, typename T2> -void TestGMockReferenceToConst() { - CompileAssertTypesEqual<T1, GMOCK_REFERENCE_TO_CONST_(T2)>(); -} - -TEST(GMockReferenceToConstTest, Works) { - TestGMockReferenceToConst<const char&, char>(); - TestGMockReferenceToConst<const int&, const int>(); - TestGMockReferenceToConst<const double&, double>(); - TestGMockReferenceToConst<const string&, const string&>(); -} - TEST(PointeeOfTest, WorksForSmartPointers) { CompileAssertTypesEqual<const char, PointeeOf<internal::linked_ptr<const char> >::type>(); @@ -217,38 +121,11 @@ TEST(GetRawPointerTest, WorksForRawPointers) { EXPECT_EQ(&n, GetRawPointer(&n)); } +// Tests KindOf<T>. + class Base {}; class Derived : public Base {}; -// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant. -TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { - GMOCK_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true); - GMOCK_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value), - const_false); -} - -// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can -// be implicitly converted to T2. -TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) { - EXPECT_TRUE((ImplicitlyConvertible<int, double>::value)); - EXPECT_TRUE((ImplicitlyConvertible<double, int>::value)); - EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value)); - EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value)); - EXPECT_TRUE((ImplicitlyConvertible<Derived&, const Base&>::value)); - EXPECT_TRUE((ImplicitlyConvertible<const Base, Base>::value)); -} - -// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1 -// cannot be implicitly converted to T2. -TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) { - EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<Base&, Derived&>::value)); -} - -// Tests KindOf<T>. - TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); // NOLINT } @@ -382,46 +259,6 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { } } -// Tests that IsAProtocolMessage<T>::value is a compile-time constant. -TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { - GMOCK_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value, const_true); - GMOCK_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false); -} - -// Tests that IsAProtocolMessage<T>::value is true when T is -// ProtocolMessage or a sub-class of it. -TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { - EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); - EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); -#if GMOCK_HAS_PROTOBUF_ - EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value); -#endif // GMOCK_HAS_PROTOBUF_ -} - -// Tests that IsAProtocolMessage<T>::value is false when T is neither -// ProtocolMessage nor a sub-class of it. -TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { - EXPECT_FALSE(IsAProtocolMessage<int>::value); - EXPECT_FALSE(IsAProtocolMessage<const Base>::value); -} - -// Tests IsContainerTest. - -class NonContainer {}; - -TEST(IsContainerTestTest, WorksForNonContainer) { - EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0))); - EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0))); - EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0))); -} - -TEST(IsContainerTestTest, WorksForContainer) { - EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest<std::vector<bool> >(0))); - EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest<std::map<int, double> >(0))); -} - // Tests the TupleMatches() template function. TEST(TupleMatchesTest, WorksForSize0) { @@ -565,10 +402,12 @@ void TestLogWithSeverity(const string& verbosity, LogSeverity severity, // Tests that when the stack_frames_to_skip parameter is negative, // Log() doesn't include the stack trace in the output. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { + const string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = kInfoVerbosity; CaptureStdout(); Log(INFO, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); + GMOCK_FLAG(verbose) = saved_flag; } // Tests that in opt mode, a positive stack_frames_to_skip argument is @@ -735,148 +574,6 @@ TEST(OnCallTest, LogsAnythingArgument) { #endif // GTEST_HAS_STREAM_REDIRECTION_ -// Tests ArrayEq(). - -TEST(ArrayEqTest, WorksForDegeneratedArrays) { - EXPECT_TRUE(ArrayEq(5, 5L)); - EXPECT_FALSE(ArrayEq('a', 0)); -} - -TEST(ArrayEqTest, WorksForOneDimensionalArrays) { - const int a[] = { 0, 1 }; - long b[] = { 0, 1 }; - EXPECT_TRUE(ArrayEq(a, b)); - EXPECT_TRUE(ArrayEq(a, 2, b)); - - b[0] = 2; - EXPECT_FALSE(ArrayEq(a, b)); - EXPECT_FALSE(ArrayEq(a, 1, b)); -} - -TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { - const char a[][3] = { "hi", "lo" }; - const char b[][3] = { "hi", "lo" }; - const char c[][3] = { "hi", "li" }; - - EXPECT_TRUE(ArrayEq(a, b)); - EXPECT_TRUE(ArrayEq(a, 2, b)); - - EXPECT_FALSE(ArrayEq(a, c)); - EXPECT_FALSE(ArrayEq(a, 2, c)); -} - -// Tests ArrayAwareFind(). - -TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { - const char a[] = "hello"; - EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); - EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); -} - -TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { - int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; - const int b[2] = { 2, 3 }; - EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); - - const int c[2] = { 6, 7 }; - EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); -} - -// Tests CopyArray(). - -TEST(CopyArrayTest, WorksForDegeneratedArrays) { - int n = 0; - CopyArray('a', &n); - EXPECT_EQ('a', n); -} - -TEST(CopyArrayTest, WorksForOneDimensionalArrays) { - const char a[3] = "hi"; - int b[3]; - CopyArray(a, &b); - EXPECT_TRUE(ArrayEq(a, b)); - - int c[3]; - CopyArray(a, 3, c); - EXPECT_TRUE(ArrayEq(a, c)); -} - -TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { - const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; - int b[2][3]; - CopyArray(a, &b); - EXPECT_TRUE(ArrayEq(a, b)); - - int c[2][3]; - CopyArray(a, 2, c); - EXPECT_TRUE(ArrayEq(a, c)); -} - -// Tests NativeArray. - -TEST(NativeArrayTest, ConstructorFromArrayWorks) { - const int a[3] = { 0, 1, 2 }; - NativeArray<int> na(a, 3, kReference); - EXPECT_EQ(3U, na.size()); - EXPECT_EQ(a, na.begin()); -} - -TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { - typedef int Array[2]; - Array* a = new Array[1]; - (*a)[0] = 0; - (*a)[1] = 1; - NativeArray<int> na(*a, 2, kCopy); - EXPECT_NE(*a, na.begin()); - delete[] a; - EXPECT_EQ(0, na.begin()[0]); - EXPECT_EQ(1, na.begin()[1]); - - // We rely on the heap checker to verify that na deletes the copy of - // array. -} - -TEST(NativeArrayTest, TypeMembersAreCorrect) { - StaticAssertTypeEq<char, NativeArray<char>::value_type>(); - StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>(); - - StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>(); - StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>(); -} - -TEST(NativeArrayTest, MethodsWork) { - const int a[3] = { 0, 1, 2 }; - NativeArray<int> na(a, 3, kCopy); - ASSERT_EQ(3U, na.size()); - EXPECT_EQ(3, na.end() - na.begin()); - - NativeArray<int>::const_iterator it = na.begin(); - EXPECT_EQ(0, *it); - ++it; - EXPECT_EQ(1, *it); - it++; - EXPECT_EQ(2, *it); - ++it; - EXPECT_EQ(na.end(), it); - - EXPECT_THAT(na, Eq(na)); - - NativeArray<int> na2(a, 3, kReference); - EXPECT_THAT(na, Eq(na2)); - - const int b1[3] = { 0, 1, 1 }; - const int b2[4] = { 0, 1, 2, 3 }; - EXPECT_THAT(na, Not(Eq(NativeArray<int>(b1, 3, kReference)))); - EXPECT_THAT(na, Not(Eq(NativeArray<int>(b2, 4, kCopy)))); -} - -TEST(NativeArrayTest, WorksForTwoDimensionalArray) { - const char a[2][3] = { "hi", "lo" }; - NativeArray<char[3]> na(a, 2, kReference); - ASSERT_EQ(2U, na.size()); - EXPECT_EQ(a, na.begin()); -} - // Tests StlContainerView. TEST(StlContainerViewTest, WorksForStlContainer) { diff --git a/testing/gmock/test/gmock-matchers_test.cc b/testing/gmock/test/gmock-matchers_test.cc index 6d784f1..3b151db 100644 --- a/testing/gmock/test/gmock-matchers_test.cc +++ b/testing/gmock/test/gmock-matchers_test.cc @@ -61,12 +61,19 @@ bool SkipPrefix(const char* prefix, const char** pstr); namespace gmock_matchers_test { +using std::list; using std::make_pair; using std::map; using std::multimap; +using std::multiset; +using std::ostream; using std::pair; +using std::set; using std::stringstream; +using std::tr1::get; using std::tr1::make_tuple; +using std::tr1::tuple; +using std::vector; using testing::A; using testing::AllArgs; using testing::AllOf; @@ -102,6 +109,7 @@ using testing::Not; using testing::NotNull; using testing::Pair; using testing::Pointee; +using testing::Pointwise; using testing::PolymorphicMatcher; using testing::Property; using testing::Ref; @@ -142,7 +150,7 @@ class GreaterThanMatcher : public MatcherInterface<int> { public: explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is > " << rhs_; } @@ -187,9 +195,9 @@ string DescribeNegation(const Matcher<T>& m) { // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> string Explain(const MatcherType& m, const Value& x) { - stringstream ss; - m.ExplainMatchResultTo(x, &ss); - return ss.str(); + StringMatchResultListener listener; + ExplainMatchResult(m, x, &listener); + return listener.str(); } TEST(MatchResultListenerTest, StreamingWorks) { @@ -226,7 +234,7 @@ class EvenMatcherImpl : public MatcherInterface<int> { return x % 2 == 0; } - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } @@ -256,7 +264,7 @@ class NewEvenMatcherImpl : public MatcherInterface<int> { return match; } - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } }; @@ -363,20 +371,20 @@ TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { // Tests that MakePolymorphicMatcher() can construct a polymorphic // matcher from its implementation using the old API. -const int bar = 1; +const int g_bar = 1; class ReferencesBarOrIsZeroImpl { public: template <typename T> bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const { const void* p = &x; - return p == &bar || x == 0; + return p == &g_bar || x == 0; } - void DescribeTo(::std::ostream* os) const { *os << "bar or zero"; } + void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't reference bar and is not zero"; + void DescribeNegationTo(ostream* os) const { + *os << "doesn't reference g_bar and is not zero"; } }; @@ -391,24 +399,24 @@ TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { Matcher<const int&> m1 = ReferencesBarOrIsZero(); EXPECT_TRUE(m1.Matches(0)); // Verifies that the identity of a by-reference argument is preserved. - EXPECT_TRUE(m1.Matches(bar)); + EXPECT_TRUE(m1.Matches(g_bar)); EXPECT_FALSE(m1.Matches(1)); - EXPECT_EQ("bar or zero", Describe(m1)); + EXPECT_EQ("g_bar or zero", Describe(m1)); // Using a polymorphic matcher to match a value type. Matcher<double> m2 = ReferencesBarOrIsZero(); EXPECT_TRUE(m2.Matches(0.0)); EXPECT_FALSE(m2.Matches(0.1)); - EXPECT_EQ("bar or zero", Describe(m2)); + EXPECT_EQ("g_bar or zero", Describe(m2)); } // Tests implementing a polymorphic matcher using MatchAndExplain(). class PolymorphicIsEvenImpl { public: - void DescribeTo(::std::ostream* os) const { *os << "is even"; } + void DescribeTo(ostream* os) const { *os << "is even"; } - void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(ostream* os) const { *os << "is odd"; } @@ -1148,7 +1156,7 @@ TEST(KeyTest, SafelyCastsInnerMatcher) { } TEST(KeyTest, InsideContainsUsingMap) { - std::map<int, char> container; + map<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1157,7 +1165,7 @@ TEST(KeyTest, InsideContainsUsingMap) { } TEST(KeyTest, InsideContainsUsingMultimap) { - std::multimap<int, char> container; + multimap<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1266,7 +1274,7 @@ TEST(PairTest, SafelyCastsInnerMatchers) { } TEST(PairTest, InsideContainsUsingMap) { - std::map<int, char> container; + map<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1759,7 +1767,7 @@ TEST(Eq2Test, MatchesEqualArguments) { // Tests that Eq() describes itself properly. TEST(Eq2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Eq(); - EXPECT_EQ("are a pair (x, y) where x == y", Describe(m)); + EXPECT_EQ("are an equal pair", Describe(m)); } // Tests that Ge() matches a 2-tuple where the first field >= the @@ -1774,7 +1782,7 @@ TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { // Tests that Ge() describes itself properly. TEST(Ge2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Ge(); - EXPECT_EQ("are a pair (x, y) where x >= y", Describe(m)); + EXPECT_EQ("are a pair where the first >= the second", Describe(m)); } // Tests that Gt() matches a 2-tuple where the first field > the @@ -1789,7 +1797,7 @@ TEST(Gt2Test, MatchesGreaterThanArguments) { // Tests that Gt() describes itself properly. TEST(Gt2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Gt(); - EXPECT_EQ("are a pair (x, y) where x > y", Describe(m)); + EXPECT_EQ("are a pair where the first > the second", Describe(m)); } // Tests that Le() matches a 2-tuple where the first field <= the @@ -1804,7 +1812,7 @@ TEST(Le2Test, MatchesLessThanOrEqualArguments) { // Tests that Le() describes itself properly. TEST(Le2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Le(); - EXPECT_EQ("are a pair (x, y) where x <= y", Describe(m)); + EXPECT_EQ("are a pair where the first <= the second", Describe(m)); } // Tests that Lt() matches a 2-tuple where the first field < the @@ -1819,7 +1827,7 @@ TEST(Lt2Test, MatchesLessThanArguments) { // Tests that Lt() describes itself properly. TEST(Lt2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Lt(); - EXPECT_EQ("are a pair (x, y) where x < y", Describe(m)); + EXPECT_EQ("are a pair where the first < the second", Describe(m)); } // Tests that Ne() matches a 2-tuple where the first field != the @@ -1834,7 +1842,7 @@ TEST(Ne2Test, MatchesUnequalArguments) { // Tests that Ne() describes itself properly. TEST(Ne2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Ne(); - EXPECT_EQ("are a pair (x, y) where x != y", Describe(m)); + EXPECT_EQ("are an unequal pair", Describe(m)); } // Tests that Not(m) matches any value that doesn't match m. @@ -3336,11 +3344,11 @@ class DivisibleByImpl { return (n % divider_) == 0; } - void DescribeTo(::std::ostream* os) const { + void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; } - void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(ostream* os) const { *os << "is not divisible by " << divider_; } @@ -3442,10 +3450,10 @@ template <typename T> class ContainerEqTest : public testing::Test {}; typedef testing::Types< - std::set<int>, - std::vector<size_t>, - std::multiset<size_t>, - std::list<int> > + set<int>, + vector<size_t>, + multiset<size_t>, + list<int> > ContainerEqTestTypes; TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes); @@ -3513,9 +3521,9 @@ TYPED_TEST(ContainerEqTest, DuplicateDifference) { TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; - std::vector<int> my_set(vals, vals + 6); - std::vector<int> test_set(test_vals, test_vals + 3); - const Matcher<std::vector<int> > m = ContainerEq(my_set); + vector<int> my_set(vals, vals + 6); + vector<int> test_set(test_vals, test_vals + 3); + const Matcher<vector<int> > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which doesn't have these expected elements: 3, 8", Explain(m, test_set)); @@ -3526,9 +3534,9 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) { TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; - std::list<size_t> my_set(vals, vals + 6); - std::list<size_t> test_set(test_vals, test_vals + 7); - const Matcher<const std::list<size_t>&> m = ContainerEq(my_set); + list<size_t> my_set(vals, vals + 6); + list<size_t> test_set(test_vals, test_vals + 7); + const Matcher<const list<size_t>&> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46", Explain(m, test_set)); @@ -3538,9 +3546,9 @@ TEST(ContainerEqExtraTest, MultipleValuesAdded) { TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 92, 46}; - std::list<size_t> my_set(vals, vals + 6); - std::list<size_t> test_set(test_vals, test_vals + 5); - const Matcher<const std::list<size_t> > m = ContainerEq(my_set); + list<size_t> my_set(vals, vals + 6); + list<size_t> test_set(test_vals, test_vals + 5); + const Matcher<const list<size_t> > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46,\n" "and doesn't have these expected elements: 5, 8", @@ -3552,9 +3560,9 @@ TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 5, 8}; - std::vector<int> my_set(vals, vals + 6); - std::vector<int> test_set(test_vals, test_vals + 5); - const Matcher<std::vector<int> > m = ContainerEq(my_set); + vector<int> my_set(vals, vals + 6); + vector<int> test_set(test_vals, test_vals + 5); + const Matcher<vector<int> > m = ContainerEq(my_set); EXPECT_TRUE(m.Matches(my_set)); EXPECT_FALSE(m.Matches(test_set)); // There is nothing to report when both sets contain all the same values. @@ -3564,15 +3572,15 @@ TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { // Tests that ContainerEq works for non-trivial associative containers, // like maps. TEST(ContainerEqExtraTest, WorksForMaps) { - std::map<int, std::string> my_map; + map<int, std::string> my_map; my_map[0] = "a"; my_map[1] = "b"; - std::map<int, std::string> test_map; + map<int, std::string> test_map; test_map[0] = "aa"; test_map[1] = "b"; - const Matcher<const std::map<int, std::string>&> m = ContainerEq(my_map); + const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); EXPECT_TRUE(m.Matches(my_map)); EXPECT_FALSE(m.Matches(test_map)); @@ -3984,5 +3992,209 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { // explanation. } +// Tests Each(). + +TEST(EachTest, ExplainsMatchResultCorrectly) { + set<int> a; // empty + + Matcher<set<int> > m = Each(2); + EXPECT_EQ("", Explain(m, a)); + + Matcher<const int(&)[1]> n = Each(1); + + const int b[1] = { 1 }; + EXPECT_EQ("", Explain(n, b)); + + n = Each(3); + EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); + + a.insert(1); + a.insert(2); + a.insert(3); + m = Each(GreaterThan(0)); + EXPECT_EQ("", Explain(m, a)); + + m = Each(GreaterThan(10)); + EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", + Explain(m, a)); +} + +TEST(EachTest, DescribesItselfCorrectly) { + Matcher<vector<int> > m = Each(1); + EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); + + Matcher<vector<int> > m2 = Not(m); + EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); +} + +TEST(EachTest, MatchesVectorWhenAllElementsMatch) { + vector<int> some_vector; + EXPECT_THAT(some_vector, Each(1)); + some_vector.push_back(3); + EXPECT_THAT(some_vector, Not(Each(1))); + EXPECT_THAT(some_vector, Each(3)); + some_vector.push_back(1); + some_vector.push_back(2); + EXPECT_THAT(some_vector, Not(Each(3))); + EXPECT_THAT(some_vector, Each(Lt(3.5))); + + vector<string> another_vector; + another_vector.push_back("fee"); + EXPECT_THAT(another_vector, Each(string("fee"))); + another_vector.push_back("fie"); + another_vector.push_back("foe"); + another_vector.push_back("fum"); + EXPECT_THAT(another_vector, Not(Each(string("fee")))); +} + +TEST(EachTest, MatchesMapWhenAllElementsMatch) { + map<const char*, int> my_map; + const char* bar = "a string"; + my_map[bar] = 2; + EXPECT_THAT(my_map, Each(make_pair(bar, 2))); + + map<string, int> another_map; + EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + another_map["fee"] = 1; + EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + another_map["fie"] = 2; + another_map["foe"] = 3; + another_map["fum"] = 4; + EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); + EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); +} + +TEST(EachTest, AcceptsMatcher) { + const int a[] = { 1, 2, 3 }; + EXPECT_THAT(a, Each(Gt(0))); + EXPECT_THAT(a, Not(Each(Gt(1)))); +} + +TEST(EachTest, WorksForNativeArrayAsTuple) { + const int a[] = { 1, 2 }; + const int* const pointer = a; + EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); + EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); +} + +// For testing Pointwise(). +class IsHalfOfMatcher { + public: + template <typename T1, typename T2> + bool MatchAndExplain(const tuple<T1, T2>& a_pair, + MatchResultListener* listener) const { + if (get<0>(a_pair) == get<1>(a_pair)/2) { + *listener << "where the second is " << get<1>(a_pair); + return true; + } else { + *listener << "where the second/2 is " << get<1>(a_pair)/2; + return false; + } + } + + void DescribeTo(ostream* os) const { + *os << "are a pair where the first is half of the second"; + } + + void DescribeNegationTo(ostream* os) const { + *os << "are a pair where the first isn't half of the second"; + } +}; + +PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { + return MakePolymorphicMatcher(IsHalfOfMatcher()); +} + +TEST(PointwiseTest, DescribesSelf) { + vector<int> rhs; + rhs.push_back(1); + rhs.push_back(2); + rhs.push_back(3); + const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); + EXPECT_EQ("contains 3 values, where each value and its corresponding value " + "in { 1, 2, 3 } are a pair where the first is half of the second", + Describe(m)); + EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " + "index i where x and the i-th value of { 1, 2, 3 } are a pair " + "where the first isn't half of the second", + DescribeNegation(m)); +} + +TEST(PointwiseTest, MakesCopyOfRhs) { + list<signed char> rhs; + rhs.push_back(2); + rhs.push_back(4); + + int lhs[] = { 1, 2 }; + const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); + EXPECT_THAT(lhs, m); + + // Changing rhs now shouldn't affect m, which made a copy of rhs. + rhs.push_back(6); + EXPECT_THAT(lhs, m); +} + +TEST(PointwiseTest, WorksForLhsNativeArray) { + const int lhs[] = { 1, 2, 3 }; + vector<int> rhs; + rhs.push_back(2); + rhs.push_back(4); + rhs.push_back(6); + EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); +} + +TEST(PointwiseTest, WorksForRhsNativeArray) { + const int rhs[] = { 1, 2, 3 }; + vector<int> lhs; + lhs.push_back(2); + lhs.push_back(4); + lhs.push_back(6); + EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); + EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); +} + +TEST(PointwiseTest, RejectsWrongSize) { + const double lhs[2] = { 1, 2 }; + const int rhs[1] = { 0 }; + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); + EXPECT_EQ("which contains 2 values", + Explain(Pointwise(Gt(), rhs), lhs)); + + const int rhs2[3] = { 0, 1, 2 }; + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); +} + +TEST(PointwiseTest, RejectsWrongContent) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 6, 4 }; + EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); + EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " + "where the second/2 is 3", + Explain(Pointwise(IsHalfOf(), rhs), lhs)); +} + +TEST(PointwiseTest, AcceptsCorrectContent) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 4, 6 }; + EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); + EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); +} + +TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 4, 6 }; + const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + EXPECT_THAT(lhs, Pointwise(m1, rhs)); + EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); + + // This type works as a tuple<const double&, const int&> can be + // implicitly cast to tuple<double, int>. + const Matcher<tuple<double, int> > m2 = IsHalfOf(); + EXPECT_THAT(lhs, Pointwise(m2, rhs)); + EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); +} + } // namespace gmock_matchers_test } // namespace testing diff --git a/testing/gmock/test/gmock-nice-strict_test.cc b/testing/gmock/test/gmock-nice-strict_test.cc index f6f278e..0e52450 100644 --- a/testing/gmock/test/gmock-nice-strict_test.cc +++ b/testing/gmock/test/gmock-nice-strict_test.cc @@ -137,6 +137,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; + const string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); nice_foo.DoThis(); @@ -147,6 +148,7 @@ TEST(NiceMockTest, InfoForUninterestingCall) { nice_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); + GMOCK_FLAG(verbose) = saved_flag; } #endif // GTEST_HAS_STREAM_REDIRECTION_ diff --git a/testing/gmock/test/gmock-port_test.cc b/testing/gmock/test/gmock-port_test.cc index 054313b..a84eb9ea 100644 --- a/testing/gmock/test/gmock-port_test.cc +++ b/testing/gmock/test/gmock-port_test.cc @@ -39,126 +39,5 @@ // NOTE: if this file is left without tests for some reason, put a dummy // test here to make references to symbols in the gtest library and avoid // 'undefined symbol' linker errors in gmock_main: -// -// TEST(DummyTest, Dummy) {} - -namespace testing { -namespace internal { -// Needed to avoid name collisions in gmock_all_test.cc. -namespace gmock_port_test { - -class Base { - public: - // Copy constructor and assignment operator do exactly what we need, so we - // use them. - Base() : member_(0) {} - explicit Base(int n) : member_(n) {} - virtual ~Base() {} - int member() { return member_; } - - private: - int member_; -}; - -class Derived : public Base { - public: - explicit Derived(int n) : Base(n) {} -}; - -TEST(ImplicitCastTest, ConvertsPointers) { - Derived derived(0); - EXPECT_TRUE(&derived == ::testing::internal::implicit_cast<Base*>(&derived)); -} - -TEST(ImplicitCastTest, CanUseInheritance) { - Derived derived(1); - Base base = ::testing::internal::implicit_cast<Base>(derived); - EXPECT_EQ(derived.member(), base.member()); -} - -class Castable { - public: - Castable(bool* converted) : converted_(converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseNonConstCastOperator) { - bool converted = false; - Castable castable(&converted); - Base base = ::testing::internal::implicit_cast<Base>(castable); - EXPECT_TRUE(converted); -} - -class ConstCastable { - public: - ConstCastable(bool* converted) : converted_(converted) {} - operator Base() const { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { - bool converted = false; - const ConstCastable const_castable(&converted); - Base base = ::testing::internal::implicit_cast<Base>(const_castable); - EXPECT_TRUE(converted); -} - -class ConstAndNonConstCastable { - public: - ConstAndNonConstCastable(bool* converted, bool* const_converted) - : converted_(converted), const_converted_(const_converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - operator Base() const { - *const_converted_ = true; - return Base(); - } - - private: - bool* converted_; - bool* const_converted_; -}; - -TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { - bool converted = false; - bool const_converted = false; - ConstAndNonConstCastable castable(&converted, &const_converted); - Base base = ::testing::internal::implicit_cast<Base>(castable); - EXPECT_TRUE(converted); - EXPECT_FALSE(const_converted); - - converted = false; - const_converted = false; - const ConstAndNonConstCastable const_castable(&converted, &const_converted); - base = ::testing::internal::implicit_cast<Base>(const_castable); - EXPECT_FALSE(converted); - EXPECT_TRUE(const_converted); -} - -class To { - public: - To(bool* converted) { *converted = true; } // NOLINT -}; - -TEST(ImplicitCastTest, CanUseImplicitConstructor) { - bool converted = false; - To to = ::testing::internal::implicit_cast<To>(&converted); - EXPECT_TRUE(converted); -} -} // namespace gmock_port_test -} // namespace internal -} // namespace testing +TEST(DummyTest, Dummy) {} diff --git a/testing/gmock/test/gmock-printers_test.cc b/testing/gmock/test/gmock-printers_test.cc deleted file mode 100644 index 92c8413..0000000 --- a/testing/gmock/test/gmock-printers_test.cc +++ /dev/null @@ -1,1118 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests the universal value printer. - -#include <gmock/gmock-printers.h> - -#include <ctype.h> -#include <limits.h> -#include <string.h> -#include <algorithm> -#include <deque> -#include <list> -#include <map> -#include <set> -#include <sstream> -#include <string> -#include <utility> -#include <vector> -#include <gmock/gmock-generated-matchers.h> -#include <gmock/gmock-matchers.h> -#include <gmock/internal/gmock-port.h> -#include <gtest/gtest.h> - -// hash_map and hash_set are available on Windows. -#if GTEST_OS_WINDOWS -#define GMOCK_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. -#include <hash_map> // NOLINT -#define GMOCK_HAS_HASH_SET_ 1 // Indicates that hash_set is available. -#include <hash_set> // NOLINT -#endif // GTEST_OS_WINDOWS - -// Some user-defined types for testing the universal value printer. - -// A user-defined unprintable class template in the global namespace. -template <typename T> -class UnprintableTemplateInGlobal { - public: - UnprintableTemplateInGlobal() : value_() {} - private: - T value_; -}; - -// A user-defined streamable type in the global namespace. -class StreamableInGlobal { - public: - virtual ~StreamableInGlobal() {} -}; - -inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { - os << "StreamableInGlobal"; -} - -namespace foo { - -// A user-defined unprintable type in a user namespace. -class UnprintableInFoo { - public: - UnprintableInFoo() : x_(0x12EF), y_(0xAB34), z_(0) {} - private: - testing::internal::Int32 x_; - testing::internal::Int32 y_; - double z_; -}; - -// A user-defined printable type in a user-chosen namespace. -struct PrintableViaPrintTo { - PrintableViaPrintTo() : value() {} - int value; -}; - -void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { - *os << "PrintableViaPrintTo: " << x.value; -} - -// A user-defined printable class template in a user-chosen namespace. -template <typename T> -class PrintableViaPrintToTemplate { - public: - explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template <typename T> -void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) { - *os << "PrintableViaPrintToTemplate: " << x.value(); -} - -// A user-defined streamable class template in a user namespace. -template <typename T> -class StreamableTemplateInFoo { - public: - StreamableTemplateInFoo() : value_() {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template <typename T> -inline ::std::ostream& operator<<(::std::ostream& os, - const StreamableTemplateInFoo<T>& x) { - return os << "StreamableTemplateInFoo: " << x.value(); -} - -} // namespace foo - -namespace testing { -namespace gmock_printers_test { - -using ::std::deque; -using ::std::list; -using ::std::make_pair; -using ::std::map; -using ::std::multimap; -using ::std::multiset; -using ::std::pair; -using ::std::set; -using ::std::tr1::make_tuple; -using ::std::tr1::tuple; -using ::std::vector; -using ::testing::ElementsAre; -using ::testing::PrintToString; -using ::testing::StartsWith; -using ::testing::internal::NativeArray; -using ::testing::internal::Strings; -using ::testing::internal::UniversalTersePrint; -using ::testing::internal::UniversalPrint; -using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -using ::testing::internal::UniversalPrinter; -using ::testing::internal::kReference; -using ::testing::internal::string; - -#if GTEST_OS_WINDOWS -// MSVC defines the following classes in the ::stdext namespace while -// gcc defines them in the :: namespace. Note that they are not part -// of the C++ standard. - -using ::stdext::hash_map; -using ::stdext::hash_set; -using ::stdext::hash_multimap; -using ::stdext::hash_multiset; - -#endif // GTEST_OS_WINDOWS - -// Prints a value to a string using the universal value printer. This -// is a helper for testing UniversalPrinter<T>::Print() for various types. -template <typename T> -string Print(const T& value) { - ::std::stringstream ss; - UniversalPrinter<T>::Print(value, &ss); - return ss.str(); -} - -// Prints a value passed by reference to a string, using the universal -// value printer. This is a helper for testing -// UniversalPrinter<T&>::Print() for various types. -template <typename T> -string PrintByRef(const T& value) { - ::std::stringstream ss; - UniversalPrinter<T&>::Print(value, &ss); - return ss.str(); -} - -// Tests printing various char types. - -// char. -TEST(PrintCharTest, PlainChar) { - EXPECT_EQ("'\\0'", Print('\0')); - EXPECT_EQ("'\\'' (39)", Print('\'')); - EXPECT_EQ("'\"' (34)", Print('"')); - EXPECT_EQ("'\\?' (63)", Print('\?')); - EXPECT_EQ("'\\\\' (92)", Print('\\')); - EXPECT_EQ("'\\a' (7)", Print('\a')); - EXPECT_EQ("'\\b' (8)", Print('\b')); - EXPECT_EQ("'\\f' (12)", Print('\f')); - EXPECT_EQ("'\\n' (10)", Print('\n')); - EXPECT_EQ("'\\r' (13)", Print('\r')); - EXPECT_EQ("'\\t' (9)", Print('\t')); - EXPECT_EQ("'\\v' (11)", Print('\v')); - EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); - EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); - EXPECT_EQ("' ' (32)", Print(' ')); - EXPECT_EQ("'a' (97)", Print('a')); -} - -// signed char. -TEST(PrintCharTest, SignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast<signed char>(-50))); -} - -// unsigned char. -TEST(PrintCharTest, UnsignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); - EXPECT_EQ("'b' (98)", - Print(static_cast<unsigned char>('b'))); -} - -// Tests printing other simple, built-in types. - -// bool. -TEST(PrintBuiltInTypeTest, Bool) { - EXPECT_EQ("false", Print(false)); - EXPECT_EQ("true", Print(true)); -} - -// wchar_t. -TEST(PrintBuiltInTypeTest, Wchar_t) { - EXPECT_EQ("L'\\0'", Print(L'\0')); - EXPECT_EQ("L'\\'' (39)", Print(L'\'')); - EXPECT_EQ("L'\"' (34)", Print(L'"')); - EXPECT_EQ("L'\\?' (63)", Print(L'\?')); - EXPECT_EQ("L'\\\\' (92)", Print(L'\\')); - EXPECT_EQ("L'\\a' (7)", Print(L'\a')); - EXPECT_EQ("L'\\b' (8)", Print(L'\b')); - EXPECT_EQ("L'\\f' (12)", Print(L'\f')); - EXPECT_EQ("L'\\n' (10)", Print(L'\n')); - EXPECT_EQ("L'\\r' (13)", Print(L'\r')); - EXPECT_EQ("L'\\t' (9)", Print(L'\t')); - EXPECT_EQ("L'\\v' (11)", Print(L'\v')); - EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); - EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); - EXPECT_EQ("L' ' (32)", Print(L' ')); - EXPECT_EQ("L'a' (97)", Print(L'a')); - EXPECT_EQ("L'\\x576' (1398)", Print(L'\x576')); - EXPECT_EQ("L'\\xC74D' (51021)", Print(L'\xC74D')); -} - -// Test that Int64 provides more storage than wchar_t. -TEST(PrintTypeSizeTest, Wchar_t) { - EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); -} - -// Various integer types. -TEST(PrintBuiltInTypeTest, Integer) { - EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8 - EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8 - EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 - EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 - EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 - EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 - EXPECT_EQ("18446744073709551615", - Print(static_cast<testing::internal::UInt64>(-1))); // uint64 - EXPECT_EQ("-9223372036854775808", - Print(static_cast<testing::internal::Int64>(1) << 63)); // int64 -} - -// Size types. -TEST(PrintBuiltInTypeTest, Size_t) { - EXPECT_EQ("1", Print(sizeof('a'))); // size_t. -#if !GTEST_OS_WINDOWS - // Windows has no ssize_t type. - EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS -} - -// Floating-points. -TEST(PrintBuiltInTypeTest, FloatingPoints) { - EXPECT_EQ("1.5", Print(1.5f)); // float - EXPECT_EQ("-2.5", Print(-2.5)); // double -} - -// Since ::std::stringstream::operator<<(const void *) formats the pointer -// output differently with different compilers, we have to create the expected -// output first and use it as our expectation. -static string PrintPointer(const void *p) { - ::std::stringstream expected_result_stream; - expected_result_stream << p; - return expected_result_stream.str(); -} - -// Tests printing C strings. - -// const char*. -TEST(PrintCStringTest, Const) { - const char* p = "World"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); -} - -// char*. -TEST(PrintCStringTest, NonConst) { - char p[] = "Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", - Print(static_cast<char*>(p))); -} - -// NULL C string. -TEST(PrintCStringTest, Null) { - const char* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that C strings are escaped properly. -TEST(PrintCStringTest, EscapesProperly) { - const char* p = "'\"\?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"\\?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", - Print(p)); -} - - - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - -// const wchar_t*. -TEST(PrintWideCStringTest, Const) { - const wchar_t* p = L"World"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); -} - -// wchar_t*. -TEST(PrintWideCStringTest, NonConst) { - wchar_t p[] = L"Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", - Print(static_cast<wchar_t*>(p))); -} - -// NULL wide C string. -TEST(PrintWideCStringTest, Null) { - const wchar_t* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that wide C strings are escaped properly. -TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t* p = L"'\"\?\\\a\b\f\n\r\t\v\xD3\x576\x8D3\xC74D a"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"'\\\"\\?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", - Print(p)); -} -#endif // native wchar_t - -// Tests printing pointers to other char types. - -// signed char*. -TEST(PrintCharPointerTest, SignedChar) { - signed char* p = reinterpret_cast<signed char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const signed char*. -TEST(PrintCharPointerTest, ConstSignedChar) { - signed char* p = reinterpret_cast<signed char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// unsigned char*. -TEST(PrintCharPointerTest, UnsignedChar) { - unsigned char* p = reinterpret_cast<unsigned char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const unsigned char*. -TEST(PrintCharPointerTest, ConstUnsignedChar) { - const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to simple, built-in types. - -// bool*. -TEST(PrintPointerToBuiltInTypeTest, Bool) { - bool* p = reinterpret_cast<bool*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// void*. -TEST(PrintPointerToBuiltInTypeTest, Void) { - void* p = reinterpret_cast<void*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const void*. -TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { - const void* p = reinterpret_cast<const void*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to pointers. -TEST(PrintPointerToPointerTest, IntPointerPointer) { - int** p = reinterpret_cast<int**>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing (non-member) function pointers. - -void MyFunction(int /* n */) {} - -TEST(PrintPointerTest, NonMemberFunctionPointer) { - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast<const void*>( - reinterpret_cast<internal::BiggestInt>(&MyFunction))), - Print(&MyFunction)); - int (*p)(bool) = NULL; // NOLINT - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing member variable pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. - -struct Foo { - public: - virtual ~Foo() {} - int MyMethod(char x) { return x + 1; } - virtual char MyVirtualMethod(int /* n */) { return 'a'; } - - int value; -}; - -TEST(PrintPointerTest, MemberVariablePointer) { - EXPECT_THAT(Print(&Foo::value), - StartsWith(Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT - EXPECT_THAT(Print(p), - StartsWith(Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing member function pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. -TEST(PrintPointerTest, MemberFunctionPointer) { - EXPECT_THAT(Print(&Foo::MyMethod), - StartsWith(Print(sizeof(&Foo::MyMethod)) + "-byte object ")); - EXPECT_THAT(Print(&Foo::MyVirtualMethod), - StartsWith(Print(sizeof((&Foo::MyVirtualMethod))) - + "-byte object ")); - int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_THAT(Print(p), - StartsWith(Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing C arrays. - -// The difference between this and Print() is that it ensures that the -// argument is a reference to an array. -template <typename T, size_t N> -string PrintArrayHelper(T (&a)[N]) { - return Print(a); -} - -// One-dimensional array. -TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); -} - -// Two-dimensional array. -TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; - EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); -} - -// Array of const elements. -TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; - EXPECT_EQ("{ false }", PrintArrayHelper(a)); -} - -// Char array. -TEST(PrintArrayTest, CharArray) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[3] = { 'H', '\0', 'i' }; - EXPECT_EQ("\"H\\0i\"", PrintArrayHelper(a)); -} - -// Const char array. -TEST(PrintArrayTest, ConstCharArray) { - const char a[4] = "\0Hi"; - EXPECT_EQ("\"\\0Hi\\0\"", PrintArrayHelper(a)); -} - -// Array of objects. -TEST(PrintArrayTest, ObjectArray) { - string a[3] = { "Hi", "Hello", "Ni hao" }; - EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); -} - -// Array with many elements. -TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", - PrintArrayHelper(a)); -} - -// Tests printing ::string and ::std::string. - -#if GTEST_HAS_GLOBAL_STRING -// ::string. -TEST(PrintStringTest, StringInGlobalNamespace) { - const char s[] = "'\"\?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_STRING - -// ::std::string. -TEST(PrintStringTest, StringInStdNamespace) { - const char s[] = "'\"\?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::std::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} - -// Tests printing ::wstring and ::std::wstring. - -#if GTEST_HAS_GLOBAL_WSTRING -// ::wstring. -TEST(PrintWideStringTest, StringInGlobalNamespace) { - const wchar_t s[] = L"'\"\?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -// ::std::wstring. -TEST(PrintWideStringTest, StringInStdNamespace) { - 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)); - EXPECT_EQ("L\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_STD_WSTRING - -// Tests printing types that support generic streaming (i.e. streaming -// to std::basic_ostream<Char, CharTraits> for any valid Char and -// CharTraits types). - -// Tests printing a non-template type that supports generic streaming. - -class AllowsGenericStreaming {}; - -template <typename Char, typename CharTraits> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreaming& /* a */) { - return os << "AllowsGenericStreaming"; -} - -TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { - AllowsGenericStreaming a; - EXPECT_EQ("AllowsGenericStreaming", Print(a)); -} - -// Tests printing a template type that supports generic streaming. - -template <typename T> -class AllowsGenericStreamingTemplate {}; - -template <typename Char, typename CharTraits, typename T> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreamingTemplate<T>& /* a */) { - return os << "AllowsGenericStreamingTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TemplateType) { - AllowsGenericStreamingTemplate<int> a; - EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); -} - -// Tests printing a type that supports generic streaming and can be -// implicitly converted to another printable type. - -template <typename T> -class AllowsGenericStreamingAndImplicitConversionTemplate { - public: - operator bool() const { return false; } -}; - -template <typename Char, typename CharTraits, typename T> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) { - return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { - AllowsGenericStreamingAndImplicitConversionTemplate<int> a; - EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); -} - -// Tests printing STL containers. - -TEST(PrintStlContainerTest, EmptyDeque) { - deque<char> empty; - EXPECT_EQ("{}", Print(empty)); -} - -TEST(PrintStlContainerTest, NonEmptyDeque) { - deque<int> non_empty; - non_empty.push_back(1); - non_empty.push_back(3); - EXPECT_EQ("{ 1, 3 }", Print(non_empty)); -} - -#if GMOCK_HAS_HASH_MAP_ - -TEST(PrintStlContainerTest, OneElementHashMap) { - hash_map<int, char> map1; - map1[1] = 'a'; - EXPECT_EQ("{ (1, 'a' (97)) }", Print(map1)); -} - -TEST(PrintStlContainerTest, HashMultiMap) { - hash_multimap<int, bool> map1; - map1.insert(make_pair(5, true)); - map1.insert(make_pair(5, false)); - - // Elements of hash_multimap can be printed in any order. - const string result = Print(map1); - EXPECT_TRUE(result == "{ (5, true), (5, false) }" || - result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; -} - -#endif // GMOCK_HAS_HASH_MAP_ - -#if GMOCK_HAS_HASH_SET_ - -TEST(PrintStlContainerTest, HashSet) { - hash_set<string> set1; - set1.insert("hello"); - EXPECT_EQ("{ \"hello\" }", Print(set1)); -} - -TEST(PrintStlContainerTest, HashMultiSet) { - const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; - hash_multiset<int> set1(a, a + kSize); - - // Elements of hash_multiset can be printed in any order. - const string result = Print(set1); - const string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. - - // Verifies the result matches the expected pattern; also extracts - // the numbers in the result. - ASSERT_EQ(expected_pattern.length(), result.length()); - std::vector<int> numbers; - for (size_t i = 0; i != result.length(); i++) { - if (expected_pattern[i] == 'd') { - ASSERT_TRUE(isdigit(result[i]) != 0); - numbers.push_back(result[i] - '0'); - } else { - EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " - << result; - } - } - - // Makes sure the result contains the right numbers. - std::sort(numbers.begin(), numbers.end()); - std::sort(a, a + kSize); - EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); -} - -#endif // GMOCK_HAS_HASH_SET_ - -TEST(PrintStlContainerTest, List) { - const char* a[] = { - "hello", - "world" - }; - const list<string> strings(a, a + 2); - EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); -} - -TEST(PrintStlContainerTest, Map) { - map<int, bool> map1; - map1[1] = true; - map1[5] = false; - map1[3] = true; - EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); -} - -TEST(PrintStlContainerTest, MultiMap) { - multimap<bool, int> map1; - map1.insert(make_pair(true, 0)); - map1.insert(make_pair(true, 1)); - map1.insert(make_pair(false, 2)); - EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); -} - -TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; - set<unsigned int> set1(a, a + 3); - EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, MultiSet) { - const int a[] = { 1, 1, 2, 5, 1 }; - multiset<int> set1(a, a + 5); - EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, Pair) { - pair<const bool, int> p(true, 5); - EXPECT_EQ("(true, 5)", Print(p)); -} - -TEST(PrintStlContainerTest, Vector) { - vector<int> v; - v.push_back(1); - v.push_back(2); - EXPECT_EQ("{ 1, 2 }", Print(v)); -} - -TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; - 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, " - "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); -} - -TEST(PrintStlContainerTest, NestedContainer) { - const int a1[] = { 1, 2 }; - const int a2[] = { 3, 4, 5 }; - const list<int> l1(a1, a1 + 2); - const list<int> l2(a2, a2 + 3); - - vector<list<int> > v; - v.push_back(l1); - v.push_back(l2); - EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); -} - -TEST(PrintStlContainerTest, OneDimensionalNativeArray) { - const int a[3] = { 1, 2, 3 }; - NativeArray<int> b(a, 3, kReference); - EXPECT_EQ("{ 1, 2, 3 }", Print(b)); -} - -TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { - const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; - NativeArray<int[3]> b(a, 2, kReference); - EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); -} - -// Tests printing tuples. - -// Tuples of various arities. -TEST(PrintTupleTest, VariousSizes) { - tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - tuple<int> t1(5); - EXPECT_EQ("(5)", Print(t1)); - - tuple<char, bool> t2('a', true); - EXPECT_EQ("('a' (97), true)", Print(t2)); - - tuple<bool, int, int> t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - tuple<bool, int, int, int> t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - tuple<bool, int, int, int, bool, int, int> t7(false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - tuple<bool, int, int, int, bool, int, int, bool> t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - tuple<bool, int, int, int, bool, int, int, bool, int> t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - tuple<bool, char, short, testing::internal::Int32, // NOLINT - testing::internal::Int64, float, double, const char*, void*, string> - t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, NULL, "10"); - EXPECT_EQ("(false, 'a' (97), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintTupleTest, NestedTuple) { - tuple<tuple<int, bool>, char> nested(make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97))", Print(nested)); -} - -// Tests printing user-defined unprintable types. - -// Unprintable types in the global namespace. -TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal<bool>())); -} - -// Unprintable types in a user namespace. -TEST(PrintUnprintableTypeTest, InUserNamespace) { - EXPECT_EQ("16-byte object <EF12 0000 34AB 0000 0000 0000 0000 0000>", - Print(::foo::UnprintableInFoo())); -} - -// Unprintable types are that too big to be printed completely. - -struct Big { - Big() { memset(array, 0, sizeof(array)); } - char array[257]; -}; - -TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 ... 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 00>", - Print(Big())); -} - -// Tests printing user-defined streamable types. - -// Streamable types in the global namespace. -TEST(PrintStreamableTypeTest, InGlobalNamespace) { - EXPECT_EQ("StreamableInGlobal", - Print(StreamableInGlobal())); -} - -// Printable template types in a user namespace. -TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { - EXPECT_EQ("StreamableTemplateInFoo: 0", - Print(::foo::StreamableTemplateInFoo<int>())); -} - -// Tests printing user-defined types that have a PrintTo() function. -TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - Print(::foo::PrintableViaPrintTo())); -} - -// Tests printing user-defined class template that have a PrintTo() function. -TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { - EXPECT_EQ("PrintableViaPrintToTemplate: 5", - Print(::foo::PrintableViaPrintToTemplate<int>(5))); -} - -#if GMOCK_HAS_PROTOBUF_ - -// Tests printing a protocol message. -TEST(PrintProtocolMessageTest, PrintsShortDebugString) { - testing::internal::TestMessage msg; - msg.set_member("yes"); - EXPECT_EQ("<member:\"yes\">", Print(msg)); -} - -// Tests printing a short proto2 message. -TEST(PrintProto2MessageTest, PrintsShortDebugStringWhenItIsShort) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<int_field:\\s*2\\s+string_field:\\s*\"hello\">"); -} - -// Tests printing a long proto2 message. -TEST(PrintProto2MessageTest, PrintsDebugStringWhenItIsLong) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - msg.add_names("peter"); - msg.add_names("paul"); - msg.add_names("mary"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<\n" - "int_field:\\s*2\n" - "string_field:\\s*\"hello\"\n" - "names:\\s*\"peter\"\n" - "names:\\s*\"paul\"\n" - "names:\\s*\"mary\"\n" - ">"); -} - -#endif // GMOCK_HAS_PROTOBUF_ - -// Tests that the universal printer prints both the address and the -// value of a reference. -TEST(PrintReferenceTest, PrintsAddressAndValue) { - int n = 5; - EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; - EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", - PrintByRef(a)); - - const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "<EF12 0000 34AB 0000 0000 0000 0000 0000>", - PrintByRef(x)); -} - -// Tests that the universal printer prints a function pointer passed by -// reference. -TEST(PrintReferenceTest, HandlesFunctionPointer) { - void (*fp)(int n) = &MyFunction; - const string fp_pointer_string = - PrintPointer(reinterpret_cast<const void*>(&fp)); - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - const string fp_string = PrintPointer(reinterpret_cast<const void*>( - reinterpret_cast<internal::BiggestInt>(fp))); - EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, - PrintByRef(fp)); -} - -// Tests that the universal printer prints a member function pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { - int (Foo::*p)(char ch) = &Foo::MyMethod; - EXPECT_THAT(PrintByRef(p), - StartsWith("@" + PrintPointer(reinterpret_cast<const void*>(&p)) - + " " + Print(sizeof(p)) + "-byte object ")); - - char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_THAT(PrintByRef(p2), - StartsWith("@" + PrintPointer(reinterpret_cast<const void*>(&p2)) - + " " + Print(sizeof(p2)) + "-byte object ")); -} - -// Tests that the universal printer prints a member variable pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT - EXPECT_THAT(PrintByRef(p), - StartsWith("@" + PrintPointer(&p) - + " " + Print(sizeof(p)) + "-byte object ")); -} - -TEST(PrintToStringTest, WorksForScalar) { - EXPECT_EQ("123", PrintToString(123)); -} - -TEST(PrintToStringTest, WorksForPointerToConstChar) { - const char* p = "hello"; - EXPECT_EQ("\"hello\"", PrintToString(p)); -} - -TEST(PrintToStringTest, WorksForPointerToNonConstChar) { - char s[] = "hello"; - char* p = s; - EXPECT_EQ("\"hello\"", PrintToString(p)); -} - -TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3 }", PrintToString(n)); -} - -TEST(UniversalTersePrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalTersePrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalTersePrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalTersePrint(s1, &ss1); - EXPECT_EQ("\"abc\"", ss1.str()); - - char* s2 = const_cast<char*>(s1); - ::std::stringstream ss2; - UniversalTersePrint(s2, &ss2); - EXPECT_EQ("\"abc\"", ss2.str()); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalTersePrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalPrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalPrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalPrint(s1, &ss1); - EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", string(ss1.str())); - - char* s2 = const_cast<char*>(s1); - ::std::stringstream ss2; - UniversalPrint(s2, &ss2); - EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", string(ss2.str())); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalPrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsEmptyTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple()), - ElementsAre()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsOneTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple(1)), - ElementsAre("1")); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTwoTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple(1, 'a')), - ElementsAre("1", "'a' (97)")); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) { - const int n = 1; - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings( - tuple<const int&, const char*>(n, "a")), - ElementsAre("1", "\"a\"")); -} - -} // namespace gmock_printers_test -} // namespace testing diff --git a/testing/gmock/test/gmock-spec-builders_test.cc b/testing/gmock/test/gmock-spec-builders_test.cc index e5fc2ec..ff30f02 100644 --- a/testing/gmock/test/gmock-spec-builders_test.cc +++ b/testing/gmock/test/gmock-spec-builders_test.cc @@ -1783,6 +1783,25 @@ class MockC { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC); }; +class VerboseFlagPreservingFixture : public testing::Test { + protected: + // The code needs to work when both ::string and ::std::string are defined + // and the flag is implemented as a testing::internal::String. In this + // case, without the call to c_str(), the compiler will complain that it + // cannot figure out what overload of string constructor to use. + // TODO(vladl@google.com): Use internal::string instead of String for + // string flags in Google Test. + VerboseFlagPreservingFixture() + : saved_verbose_flag_(GMOCK_FLAG(verbose).c_str()) {} + + ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; } + + private: + const string saved_verbose_flag_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); +}; + #if GTEST_HAS_STREAM_REDIRECTION_ // Tests that an uninteresting mock function call generates a warning @@ -1842,7 +1861,7 @@ TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) { // Tests how the --gmock_verbose flag affects Google Mock's output. -class GMockVerboseFlagTest : public testing::Test { +class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { public: // Verifies that the given Google Mock output is correct. (When // should_print is true, the output should match the given regex and @@ -1982,22 +2001,9 @@ class LogTestHelper { GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); }; -class GMockLogTest : public ::testing::Test { +class GMockLogTest : public VerboseFlagPreservingFixture { protected: - virtual void SetUp() { - // The code needs to work when both ::string and ::std::string are - // defined and the flag is implemented as a - // testing::internal::String. In this case, without the call to - // c_str(), the compiler will complain that it cannot figure out - // whether the String flag should be converted to a ::string or an - // ::std::string before being assigned to original_verbose_. - original_verbose_ = GMOCK_FLAG(verbose).c_str(); - } - - virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; } - LogTestHelper helper_; - string original_verbose_; }; TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { @@ -2358,9 +2364,23 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { // action or as a default action without causing a dead lock. It // verifies that the action is not performed inside the critical // section. +TEST(SynchronizationTest, CanCallMockMethodInAction) { + MockA a; + MockC c; + ON_CALL(a, DoA(_)) + .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, + &MockC::NonVoidMethod))); + EXPECT_CALL(a, DoA(1)); + EXPECT_CALL(a, DoA(1)) + .WillOnce(Invoke(&a, &MockA::DoA)) + .RetiresOnSaturation(); + EXPECT_CALL(c, NonVoidMethod()); -void Helper(MockC* c) { - c->NonVoidMethod(); + a.DoA(1); + // This will match the second EXPECT_CALL() and trigger another a.DoA(1), + // which will in turn match the first EXPECT_CALL() and trigger a call to + // c.NonVoidMethod() that was specified by the ON_CALL() since the first + // EXPECT_CALL() did not specify an action. } } // namespace diff --git a/testing/gmock/test/gmock_all_test.cc b/testing/gmock/test/gmock_all_test.cc index 7361259..691aac8 100644 --- a/testing/gmock/test/gmock_all_test.cc +++ b/testing/gmock/test/gmock_all_test.cc @@ -44,6 +44,5 @@ #include "test/gmock-more-actions_test.cc" #include "test/gmock-nice-strict_test.cc" #include "test/gmock-port_test.cc" -#include "test/gmock-printers_test.cc" #include "test/gmock-spec-builders_test.cc" #include "test/gmock_test.cc" diff --git a/testing/gmock/test/gmock_output_test.py b/testing/gmock/test/gmock_output_test.py index 614a58f..eced8a8 100755 --- a/testing/gmock/test/gmock_output_test.py +++ b/testing/gmock/test/gmock_output_test.py @@ -32,7 +32,7 @@ """Tests the text output of Google C++ Mocking Framework. SYNOPSIS - gmock_output_test.py --gmock_build_dir=BUILD/DIR --gengolden + gmock_output_test.py --build_dir=BUILD/DIR --gengolden # where BUILD/DIR contains the built gmock_output_test_ file. gmock_output_test.py --gengolden gmock_output_test.py diff --git a/testing/gmock/test/gmock_output_test_golden.txt b/testing/gmock/test/gmock_output_test_golden.txt index 382dc8c..a7ff563 100644 --- a/testing/gmock/test/gmock_output_test_golden.txt +++ b/testing/gmock/test/gmock_output_test_golden.txt @@ -151,7 +151,7 @@ FILE:#: pre-requisite #1 [ RUN ] GMockOutputTest.UnsatisfiedWith FILE:#: Failure Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))... - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Expected: to be called once Actual: never called - unsatisfied and active [ FAILED ] GMockOutputTest.UnsatisfiedWith @@ -190,7 +190,7 @@ Unexpected mock function call - returning default value. Google Mock tried the following 1 expectation, but it didn't match: FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))... - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Actual: don't match Expected: to be called once Actual: never called - unsatisfied and active @@ -206,7 +206,7 @@ Google Mock tried the following 1 expectation, but it didn't match: FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))... Expected arg #0: is >= 2 Actual: 1 - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Actual: don't match Expected: to be called once Actual: never called - unsatisfied and active diff --git a/testing/gmock/test/gmock_test_utils.py b/testing/gmock/test/gmock_test_utils.py index fa896a4..ac3d67a 100755 --- a/testing/gmock/test/gmock_test_utils.py +++ b/testing/gmock/test/gmock_test_utils.py @@ -51,62 +51,10 @@ sys.path.append(GTEST_TESTS_UTIL_DIR) import gtest_test_utils # pylint: disable-msg=C6204 -# Initially maps a flag to its default value. After -# _ParseAndStripGMockFlags() is called, maps a flag to its actual -# value. -_flag_map = {'gmock_source_dir': os.path.dirname(sys.argv[0]), - 'gmock_build_dir': os.path.dirname(sys.argv[0])} -_gmock_flags_are_parsed = False - - -def _ParseAndStripGMockFlags(argv): - """Parses and strips Google Test flags from argv. This is idempotent.""" - - global _gmock_flags_are_parsed - if _gmock_flags_are_parsed: - return - - _gmock_flags_are_parsed = True - for flag in _flag_map: - # The environment variable overrides the default value. - if flag.upper() in os.environ: - _flag_map[flag] = os.environ[flag.upper()] - - # The command line flag overrides the environment variable. - i = 1 # Skips the program name. - while i < len(argv): - prefix = '--' + flag + '=' - if argv[i].startswith(prefix): - _flag_map[flag] = argv[i][len(prefix):] - del argv[i] - break - else: - # We don't increment i in case we just found a --gmock_* flag - # and removed it from argv. - i += 1 - - -def GetFlag(flag): - """Returns the value of the given flag.""" - - # In case GetFlag() is called before Main(), we always call - # _ParseAndStripGMockFlags() here to make sure the --gmock_* flags - # are parsed. - _ParseAndStripGMockFlags(sys.argv) - - return _flag_map[flag] - - def GetSourceDir(): """Returns the absolute path of the directory where the .py files are.""" - return os.path.abspath(GetFlag('gmock_source_dir')) - - -def GetBuildDir(): - """Returns the absolute path of the directory where the test binaries are.""" - - return os.path.abspath(GetFlag('gmock_build_dir')) + return gtest_test_utils.GetSourceDir() def GetTestExecutablePath(executable_name): @@ -122,7 +70,7 @@ def GetTestExecutablePath(executable_name): The absolute path of the test binary. """ - return gtest_test_utils.GetTestExecutablePath(executable_name, GetBuildDir()) + return gtest_test_utils.GetTestExecutablePath(executable_name) def GetExitStatus(exit_code): @@ -160,8 +108,4 @@ TestCase = gtest_test_utils.TestCase def Main(): """Runs the unit test.""" - # We must call _ParseAndStripGMockFlags() before calling - # gtest_test_utils.Main(). Otherwise unittest.main it calls will be - # confused by the --gmock_* flags. - _ParseAndStripGMockFlags(sys.argv) gtest_test_utils.Main() |