blob: 2a43caa93554b7e99dba022b603b0d8cf3f7fe4b [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the internal utilities.
35
36#include <gmock/internal/gmock-internal-utils.h>
37#include <map>
38#include <string>
39#include <sstream>
40#include <vector>
41#include <gmock/gmock.h>
42#include <gmock/internal/gmock-port.h>
43#include <gtest/gtest.h>
44#include <gtest/gtest-spi.h>
45
46namespace testing {
47namespace internal {
48
49namespace {
50
51using ::std::tr1::tuple;
52
53// Tests that CompileAssertTypesEqual compiles when the type arguments are
54// equal.
55TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
56 CompileAssertTypesEqual<void, void>();
57 CompileAssertTypesEqual<int*, int*>();
58}
59
60// Tests that RemoveReference does not affect non-reference types.
61TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
62 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
63 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
64}
65
66// Tests that RemoveReference removes reference from reference types.
67TEST(RemoveReferenceTest, RemovesReference) {
68 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
69 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
70}
71
72// Tests GMOCK_REMOVE_REFERENCE.
73
74template <typename T1, typename T2>
75void TestGMockRemoveReference() {
76 CompileAssertTypesEqual<T1, GMOCK_REMOVE_REFERENCE(T2)>();
77}
78
79TEST(RemoveReferenceTest, MacroVersion) {
80 TestGMockRemoveReference<int, int>();
81 TestGMockRemoveReference<const char, const char&>();
82}
83
84
85// Tests that RemoveConst does not affect non-const types.
86TEST(RemoveConstTest, DoesNotAffectNonConstType) {
87 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
88 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
89}
90
91// Tests that RemoveConst removes const from const types.
92TEST(RemoveConstTest, RemovesConst) {
93 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
94}
95
96// Tests GMOCK_REMOVE_CONST.
97
98template <typename T1, typename T2>
99void TestGMockRemoveConst() {
100 CompileAssertTypesEqual<T1, GMOCK_REMOVE_CONST(T2)>();
101}
102
103TEST(RemoveConstTest, MacroVersion) {
104 TestGMockRemoveConst<int, int>();
105 TestGMockRemoveConst<double&, double&>();
106 TestGMockRemoveConst<char, const char>();
107}
108
109// Tests that AddReference does not affect reference types.
110TEST(AddReferenceTest, DoesNotAffectReferenceType) {
111 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
112 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
113}
114
115// Tests that AddReference adds reference to non-reference types.
116TEST(AddReferenceTest, AddsReference) {
117 CompileAssertTypesEqual<int&, AddReference<int>::type>();
118 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
119}
120
121// Tests GMOCK_ADD_REFERENCE.
122
123template <typename T1, typename T2>
124void TestGMockAddReference() {
125 CompileAssertTypesEqual<T1, GMOCK_ADD_REFERENCE(T2)>();
126}
127
128TEST(AddReferenceTest, MacroVersion) {
129 TestGMockAddReference<int&, int>();
130 TestGMockAddReference<const char&, const char&>();
131}
132
133// Tests GMOCK_REFERENCE_TO_CONST.
134
135template <typename T1, typename T2>
136void TestGMockReferenceToConst() {
137 CompileAssertTypesEqual<T1, GMOCK_REFERENCE_TO_CONST(T2)>();
138}
139
140TEST(GMockReferenceToConstTest, Works) {
141 TestGMockReferenceToConst<const char&, char>();
142 TestGMockReferenceToConst<const int&, const int>();
143 TestGMockReferenceToConst<const double&, double>();
144 TestGMockReferenceToConst<const string&, const string&>();
145}
146
147TEST(PointeeOfTest, WorksForSmartPointers) {
148 CompileAssertTypesEqual<const char,
149 PointeeOf<internal::linked_ptr<const char> >::type>();
150}
151
152TEST(PointeeOfTest, WorksForRawPointers) {
153 CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
154 CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
155 CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
156}
157
158TEST(GetRawPointerTest, WorksForSmartPointers) {
159 const char* const raw_p4 = new const char('a'); // NOLINT
160 const internal::linked_ptr<const char> p4(raw_p4);
161 EXPECT_EQ(raw_p4, GetRawPointer(p4));
162}
163
164TEST(GetRawPointerTest, WorksForRawPointers) {
165 int* p = NULL;
166 EXPECT_EQ(NULL, GetRawPointer(p));
167 int n = 1;
168 EXPECT_EQ(&n, GetRawPointer(&n));
169}
170
171class Base {};
172class Derived : public Base {};
173
174// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
175TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
176 GMOCK_COMPILE_ASSERT((ImplicitlyConvertible<int, int>::value), const_true);
177 GMOCK_COMPILE_ASSERT((!ImplicitlyConvertible<void*, int*>::value), const_false);
178}
179
180// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
181// be implicitly converted to T2.
182TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
183 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
184 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
185 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
186 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
187 EXPECT_TRUE((ImplicitlyConvertible<Derived&, const Base&>::value));
188 EXPECT_TRUE((ImplicitlyConvertible<const Base, Base>::value));
189}
190
191// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
192// cannot be implicitly converted to T2.
193TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
194 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
195 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
196 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
197 EXPECT_FALSE((ImplicitlyConvertible<Base&, Derived&>::value));
198}
199
200// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
201TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
202 GMOCK_COMPILE_ASSERT(IsAProtocolMessage<ProtocolMessage>::value, const_true);
203 GMOCK_COMPILE_ASSERT(!IsAProtocolMessage<int>::value, const_false);
204}
205
206// Tests that IsAProtocolMessage<T>::value is true when T is
207// ProtocolMessage or a sub-class of it.
208TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
209 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
210#if GMOCK_HAS_PROTOBUF_
211 EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value);
212#endif // GMOCK_HAS_PROTOBUF_
213}
214
215// Tests that IsAProtocolMessage<T>::value is false when T is neither
216// ProtocolMessage nor a sub-class of it.
217TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
218 EXPECT_FALSE(IsAProtocolMessage<int>::value);
219 EXPECT_FALSE(IsAProtocolMessage<const Base>::value);
220}
221
222// Tests IsContainerTest.
223
224class NonContainer {};
225
226TEST(IsContainerTestTest, WorksForNonContainer) {
227 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
228 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
229 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
230}
231
232TEST(IsContainerTestTest, WorksForContainer) {
233 EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool> >(0)));
234 EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::map<int, double> >(0)));
235}
236
237// Tests the TupleMatches() template function.
238
239TEST(TupleMatchesTest, WorksForSize0) {
240 tuple<> matchers;
241 tuple<> values;
242
243 EXPECT_TRUE(TupleMatches(matchers, values));
244}
245
246TEST(TupleMatchesTest, WorksForSize1) {
247 tuple<Matcher<int> > matchers(Eq(1));
248 tuple<int> values1(1),
249 values2(2);
250
251 EXPECT_TRUE(TupleMatches(matchers, values1));
252 EXPECT_FALSE(TupleMatches(matchers, values2));
253}
254
255TEST(TupleMatchesTest, WorksForSize2) {
256 tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
257 tuple<int, char> values1(1, 'a'),
258 values2(1, 'b'),
259 values3(2, 'a'),
260 values4(2, 'b');
261
262 EXPECT_TRUE(TupleMatches(matchers, values1));
263 EXPECT_FALSE(TupleMatches(matchers, values2));
264 EXPECT_FALSE(TupleMatches(matchers, values3));
265 EXPECT_FALSE(TupleMatches(matchers, values4));
266}
267
268TEST(TupleMatchesTest, WorksForSize5) {
269 tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT
270 Matcher<string> >
271 matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
272 tuple<int, char, bool, long, string> // NOLINT
273 values1(1, 'a', true, 2L, "hi"),
274 values2(1, 'a', true, 2L, "hello"),
275 values3(2, 'a', true, 2L, "hi");
276
277 EXPECT_TRUE(TupleMatches(matchers, values1));
278 EXPECT_FALSE(TupleMatches(matchers, values2));
279 EXPECT_FALSE(TupleMatches(matchers, values3));
280}
281
282// Tests that Assert(true, ...) succeeds.
283TEST(AssertTest, SucceedsOnTrue) {
284 Assert(true, __FILE__, __LINE__, "This should succeed.");
285 Assert(true, __FILE__, __LINE__); // This should succeed too.
286}
287
288#ifdef GTEST_HAS_DEATH_TEST
289
290// Tests that Assert(false, ...) generates a fatal failure.
291TEST(AssertTest, FailsFatallyOnFalse) {
292 EXPECT_DEATH({ // NOLINT
293 Assert(false, __FILE__, __LINE__, "This should fail.");
294 }, "");
295
296 EXPECT_DEATH({ // NOLINT
297 Assert(false, __FILE__, __LINE__);
298 }, "");
299}
300
301#endif // GTEST_HAS_DEATH_TEST
302
303// Tests that Expect(true, ...) succeeds.
304TEST(ExpectTest, SucceedsOnTrue) {
305 Expect(true, __FILE__, __LINE__, "This should succeed.");
306 Expect(true, __FILE__, __LINE__); // This should succeed too.
307}
308
309// Tests that Expect(false, ...) generates a non-fatal failure.
310TEST(ExpectTest, FailsNonfatallyOnFalse) {
311 EXPECT_NONFATAL_FAILURE({ // NOLINT
312 Expect(false, __FILE__, __LINE__, "This should fail.");
313 }, "This should fail");
314
315 EXPECT_NONFATAL_FAILURE({ // NOLINT
316 Expect(false, __FILE__, __LINE__);
317 }, "Expectation failed");
318}
319
320// TODO(wan@google.com): find a way to re-enable these tests.
321#if 0
322
323// Tests the Log() function.
324
325// Verifies that Log() behaves correctly for the given verbosity level
326// and log severity.
327void TestLogWithSeverity(const string& verbosity, LogSeverity severity,
328 bool should_print) {
329 const string old_flag = GMOCK_FLAG(verbose);
330 GMOCK_FLAG(verbose) = verbosity;
331 CaptureTestStdout();
332 Log(severity, "Test log.\n", 0);
333 if (should_print) {
334 EXPECT_PRED2(RE::FullMatch,
335 GetCapturedTestStdout(),
336 severity == WARNING ?
337 "\nGMOCK WARNING:\nTest log\\.\nStack trace:\n[\\s\\S]*" :
338 "\nTest log\\.\nStack trace:\n[\\s\\S]*");
339 } else {
340 EXPECT_EQ("", GetCapturedTestStdout());
341 }
342 GMOCK_FLAG(verbose) = old_flag;
343}
344
345// Tests that when the stack_frames_to_skip parameter is negative,
346// Log() doesn't include the stack trace in the output.
347TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
348 GMOCK_FLAG(verbose) = kInfoVerbosity;
349 CaptureTestStdout();
350 Log(INFO, "Test log.\n", -1);
351 EXPECT_EQ("\nTest log.\n", GetCapturedTestStdout());
352}
353
354// Tests that in opt mode, a positive stack_frames_to_skip argument is
355// treated as 0.
356TEST(LogTest, NoSkippingStackFrameInOptMode) {
357 CaptureTestStdout();
358 Log(WARNING, "Test log.\n", 100);
359 const string log = GetCapturedTestStdout();
360#ifdef NDEBUG
361 // In opt mode, no stack frame should be skipped.
362 EXPECT_THAT(log, ContainsRegex("\nGMOCK WARNING:\n"
363 "Test log\\.\n"
364 "Stack trace:\n"
365 ".+"));
366#else
367 // In dbg mode, the stack frames should be skipped.
368 EXPECT_EQ("\nGMOCK WARNING:\n"
369 "Test log.\n"
370 "Stack trace:\n", log);
371#endif // NDEBUG
372}
373
374// Tests that all logs are printed when the value of the
375// --gmock_verbose flag is "info".
376TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
377 TestLogWithSeverity(kInfoVerbosity, INFO, true);
378 TestLogWithSeverity(kInfoVerbosity, WARNING, true);
379}
380
381// Tests that only warnings are printed when the value of the
382// --gmock_verbose flag is "warning".
383TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
384 TestLogWithSeverity(kWarningVerbosity, INFO, false);
385 TestLogWithSeverity(kWarningVerbosity, WARNING, true);
386}
387
388// Tests that no logs are printed when the value of the
389// --gmock_verbose flag is "error".
390TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
391 TestLogWithSeverity(kErrorVerbosity, INFO, false);
392 TestLogWithSeverity(kErrorVerbosity, WARNING, false);
393}
394
395// Tests that only warnings are printed when the value of the
396// --gmock_verbose flag is invalid.
397TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
398 TestLogWithSeverity("invalid", INFO, false);
399 TestLogWithSeverity("invalid", WARNING, true);
400}
401
402#endif // 0
403
404TEST(TypeTraitsTest, true_type) {
405 EXPECT_TRUE(true_type::value);
406}
407
408TEST(TypeTraitsTest, false_type) {
409 EXPECT_FALSE(false_type::value);
410}
411
412TEST(TypeTraitsTest, is_reference) {
413 EXPECT_FALSE(is_reference<int>::value);
414 EXPECT_FALSE(is_reference<char*>::value);
415 EXPECT_TRUE(is_reference<const int&>::value);
416}
417
418TEST(TypeTraitsTest, is_pointer) {
419 EXPECT_FALSE(is_pointer<int>::value);
420 EXPECT_FALSE(is_pointer<char&>::value);
421 EXPECT_TRUE(is_pointer<const int*>::value);
422}
423
424TEST(TypeTraitsTest, type_equals) {
425 EXPECT_FALSE((type_equals<int, const int>::value));
426 EXPECT_FALSE((type_equals<int, int&>::value));
427 EXPECT_FALSE((type_equals<int, double>::value));
428 EXPECT_TRUE((type_equals<char, char>::value));
429}
430
431TEST(TypeTraitsTest, remove_reference) {
432 EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
433 EXPECT_TRUE((type_equals<const int,
434 remove_reference<const int&>::type>::value));
435 EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
436 EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
437}
438
439// TODO(wan@google.com): find a way to re-enable these tests.
440#if 0
441
442// Verifies that Log() behaves correctly for the given verbosity level
443// and log severity.
444string GrabOutput(void(*logger)(), const char* verbosity) {
445 const string saved_flag = GMOCK_FLAG(verbose);
446 GMOCK_FLAG(verbose) = verbosity;
447 CaptureTestStdout();
448 logger();
449 GMOCK_FLAG(verbose) = saved_flag;
450 return GetCapturedTestStdout();
451}
452
453class DummyMock {
454 public:
455 MOCK_METHOD0(TestMethod, void());
456 MOCK_METHOD1(TestMethodArg, void(int dummy));
457};
458
459void ExpectCallLogger() {
460 DummyMock mock;
461 EXPECT_CALL(mock, TestMethod());
462 mock.TestMethod();
463};
464
465// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
466TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
467 EXPECT_THAT(GrabOutput(ExpectCallLogger, kInfoVerbosity),
468 HasSubstr("EXPECT_CALL(mock, TestMethod())"));
469}
470
471// Verifies that EXPECT_CALL doesn't log
472// if the --gmock_verbose flag is set to "warning".
473TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
474 EXPECT_EQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity));
475}
476
477// Verifies that EXPECT_CALL doesn't log
478// if the --gmock_verbose flag is set to "error".
479TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
480 EXPECT_EQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity));
481}
482
483void OnCallLogger() {
484 DummyMock mock;
485 ON_CALL(mock, TestMethod());
486};
487
488// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
489TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
490 EXPECT_THAT(GrabOutput(OnCallLogger, kInfoVerbosity),
491 HasSubstr("ON_CALL(mock, TestMethod())"));
492}
493
494// Verifies that ON_CALL doesn't log
495// if the --gmock_verbose flag is set to "warning".
496TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
497 EXPECT_EQ("", GrabOutput(OnCallLogger, kWarningVerbosity));
498}
499
500// Verifies that ON_CALL doesn't log if
501// the --gmock_verbose flag is set to "error".
502TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
503 EXPECT_EQ("", GrabOutput(OnCallLogger, kErrorVerbosity));
504}
505
506void OnCallAnyArgumentLogger() {
507 DummyMock mock;
508 ON_CALL(mock, TestMethodArg(_));
509}
510
511// Verifies that ON_CALL prints provided _ argument.
512TEST(OnCallTest, LogsAnythingArgument) {
513 EXPECT_THAT(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity),
514 HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
515}
516
517#endif // 0
518
519} // namespace
520} // namespace internal
521} // namespace testing