blob: 46db38d400bb01b60af1672cf26376fea5e3ce06 [file] [log] [blame]
shiqian4b6829f2008-07-03 22:38:12 +00001// Copyright 2005, 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// Tests for Google Test itself. This verifies that the basic constructs of
33// Google Test work.
34
zhanyong.wan2620c792010-09-14 05:35:59 +000035#include "gtest/gtest.h"
zhanyong.wan93d13a82010-02-25 01:09:07 +000036#include <vector>
vladlosev12878402010-10-22 01:33:11 +000037#include <ostream>
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000038
39// Verifies that the command line flag variables can be accessed
40// in code once <gtest/gtest.h> has been #included.
41// Do not move it after other #includes.
42TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
43 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
44 || testing::GTEST_FLAG(break_on_failure)
45 || testing::GTEST_FLAG(catch_exceptions)
46 || testing::GTEST_FLAG(color) != "unknown"
47 || testing::GTEST_FLAG(filter) != "unknown"
48 || testing::GTEST_FLAG(list_tests)
49 || testing::GTEST_FLAG(output) != "unknown"
50 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000051 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000052 || testing::GTEST_FLAG(repeat) > 0
53 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000054 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000055 || testing::GTEST_FLAG(stack_trace_depth) > 0
zhanyong.wanc95489e2010-08-19 22:16:00 +000056 || testing::GTEST_FLAG(stream_result_to) != "unknown"
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000057 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000058 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
59}
60
zhanyong.wan2620c792010-09-14 05:35:59 +000061#include "gtest/gtest-spi.h"
shiqian4b6829f2008-07-03 22:38:12 +000062
63// Indicates that this translation unit is part of Google Test's
64// implementation. It must come before gtest-internal-inl.h is
65// included, or there will be a compiler error. This trick is to
66// prevent a user from accidentally including gtest-internal-inl.h in
67// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000068#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000069#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000070#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000071
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +000072#include <limits.h> // For INT_MAX.
shiqian4b6829f2008-07-03 22:38:12 +000073#include <stdlib.h>
zhanyong.wan98efcc42009-04-28 00:28:09 +000074#include <time.h>
shiqian4b6829f2008-07-03 22:38:12 +000075
zhanyong.wan98efcc42009-04-28 00:28:09 +000076#include <map>
zhanyong.wan98efcc42009-04-28 00:28:09 +000077
shiqian4b6829f2008-07-03 22:38:12 +000078namespace testing {
79namespace internal {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000080
zhanyong.wanf6d087b2009-09-30 20:23:50 +000081// Provides access to otherwise private parts of the TestEventListeners class
zhanyong.wanf39160b2009-09-04 18:30:25 +000082// that are needed to test it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +000083class TestEventListenersAccessor {
zhanyong.wanf39160b2009-09-04 18:30:25 +000084 public:
zhanyong.wanf6d087b2009-09-30 20:23:50 +000085 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
zhanyong.wanfff03342009-09-24 21:15:59 +000086 return listeners->repeater();
87 }
zhanyong.wanf39160b2009-09-04 18:30:25 +000088
zhanyong.wanf6d087b2009-09-30 20:23:50 +000089 static void SetDefaultResultPrinter(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +000090 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000091 listeners->SetDefaultResultPrinter(listener);
92 }
zhanyong.wanf6d087b2009-09-30 20:23:50 +000093 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +000094 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000095 listeners->SetDefaultXmlGenerator(listener);
96 }
97
zhanyong.wanf6d087b2009-09-30 20:23:50 +000098 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000099 return listeners.EventForwardingEnabled();
100 }
101
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000102 static void SuppressEventForwarding(TestEventListeners* listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000103 listeners->SuppressEventForwarding();
104 }
105};
106
shiqian4b6829f2008-07-03 22:38:12 +0000107} // namespace internal
108} // namespace testing
109
shiqian760af5c2008-08-06 21:43:15 +0000110using testing::AssertionFailure;
111using testing::AssertionResult;
112using testing::AssertionSuccess;
113using testing::DoubleLE;
zhanyong.wanfff03342009-09-24 21:15:59 +0000114using testing::EmptyTestEventListener;
shiqian760af5c2008-08-06 21:43:15 +0000115using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000116using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000117using testing::GTEST_FLAG(break_on_failure);
118using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000119using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000120using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000121using testing::GTEST_FLAG(filter);
122using testing::GTEST_FLAG(list_tests);
123using testing::GTEST_FLAG(output);
124using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000125using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000126using testing::GTEST_FLAG(repeat);
127using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000128using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000129using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanc95489e2010-08-19 22:16:00 +0000130using testing::GTEST_FLAG(stream_result_to);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000131using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000132using testing::IsNotSubstring;
133using testing::IsSubstring;
134using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000135using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000136using testing::StaticAssertTypeEq;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000137using testing::Test;
zhanyong.wanfff03342009-09-24 21:15:59 +0000138using testing::TestCase;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000139using testing::TestEventListeners;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000140using testing::TestPartResult;
141using testing::TestPartResultArray;
zhanyong.wanfff03342009-09-24 21:15:59 +0000142using testing::TestProperty;
143using testing::TestResult;
shiqian4b6829f2008-07-03 22:38:12 +0000144using testing::UnitTest;
vladlosevba015a92009-11-17 22:43:15 +0000145using testing::kMaxStackTraceDepth;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000146using testing::internal::AddReference;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000147using testing::internal::AlwaysFalse;
148using testing::internal::AlwaysTrue;
shiqian4b6829f2008-07-03 22:38:12 +0000149using testing::internal::AppendUserMessage;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000150using testing::internal::ArrayAwareFind;
151using testing::internal::ArrayEq;
vladloseve006e682008-08-25 23:11:54 +0000152using testing::internal::CodePointToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000153using testing::internal::CompileAssertTypesEqual;
154using testing::internal::CopyArray;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000155using testing::internal::CountIf;
shiqian4b6829f2008-07-03 22:38:12 +0000156using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000157using testing::internal::FloatingPoint;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000158using testing::internal::ForEach;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000159using testing::internal::FormatTimeInMillisAsSeconds;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000160using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000161using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000162using testing::internal::GetElementOr;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000163using testing::internal::GetNextRandomSeed;
164using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000165using testing::internal::GetTestTypeId;
166using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000167using testing::internal::GetUnitTestImpl;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000168using testing::internal::ImplicitlyConvertible;
shiqian4b6829f2008-07-03 22:38:12 +0000169using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000170using testing::internal::Int32FromEnvOrDie;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000171using testing::internal::IsAProtocolMessage;
172using testing::internal::IsContainer;
173using testing::internal::IsContainerTest;
174using testing::internal::IsNotContainer;
175using testing::internal::NativeArray;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000176using testing::internal::ParseInt32Flag;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000177using testing::internal::RemoveConst;
178using testing::internal::RemoveReference;
zhanyong.wan905074c2009-02-09 18:05:21 +0000179using testing::internal::ShouldRunTestOnShard;
180using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000181using testing::internal::ShouldUseColor;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000182using testing::internal::Shuffle;
183using testing::internal::ShuffleRange;
zhanyong.wan9748de02010-06-08 22:51:46 +0000184using testing::internal::SkipPrefix;
shiqian4b6829f2008-07-03 22:38:12 +0000185using testing::internal::StreamableToString;
186using testing::internal::String;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000187using testing::internal::TestEventListenersAccessor;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000188using testing::internal::TestResultAccessor;
zhanyong.wan85f555a2009-09-21 19:42:03 +0000189using testing::internal::UInt32;
vladloseve006e682008-08-25 23:11:54 +0000190using testing::internal::WideStringToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000191using testing::internal::kCopy;
zhanyong.wanfff03342009-09-24 21:15:59 +0000192using testing::internal::kMaxRandomSeed;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000193using testing::internal::kReference;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000194using testing::internal::kTestTypeIdInGoogleTest;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000195using testing::internal::scoped_ptr;
shiqian4b6829f2008-07-03 22:38:12 +0000196
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +0000197#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +0000198using testing::internal::CaptureStdout;
199using testing::internal::GetCapturedStdout;
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +0000200#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +0000201
zhanyong.wanf6fb5322010-03-04 22:15:53 +0000202#if GTEST_IS_THREADSAFE
203using testing::internal::ThreadWithParam;
204#endif
205
zhanyong.wan93d13a82010-02-25 01:09:07 +0000206class TestingVector : public std::vector<int> {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000207};
208
209::std::ostream& operator<<(::std::ostream& os,
210 const TestingVector& vector) {
211 os << "{ ";
zhanyong.wan93d13a82010-02-25 01:09:07 +0000212 for (size_t i = 0; i < vector.size(); i++) {
213 os << vector[i] << " ";
zhanyong.wanf19450f2009-09-30 23:46:28 +0000214 }
215 os << "}";
216 return os;
217}
218
shiqian4b6829f2008-07-03 22:38:12 +0000219// This line tests that we can define tests in an unnamed namespace.
220namespace {
221
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000222TEST(GetRandomSeedFromFlagTest, HandlesZero) {
223 const int seed = GetRandomSeedFromFlag(0);
224 EXPECT_LE(1, seed);
225 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
226}
227
228TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
229 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
230 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
231 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
232 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
233 GetRandomSeedFromFlag(kMaxRandomSeed));
234}
235
236TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
237 const int seed1 = GetRandomSeedFromFlag(-1);
238 EXPECT_LE(1, seed1);
239 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
240
241 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
242 EXPECT_LE(1, seed2);
243 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
244}
245
246TEST(GetNextRandomSeedTest, WorksForValidInput) {
247 EXPECT_EQ(2, GetNextRandomSeed(1));
248 EXPECT_EQ(3, GetNextRandomSeed(2));
249 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
250 GetNextRandomSeed(kMaxRandomSeed - 1));
251 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
252
253 // We deliberately don't test GetNextRandomSeed() with invalid
254 // inputs, as that requires death tests, which are expensive. This
255 // is fine as GetNextRandomSeed() is internal and has a
256 // straightforward definition.
257}
258
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000259static void ClearCurrentTestPartResults() {
260 TestResultAccessor::ClearTestPartResults(
261 GetUnitTestImpl()->current_test_result());
262}
263
shiqianfe6a9a42008-11-24 20:13:22 +0000264// Tests GetTypeId.
265
266TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
267 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
268 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
269}
270
271class SubClassOfTest : public Test {};
272class AnotherSubClassOfTest : public Test {};
273
274TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
275 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
276 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
277 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
278 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
279 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
280 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
281}
282
283// Verifies that GetTestTypeId() returns the same value, no matter it
284// is called from inside Google Test or outside of it.
285TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
286 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
287}
288
shiqianf0e809a2008-09-26 16:08:30 +0000289// Tests FormatTimeInMillisAsSeconds().
290
291TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000292 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
shiqianf0e809a2008-09-26 16:08:30 +0000293}
294
295TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000296 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
297 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
298 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
299 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
300 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
shiqianf0e809a2008-09-26 16:08:30 +0000301}
302
303TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000304 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
305 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
306 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
307 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
308 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
shiqianf0e809a2008-09-26 16:08:30 +0000309}
310
vladlosev5147b452010-03-17 18:22:59 +0000311#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +0000312
zhanyong.wan733a54a2011-02-22 22:08:59 +0000313# ifdef __BORLANDC__
zhanyong.wan98efcc42009-04-28 00:28:09 +0000314// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +0000315# pragma option push -w-ccc -w-rch
316# endif
zhanyong.wan98efcc42009-04-28 00:28:09 +0000317
shiqiane44602e2008-10-11 07:20:02 +0000318// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000319// pointer literal.
320TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000321 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
322 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000323 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
324 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
zhanyong.wan733a54a2011-02-22 22:08:59 +0000325
326# ifndef __BORLANDC__
327
zhanyong.wan98efcc42009-04-28 00:28:09 +0000328 // Some compilers may fail to detect some null pointer literals;
329 // as long as users of the framework don't use such literals, this
330 // is harmless.
331 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
zhanyong.wan733a54a2011-02-22 22:08:59 +0000332
333# endif
shiqian4b6829f2008-07-03 22:38:12 +0000334}
335
shiqiane44602e2008-10-11 07:20:02 +0000336// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
shiqian4b6829f2008-07-03 22:38:12 +0000337// pointer literal.
338TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000339 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
340 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
341 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
342 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
shiqian4b6829f2008-07-03 22:38:12 +0000343}
344
zhanyong.wan733a54a2011-02-22 22:08:59 +0000345# ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +0000346// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan733a54a2011-02-22 22:08:59 +0000347# pragma option pop
348# endif
zhanyong.wan98efcc42009-04-28 00:28:09 +0000349
vladlosev5147b452010-03-17 18:22:59 +0000350#endif // GTEST_CAN_COMPARE_NULL
vladloseve006e682008-08-25 23:11:54 +0000351//
352// Tests CodePointToUtf8().
shiqian4b6829f2008-07-03 22:38:12 +0000353
354// Tests that the NUL character L'\0' is encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000355TEST(CodePointToUtf8Test, CanEncodeNul) {
356 char buffer[32];
357 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000358}
359
360// Tests that ASCII characters are encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000361TEST(CodePointToUtf8Test, CanEncodeAscii) {
362 char buffer[32];
363 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
364 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
365 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
366 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000367}
368
369// Tests that Unicode code-points that have 8 to 11 bits are encoded
370// as 110xxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000371TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
372 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000373 // 000 1101 0011 => 110-00011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000374 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000375
376 // 101 0111 0110 => 110-10101 10-110110
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000377 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
378 // in wide strings and wide chars. In order to accomodate them, we have to
379 // introduce such character constants as integers.
380 EXPECT_STREQ("\xD5\xB6",
381 CodePointToUtf8(static_cast<wchar_t>(0x576), buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000382}
383
384// Tests that Unicode code-points that have 12 to 16 bits are encoded
385// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000386TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
387 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000388 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000389 EXPECT_STREQ("\xE0\xA3\x93",
390 CodePointToUtf8(static_cast<wchar_t>(0x8D3), buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000391
392 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000393 EXPECT_STREQ("\xEC\x9D\x8D",
394 CodePointToUtf8(static_cast<wchar_t>(0xC74D), buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000395}
396
zhanyong.wan4cd62602009-02-23 23:21:55 +0000397#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000398// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000399// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000400// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000401
402// Tests that Unicode code-points that have 17 to 21 bits are encoded
403// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000404TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
405 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000406 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000407 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000408
vladloseve006e682008-08-25 23:11:54 +0000409 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
410 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
411
412 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
413 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000414}
415
416// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000417TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
418 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000419 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
vladloseve006e682008-08-25 23:11:54 +0000420 CodePointToUtf8(L'\x1234ABCD', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000421}
422
zhanyong.wan4cd62602009-02-23 23:21:55 +0000423#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000424
425// Tests WideStringToUtf8().
426
427// Tests that the NUL character L'\0' is encoded correctly.
428TEST(WideStringToUtf8Test, CanEncodeNul) {
429 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
430 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
431}
432
433// Tests that ASCII strings are encoded correctly.
434TEST(WideStringToUtf8Test, CanEncodeAscii) {
435 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
436 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
437 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
438 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
439}
440
441// Tests that Unicode code-points that have 8 to 11 bits are encoded
442// as 110xxxxx 10xxxxxx.
443TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
444 // 000 1101 0011 => 110-00011 10-010011
445 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
446 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
447
448 // 101 0111 0110 => 110-10101 10-110110
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000449 const wchar_t s[] = { 0x576, '\0' };
450 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
451 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000452}
453
454// Tests that Unicode code-points that have 12 to 16 bits are encoded
455// as 1110xxxx 10xxxxxx 10xxxxxx.
456TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
457 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000458 const wchar_t s1[] = { 0x8D3, '\0' };
459 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
460 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000461
462 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000463 const wchar_t s2[] = { 0xC74D, '\0' };
464 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
465 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000466}
467
468// Tests that the conversion stops when the function encounters \0 character.
469TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
470 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
471}
472
473// Tests that the conversion stops when the function reaches the limit
474// specified by the 'length' parameter.
475TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
476 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
477}
478
zhanyong.wan4cd62602009-02-23 23:21:55 +0000479#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000480// Tests that Unicode code-points that have 17 to 21 bits are encoded
481// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
482// on the systems using UTF-16 encoding.
483TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
484 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
485 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
486 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
487
488 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
489 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
490 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
491}
492
493// Tests that encoding an invalid code-point generates the expected result.
494TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
495 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
496 WideStringToUtf8(L"\xABCDFF", -1).c_str());
497}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000498#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000499// Tests that surrogate pairs are encoded correctly on the systems using
500// UTF-16 encoding in the wide strings.
501TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000502 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
503 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000504}
505
506// Tests that encoding an invalid UTF-16 surrogate pair
507// generates the expected result.
508TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
509 // Leading surrogate is at the end of the string.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000510 const wchar_t s1[] = { 0xD800, '\0' };
511 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000512 // Leading surrogate is not followed by the trailing surrogate.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000513 const wchar_t s2[] = { 0xD800, 'M', '\0' };
514 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000515 // Trailing surrogate appearas without a leading surrogate.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000516 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
517 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000518}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000519#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000520
521// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000522#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000523TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000524 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
vladloseve006e682008-08-25 23:11:54 +0000525 EXPECT_STREQ(
526 "\xF4\x88\x98\xB4"
527 "\xEC\x9D\x8D"
528 "\n"
529 "\xD5\xB6"
530 "\xE0\xA3\x93"
531 "\xF4\x88\x98\xB4",
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000532 WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000533}
534#else
535TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000536 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
vladloseve006e682008-08-25 23:11:54 +0000537 EXPECT_STREQ(
538 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000539 WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000540}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000541#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000542
zhanyong.wan85f555a2009-09-21 19:42:03 +0000543// Tests the Random class.
544
545TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
546 testing::internal::Random random(42);
547 EXPECT_DEATH_IF_SUPPORTED(
548 random.Generate(0),
549 "Cannot generate a number in the range \\[0, 0\\)");
550 EXPECT_DEATH_IF_SUPPORTED(
551 random.Generate(testing::internal::Random::kMaxRange + 1),
552 "Generation of a number in \\[0, 2147483649\\) was requested, "
553 "but this can only generate numbers in \\[0, 2147483648\\)");
554}
555
556TEST(RandomTest, GeneratesNumbersWithinRange) {
557 const UInt32 kRange = 10000;
558 testing::internal::Random random(12345);
559 for (int i = 0; i < 10; i++) {
560 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
561 }
562
563 testing::internal::Random random2(testing::internal::Random::kMaxRange);
564 for (int i = 0; i < 10; i++) {
565 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
566 }
567}
568
569TEST(RandomTest, RepeatsWhenReseeded) {
570 const int kSeed = 123;
571 const int kArraySize = 10;
572 const UInt32 kRange = 10000;
573 UInt32 values[kArraySize];
574
575 testing::internal::Random random(kSeed);
576 for (int i = 0; i < kArraySize; i++) {
577 values[i] = random.Generate(kRange);
578 }
579
580 random.Reseed(kSeed);
581 for (int i = 0; i < kArraySize; i++) {
582 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
583 }
584}
585
zhanyong.wan93d13a82010-02-25 01:09:07 +0000586// Tests STL container utilities.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000587
zhanyong.wan93d13a82010-02-25 01:09:07 +0000588// Tests CountIf().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000589
zhanyong.wan93d13a82010-02-25 01:09:07 +0000590static bool IsPositive(int n) { return n > 0; }
591
592TEST(ContainerUtilityTest, CountIf) {
593 std::vector<int> v;
594 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
595
596 v.push_back(-1);
597 v.push_back(0);
598 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
599
600 v.push_back(2);
601 v.push_back(-10);
602 v.push_back(10);
603 EXPECT_EQ(2, CountIf(v, IsPositive));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000604}
605
zhanyong.wan93d13a82010-02-25 01:09:07 +0000606// Tests ForEach().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000607
zhanyong.wan93d13a82010-02-25 01:09:07 +0000608static int g_sum = 0;
609static void Accumulate(int n) { g_sum += n; }
610
611TEST(ContainerUtilityTest, ForEach) {
612 std::vector<int> v;
613 g_sum = 0;
614 ForEach(v, Accumulate);
615 EXPECT_EQ(0, g_sum); // Works for an empty container;
616
617 g_sum = 0;
618 v.push_back(1);
619 ForEach(v, Accumulate);
620 EXPECT_EQ(1, g_sum); // Works for a container with one element.
621
622 g_sum = 0;
623 v.push_back(20);
624 v.push_back(300);
625 ForEach(v, Accumulate);
626 EXPECT_EQ(321, g_sum);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000627}
shiqian4b6829f2008-07-03 22:38:12 +0000628
zhanyong.wan93d13a82010-02-25 01:09:07 +0000629// Tests GetElementOr().
630TEST(ContainerUtilityTest, GetElementOr) {
631 std::vector<char> a;
632 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000633
zhanyong.wan93d13a82010-02-25 01:09:07 +0000634 a.push_back('a');
635 a.push_back('b');
636 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
637 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
638 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
639 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000640}
641
zhanyong.wan93d13a82010-02-25 01:09:07 +0000642TEST(ContainerUtilityDeathTest, ShuffleRange) {
643 std::vector<int> a;
644 a.push_back(0);
645 a.push_back(1);
646 a.push_back(2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000647 testing::internal::Random random(1);
648
649 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000650 ShuffleRange(&random, -1, 1, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000651 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
652 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000653 ShuffleRange(&random, 4, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000654 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
655 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000656 ShuffleRange(&random, 3, 2, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000657 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
658 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000659 ShuffleRange(&random, 3, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000660 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
661}
662
663class VectorShuffleTest : public Test {
664 protected:
665 static const int kVectorSize = 20;
666
667 VectorShuffleTest() : random_(1) {
668 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000669 vector_.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000670 }
671 }
672
673 static bool VectorIsCorrupt(const TestingVector& vector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000674 if (kVectorSize != static_cast<int>(vector.size())) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000675 return true;
676 }
677
678 bool found_in_vector[kVectorSize] = { false };
zhanyong.wan93d13a82010-02-25 01:09:07 +0000679 for (size_t i = 0; i < vector.size(); i++) {
680 const int e = vector[i];
zhanyong.wanf19450f2009-09-30 23:46:28 +0000681 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
682 return true;
683 }
684 found_in_vector[e] = true;
685 }
686
687 // Vector size is correct, elements' range is correct, no
688 // duplicate elements. Therefore no corruption has occurred.
689 return false;
690 }
691
692 static bool VectorIsNotCorrupt(const TestingVector& vector) {
693 return !VectorIsCorrupt(vector);
694 }
695
696 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
697 for (int i = begin; i < end; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000698 if (i != vector[i]) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000699 return true;
700 }
701 }
702 return false;
703 }
704
705 static bool RangeIsUnshuffled(
706 const TestingVector& vector, int begin, int end) {
707 return !RangeIsShuffled(vector, begin, end);
708 }
709
710 static bool VectorIsShuffled(const TestingVector& vector) {
zhanyong.wanb03ca472010-02-25 22:15:27 +0000711 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
zhanyong.wanf19450f2009-09-30 23:46:28 +0000712 }
713
714 static bool VectorIsUnshuffled(const TestingVector& vector) {
715 return !VectorIsShuffled(vector);
716 }
717
718 testing::internal::Random random_;
719 TestingVector vector_;
720}; // class VectorShuffleTest
721
722const int VectorShuffleTest::kVectorSize;
723
724TEST_F(VectorShuffleTest, HandlesEmptyRange) {
725 // Tests an empty range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000726 ShuffleRange(&random_, 0, 0, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000727 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
728 ASSERT_PRED1(VectorIsUnshuffled, vector_);
729
730 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000731 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000732 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
733 ASSERT_PRED1(VectorIsUnshuffled, vector_);
734
735 // ...at the end...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000736 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000737 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
738 ASSERT_PRED1(VectorIsUnshuffled, vector_);
739
740 // ...and past the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000741 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000742 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
743 ASSERT_PRED1(VectorIsUnshuffled, vector_);
744}
745
746TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
747 // Tests a size one range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000748 ShuffleRange(&random_, 0, 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000749 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
750 ASSERT_PRED1(VectorIsUnshuffled, vector_);
751
752 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000753 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000754 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
755 ASSERT_PRED1(VectorIsUnshuffled, vector_);
756
757 // ...and at the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000758 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000759 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
760 ASSERT_PRED1(VectorIsUnshuffled, vector_);
761}
762
763// Because we use our own random number generator and a fixed seed,
764// we can guarantee that the following "random" tests will succeed.
765
766TEST_F(VectorShuffleTest, ShufflesEntireVector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000767 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000768 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
769 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
770
771 // Tests the first and last elements in particular to ensure that
772 // there are no off-by-one problems in our shuffle algorithm.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000773 EXPECT_NE(0, vector_[0]);
774 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000775}
776
777TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
778 const int kRangeSize = kVectorSize/2;
779
zhanyong.wan93d13a82010-02-25 01:09:07 +0000780 ShuffleRange(&random_, 0, kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000781
782 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
783 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
784 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
785}
786
787TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
788 const int kRangeSize = kVectorSize / 2;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000789 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000790
791 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
792 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
793 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
794}
795
796TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
797 int kRangeSize = kVectorSize/3;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000798 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000799
800 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
801 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
802 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
803 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
804}
805
806TEST_F(VectorShuffleTest, ShufflesRepeatably) {
807 TestingVector vector2;
808 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000809 vector2.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000810 }
811
812 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000813 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000814 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000815 Shuffle(&random_, &vector2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000816
817 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
818 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
819
820 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000821 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
zhanyong.wanf19450f2009-09-30 23:46:28 +0000822 }
823}
824
zhanyong.wanf39160b2009-09-04 18:30:25 +0000825// Tests the size of the AssertHelper class.
shiqian4b6829f2008-07-03 22:38:12 +0000826
zhanyong.wanf39160b2009-09-04 18:30:25 +0000827TEST(AssertHelperTest, AssertHelperIsSmall) {
zhanyong.wan89be5762009-09-01 18:53:56 +0000828 // To avoid breaking clients that use lots of assertions in one
zhanyong.wanf39160b2009-09-04 18:30:25 +0000829 // function, we cannot grow the size of AssertHelper.
830 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
zhanyong.wan89be5762009-09-01 18:53:56 +0000831}
832
zhanyong.wanf39160b2009-09-04 18:30:25 +0000833// Tests the String class.
834
shiqian4b6829f2008-07-03 22:38:12 +0000835// Tests String's constructors.
836TEST(StringTest, Constructors) {
837 // Default ctor.
838 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +0000839 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
840 // pointers with NULL isn't supported on all platforms.
zhanyong.wan89be5762009-09-01 18:53:56 +0000841 EXPECT_EQ(0U, s1.length());
shiqiandd4a17b2008-07-31 18:34:08 +0000842 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +0000843
844 // Implicitly constructs from a C-string.
845 String s2 = "Hi";
zhanyong.wan89be5762009-09-01 18:53:56 +0000846 EXPECT_EQ(2U, s2.length());
shiqian4b6829f2008-07-03 22:38:12 +0000847 EXPECT_STREQ("Hi", s2.c_str());
848
849 // Constructs from a C-string and a length.
850 String s3("hello", 3);
zhanyong.wan89be5762009-09-01 18:53:56 +0000851 EXPECT_EQ(3U, s3.length());
shiqian4b6829f2008-07-03 22:38:12 +0000852 EXPECT_STREQ("hel", s3.c_str());
853
zhanyong.wan89be5762009-09-01 18:53:56 +0000854 // The empty String should be created when String is constructed with
855 // a NULL pointer and length 0.
856 EXPECT_EQ(0U, String(NULL, 0).length());
857 EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
858
859 // Constructs a String that contains '\0'.
860 String s4("a\0bcd", 4);
861 EXPECT_EQ(4U, s4.length());
862 EXPECT_EQ('a', s4.c_str()[0]);
863 EXPECT_EQ('\0', s4.c_str()[1]);
864 EXPECT_EQ('b', s4.c_str()[2]);
865 EXPECT_EQ('c', s4.c_str()[3]);
866
867 // Copy ctor where the source is NULL.
868 const String null_str;
869 String s5 = null_str;
870 EXPECT_TRUE(s5.c_str() == NULL);
871
872 // Copy ctor where the source isn't NULL.
873 String s6 = s3;
874 EXPECT_EQ(3U, s6.length());
875 EXPECT_STREQ("hel", s6.c_str());
876
877 // Copy ctor where the source contains '\0'.
878 String s7 = s4;
879 EXPECT_EQ(4U, s7.length());
880 EXPECT_EQ('a', s7.c_str()[0]);
881 EXPECT_EQ('\0', s7.c_str()[1]);
882 EXPECT_EQ('b', s7.c_str()[2]);
883 EXPECT_EQ('c', s7.c_str()[3]);
shiqian4b6829f2008-07-03 22:38:12 +0000884}
885
vladlosevf179f4e2008-11-26 20:48:45 +0000886TEST(StringTest, ConvertsFromStdString) {
887 // An empty std::string.
888 const std::string src1("");
889 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000890 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000891 EXPECT_STREQ("", dest1.c_str());
892
893 // A normal std::string.
894 const std::string src2("Hi");
895 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000896 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000897 EXPECT_STREQ("Hi", dest2.c_str());
898
899 // An std::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000900 const char src3[] = "a\0b";
vladlosevf179f4e2008-11-26 20:48:45 +0000901 const String dest3 = std::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000902 EXPECT_EQ(sizeof(src3), dest3.length());
903 EXPECT_EQ('a', dest3.c_str()[0]);
904 EXPECT_EQ('\0', dest3.c_str()[1]);
905 EXPECT_EQ('b', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000906}
907
908TEST(StringTest, ConvertsToStdString) {
909 // An empty String.
910 const String src1("");
911 const std::string dest1 = src1;
912 EXPECT_EQ("", dest1);
913
914 // A normal String.
915 const String src2("Hi");
916 const std::string dest2 = src2;
917 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000918
919 // A String containing a '\0'.
920 const String src3("x\0y", 3);
921 const std::string dest3 = src3;
922 EXPECT_EQ(std::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000923}
924
vladlosevf179f4e2008-11-26 20:48:45 +0000925#if GTEST_HAS_GLOBAL_STRING
926
927TEST(StringTest, ConvertsFromGlobalString) {
928 // An empty ::string.
929 const ::string src1("");
930 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000931 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000932 EXPECT_STREQ("", dest1.c_str());
933
934 // A normal ::string.
935 const ::string src2("Hi");
936 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000937 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000938 EXPECT_STREQ("Hi", dest2.c_str());
939
940 // An ::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000941 const char src3[] = "x\0y";
vladlosevf179f4e2008-11-26 20:48:45 +0000942 const String dest3 = ::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000943 EXPECT_EQ(sizeof(src3), dest3.length());
944 EXPECT_EQ('x', dest3.c_str()[0]);
945 EXPECT_EQ('\0', dest3.c_str()[1]);
946 EXPECT_EQ('y', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000947}
948
949TEST(StringTest, ConvertsToGlobalString) {
950 // An empty String.
951 const String src1("");
952 const ::string dest1 = src1;
953 EXPECT_EQ("", dest1);
954
955 // A normal String.
956 const String src2("Hi");
957 const ::string dest2 = src2;
958 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000959
960 const String src3("x\0y", 3);
961 const ::string dest3 = src3;
962 EXPECT_EQ(::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000963}
964
965#endif // GTEST_HAS_GLOBAL_STRING
966
shiqian4b6829f2008-07-03 22:38:12 +0000967// Tests String::ShowCStringQuoted().
968TEST(StringTest, ShowCStringQuoted) {
969 EXPECT_STREQ("(null)",
970 String::ShowCStringQuoted(NULL).c_str());
971 EXPECT_STREQ("\"\"",
972 String::ShowCStringQuoted("").c_str());
973 EXPECT_STREQ("\"foo\"",
974 String::ShowCStringQuoted("foo").c_str());
975}
976
zhanyong.wan89be5762009-09-01 18:53:56 +0000977// Tests String::empty().
978TEST(StringTest, Empty) {
979 EXPECT_TRUE(String("").empty());
980 EXPECT_FALSE(String().empty());
981 EXPECT_FALSE(String(NULL).empty());
982 EXPECT_FALSE(String("a").empty());
983 EXPECT_FALSE(String("\0", 1).empty());
984}
985
986// Tests String::Compare().
987TEST(StringTest, Compare) {
988 // NULL vs NULL.
989 EXPECT_EQ(0, String().Compare(String()));
990
991 // NULL vs non-NULL.
992 EXPECT_EQ(-1, String().Compare(String("")));
993
994 // Non-NULL vs NULL.
995 EXPECT_EQ(1, String("").Compare(String()));
996
997 // The following covers non-NULL vs non-NULL.
998
999 // "" vs "".
1000 EXPECT_EQ(0, String("").Compare(String("")));
1001
1002 // "" vs non-"".
1003 EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
1004 EXPECT_EQ(-1, String("").Compare(" "));
1005
1006 // Non-"" vs "".
1007 EXPECT_EQ(1, String("a").Compare(String("")));
1008
1009 // The following covers non-"" vs non-"".
1010
1011 // Same length and equal.
1012 EXPECT_EQ(0, String("a").Compare(String("a")));
1013
1014 // Same length and different.
1015 EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
1016 EXPECT_EQ(1, String("b").Compare(String("a")));
1017
1018 // Different lengths.
1019 EXPECT_EQ(-1, String("a").Compare(String("ab")));
1020 EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
1021 EXPECT_EQ(1, String("abc").Compare(String("aacd")));
1022}
1023
shiqian4b6829f2008-07-03 22:38:12 +00001024// Tests String::operator==().
1025TEST(StringTest, Equals) {
1026 const String null(NULL);
1027 EXPECT_TRUE(null == NULL); // NOLINT
1028 EXPECT_FALSE(null == ""); // NOLINT
1029 EXPECT_FALSE(null == "bar"); // NOLINT
1030
1031 const String empty("");
1032 EXPECT_FALSE(empty == NULL); // NOLINT
1033 EXPECT_TRUE(empty == ""); // NOLINT
1034 EXPECT_FALSE(empty == "bar"); // NOLINT
1035
1036 const String foo("foo");
1037 EXPECT_FALSE(foo == NULL); // NOLINT
1038 EXPECT_FALSE(foo == ""); // NOLINT
1039 EXPECT_FALSE(foo == "bar"); // NOLINT
1040 EXPECT_TRUE(foo == "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001041
1042 const String bar("x\0y", 3);
1043 EXPECT_FALSE(bar == "x");
shiqian4b6829f2008-07-03 22:38:12 +00001044}
1045
1046// Tests String::operator!=().
1047TEST(StringTest, NotEquals) {
1048 const String null(NULL);
1049 EXPECT_FALSE(null != NULL); // NOLINT
1050 EXPECT_TRUE(null != ""); // NOLINT
1051 EXPECT_TRUE(null != "bar"); // NOLINT
1052
1053 const String empty("");
1054 EXPECT_TRUE(empty != NULL); // NOLINT
1055 EXPECT_FALSE(empty != ""); // NOLINT
1056 EXPECT_TRUE(empty != "bar"); // NOLINT
1057
1058 const String foo("foo");
1059 EXPECT_TRUE(foo != NULL); // NOLINT
1060 EXPECT_TRUE(foo != ""); // NOLINT
1061 EXPECT_TRUE(foo != "bar"); // NOLINT
1062 EXPECT_FALSE(foo != "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001063
1064 const String bar("x\0y", 3);
1065 EXPECT_TRUE(bar != "x");
1066}
1067
1068// Tests String::length().
1069TEST(StringTest, Length) {
1070 EXPECT_EQ(0U, String().length());
1071 EXPECT_EQ(0U, String("").length());
1072 EXPECT_EQ(2U, String("ab").length());
1073 EXPECT_EQ(3U, String("a\0b", 3).length());
shiqian4b6829f2008-07-03 22:38:12 +00001074}
1075
1076// Tests String::EndsWith().
1077TEST(StringTest, EndsWith) {
1078 EXPECT_TRUE(String("foobar").EndsWith("bar"));
1079 EXPECT_TRUE(String("foobar").EndsWith(""));
1080 EXPECT_TRUE(String("").EndsWith(""));
1081
1082 EXPECT_FALSE(String("foobar").EndsWith("foo"));
1083 EXPECT_FALSE(String("").EndsWith("foo"));
1084}
1085
1086// Tests String::EndsWithCaseInsensitive().
1087TEST(StringTest, EndsWithCaseInsensitive) {
1088 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
1089 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
1090 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
1091 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
1092
1093 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
1094 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
1095 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
1096}
1097
zhanyong.wan98efcc42009-04-28 00:28:09 +00001098// C++Builder's preprocessor is buggy; it fails to expand macros that
1099// appear in macro parameters after wide char literals. Provide an alias
1100// for NULL as a workaround.
1101static const wchar_t* const kNull = NULL;
1102
shiqiane8ff1482008-09-08 17:55:52 +00001103// Tests String::CaseInsensitiveWideCStringEquals
1104TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1105 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001106 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1107 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1108 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1109 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +00001110 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1111 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1112 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1113}
1114
shiqian4b6829f2008-07-03 22:38:12 +00001115// Tests that NULL can be assigned to a String.
1116TEST(StringTest, CanBeAssignedNULL) {
1117 const String src(NULL);
1118 String dest;
1119
1120 dest = src;
1121 EXPECT_STREQ(NULL, dest.c_str());
1122}
1123
1124// Tests that the empty string "" can be assigned to a String.
1125TEST(StringTest, CanBeAssignedEmpty) {
1126 const String src("");
1127 String dest;
1128
1129 dest = src;
1130 EXPECT_STREQ("", dest.c_str());
1131}
1132
1133// Tests that a non-empty string can be assigned to a String.
1134TEST(StringTest, CanBeAssignedNonEmpty) {
1135 const String src("hello");
1136 String dest;
shiqian4b6829f2008-07-03 22:38:12 +00001137 dest = src;
zhanyong.wan89be5762009-09-01 18:53:56 +00001138 EXPECT_EQ(5U, dest.length());
shiqian4b6829f2008-07-03 22:38:12 +00001139 EXPECT_STREQ("hello", dest.c_str());
zhanyong.wan89be5762009-09-01 18:53:56 +00001140
1141 const String src2("x\0y", 3);
1142 String dest2;
1143 dest2 = src2;
1144 EXPECT_EQ(3U, dest2.length());
1145 EXPECT_EQ('x', dest2.c_str()[0]);
1146 EXPECT_EQ('\0', dest2.c_str()[1]);
1147 EXPECT_EQ('y', dest2.c_str()[2]);
shiqian4b6829f2008-07-03 22:38:12 +00001148}
1149
1150// Tests that a String can be assigned to itself.
1151TEST(StringTest, CanBeAssignedSelf) {
1152 String dest("hello");
1153
zhanyong.wanbe1cdf32011-01-07 01:14:05 +00001154 // Use explicit function call notation here to suppress self-assign warning.
1155 dest.operator=(dest);
shiqian4b6829f2008-07-03 22:38:12 +00001156 EXPECT_STREQ("hello", dest.c_str());
1157}
1158
vladlosev673a0cb2010-02-03 02:27:02 +00001159// Sun Studio < 12 incorrectly rejects this code due to an overloading
1160// ambiguity.
1161#if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
zhanyong.wan89be5762009-09-01 18:53:56 +00001162// Tests streaming a String.
1163TEST(StringTest, Streams) {
1164 EXPECT_EQ(StreamableToString(String()), "(null)");
1165 EXPECT_EQ(StreamableToString(String("")), "");
1166 EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
1167}
vladlosev673a0cb2010-02-03 02:27:02 +00001168#endif
zhanyong.wan89be5762009-09-01 18:53:56 +00001169
zhanyong.wanf39160b2009-09-04 18:30:25 +00001170// Tests that String::Format() works.
1171TEST(StringTest, FormatWorks) {
1172 // Normal case: the format spec is valid, the arguments match the
1173 // spec, and the result is < 4095 characters.
1174 EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
1175
1176 // Edge case: the result is 4095 characters.
1177 char buffer[4096];
1178 const size_t kSize = sizeof(buffer);
1179 memset(buffer, 'a', kSize - 1);
1180 buffer[kSize - 1] = '\0';
1181 EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
1182
1183 // The result needs to be 4096 characters, exceeding Format()'s limit.
1184 EXPECT_STREQ("<formatting error or buffer exceeded>",
1185 String::Format("x%s", buffer).c_str());
1186
1187#if GTEST_OS_LINUX
1188 // On Linux, invalid format spec should lead to an error message.
1189 // In other environment (e.g. MSVC on Windows), String::Format() may
1190 // simply ignore a bad format spec, so this assertion is run on
1191 // Linux only.
1192 EXPECT_STREQ("<formatting error or buffer exceeded>",
1193 String::Format("%").c_str());
1194#endif
1195}
1196
zhanyong.wan4cd62602009-02-23 23:21:55 +00001197#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00001198
1199// Tests String::ShowWideCString().
1200TEST(StringTest, ShowWideCString) {
1201 EXPECT_STREQ("(null)",
1202 String::ShowWideCString(NULL).c_str());
1203 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1204 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1205}
1206
1207// Tests String::ShowWideCStringQuoted().
1208TEST(StringTest, ShowWideCStringQuoted) {
1209 EXPECT_STREQ("(null)",
1210 String::ShowWideCStringQuoted(NULL).c_str());
1211 EXPECT_STREQ("L\"\"",
1212 String::ShowWideCStringQuoted(L"").c_str());
1213 EXPECT_STREQ("L\"foo\"",
1214 String::ShowWideCStringQuoted(L"foo").c_str());
1215}
1216
zhanyong.wan733a54a2011-02-22 22:08:59 +00001217# if GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001218TEST(StringTest, AnsiAndUtf16Null) {
1219 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1220 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1221}
1222
1223TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1224 const char* ansi = String::Utf16ToAnsi(L"str");
1225 EXPECT_STREQ("str", ansi);
1226 delete [] ansi;
1227 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001228 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001229 delete [] utf16;
1230}
1231
1232TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1233 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1234 EXPECT_STREQ(".:\\ \"*?", ansi);
1235 delete [] ansi;
1236 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001237 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001238 delete [] utf16;
1239}
zhanyong.wan733a54a2011-02-22 22:08:59 +00001240# endif // GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001241
shiqian4b6829f2008-07-03 22:38:12 +00001242#endif // GTEST_OS_WINDOWS
1243
1244// Tests TestProperty construction.
1245TEST(TestPropertyTest, StringValue) {
1246 TestProperty property("key", "1");
1247 EXPECT_STREQ("key", property.key());
1248 EXPECT_STREQ("1", property.value());
1249}
1250
1251// Tests TestProperty replacing a value.
1252TEST(TestPropertyTest, ReplaceStringValue) {
1253 TestProperty property("key", "1");
1254 EXPECT_STREQ("1", property.value());
1255 property.SetValue("2");
1256 EXPECT_STREQ("2", property.value());
1257}
1258
zhanyong.wan98efcc42009-04-28 00:28:09 +00001259// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1260// functions (i.e. their definitions cannot be inlined at the call
1261// sites), or C++Builder won't compile the code.
1262static void AddFatalFailure() {
1263 FAIL() << "Expected fatal failure.";
1264}
1265
1266static void AddNonfatalFailure() {
1267 ADD_FAILURE() << "Expected non-fatal failure.";
1268}
1269
shiqiane44602e2008-10-11 07:20:02 +00001270class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001271 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001272 enum FailureMode {
1273 FATAL_FAILURE,
1274 NONFATAL_FAILURE
1275 };
1276 static void AddFailure(FailureMode failure) {
1277 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001278 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001279 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001280 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001281 }
1282 }
shiqian4b6829f2008-07-03 22:38:12 +00001283};
1284
shiqian4b6829f2008-07-03 22:38:12 +00001285// Tests that ScopedFakeTestPartResultReporter intercepts test
1286// failures.
shiqiane44602e2008-10-11 07:20:02 +00001287TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001288 TestPartResultArray results;
1289 {
shiqiane44602e2008-10-11 07:20:02 +00001290 ScopedFakeTestPartResultReporter reporter(
1291 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1292 &results);
1293 AddFailure(NONFATAL_FAILURE);
1294 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001295 }
1296
1297 EXPECT_EQ(2, results.size());
1298 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1299 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1300}
1301
shiqiane44602e2008-10-11 07:20:02 +00001302TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1303 TestPartResultArray results;
1304 {
1305 // Tests, that the deprecated constructor still works.
1306 ScopedFakeTestPartResultReporter reporter(&results);
1307 AddFailure(NONFATAL_FAILURE);
1308 }
1309 EXPECT_EQ(1, results.size());
1310}
1311
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001312#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001313
1314class ScopedFakeTestPartResultReporterWithThreadsTest
1315 : public ScopedFakeTestPartResultReporterTest {
1316 protected:
1317 static void AddFailureInOtherThread(FailureMode failure) {
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001318 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1319 thread.Join();
shiqiane44602e2008-10-11 07:20:02 +00001320 }
1321};
1322
1323TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1324 InterceptsTestFailuresInAllThreads) {
1325 TestPartResultArray results;
1326 {
1327 ScopedFakeTestPartResultReporter reporter(
1328 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1329 AddFailure(NONFATAL_FAILURE);
1330 AddFailure(FATAL_FAILURE);
1331 AddFailureInOtherThread(NONFATAL_FAILURE);
1332 AddFailureInOtherThread(FATAL_FAILURE);
1333 }
1334
1335 EXPECT_EQ(4, results.size());
1336 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1337 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1338 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1339 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1340}
1341
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001342#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001343
zhanyong.wan98efcc42009-04-28 00:28:09 +00001344// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1345// work even if the failure is generated in a called function rather than
1346// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001347
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001348typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001349
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001350TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001351 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001352}
1353
zhanyong.wan375ce982010-09-27 17:42:52 +00001354#if GTEST_HAS_GLOBAL_STRING
1355TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1356 EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1357}
1358#endif
1359
1360TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1361 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1362 ::std::string("Expected fatal failure."));
1363}
1364
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001365TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1366 // We have another test below to verify that the macro catches fatal
1367 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001368 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001369 "Expected fatal failure.");
1370}
1371
zhanyong.wan98efcc42009-04-28 00:28:09 +00001372#ifdef __BORLANDC__
1373// Silences warnings: "Condition is always true"
zhanyong.wan733a54a2011-02-22 22:08:59 +00001374# pragma option push -w-ccc
zhanyong.wan98efcc42009-04-28 00:28:09 +00001375#endif
1376
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001377// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1378// function even when the statement in it contains ASSERT_*.
1379
1380int NonVoidFunction() {
1381 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1382 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1383 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001384}
1385
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001386TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1387 NonVoidFunction();
1388}
1389
1390// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1391// current function even though 'statement' generates a fatal failure.
1392
1393void DoesNotAbortHelper(bool* aborted) {
1394 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1395 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1396
1397 *aborted = false;
1398}
1399
zhanyong.wan98efcc42009-04-28 00:28:09 +00001400#ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +00001401// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan733a54a2011-02-22 22:08:59 +00001402# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00001403#endif
1404
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001405TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1406 bool aborted = true;
1407 DoesNotAbortHelper(&aborted);
1408 EXPECT_FALSE(aborted);
1409}
1410
1411// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1412// statement that contains a macro which expands to code containing an
1413// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001414
1415static int global_var = 0;
1416#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1417
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001418TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.waned1042b2011-03-05 08:04:01 +00001419#ifndef __BORLANDC__
1420 // ICE's in C++Builder.
shiqiane44602e2008-10-11 07:20:02 +00001421 EXPECT_FATAL_FAILURE({
1422 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001423 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001424 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001425#endif
shiqiane44602e2008-10-11 07:20:02 +00001426
1427 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1428 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001429 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001430 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001431}
shiqiane44602e2008-10-11 07:20:02 +00001432
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001433// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1434
1435typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1436
1437TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001438 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001439 "Expected non-fatal failure.");
1440}
1441
zhanyong.wan375ce982010-09-27 17:42:52 +00001442#if GTEST_HAS_GLOBAL_STRING
1443TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1444 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1445 ::string("Expected non-fatal failure."));
1446}
1447#endif
1448
1449TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1450 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1451 ::std::string("Expected non-fatal failure."));
1452}
1453
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001454TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1455 // We have another test below to verify that the macro catches
1456 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001457 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001458 "Expected non-fatal failure.");
1459}
1460
1461// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1462// statement that contains a macro which expands to code containing an
1463// unprotected comma.
1464TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001465 EXPECT_NONFATAL_FAILURE({
1466 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001467 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001468 }, "");
1469
1470 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1471 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001472 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001473 }, "");
1474}
1475
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001476#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001477
1478typedef ScopedFakeTestPartResultReporterWithThreadsTest
1479 ExpectFailureWithThreadsTest;
1480
1481TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1482 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1483 "Expected fatal failure.");
1484}
1485
1486TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1487 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1488 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1489}
1490
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001491#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001492
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001493// Tests the TestProperty class.
1494
1495TEST(TestPropertyTest, ConstructorWorks) {
1496 const TestProperty property("key", "value");
1497 EXPECT_STREQ("key", property.key());
1498 EXPECT_STREQ("value", property.value());
1499}
1500
1501TEST(TestPropertyTest, SetValue) {
1502 TestProperty property("key", "value_1");
1503 EXPECT_STREQ("key", property.key());
1504 property.SetValue("value_2");
1505 EXPECT_STREQ("key", property.key());
1506 EXPECT_STREQ("value_2", property.value());
1507}
1508
shiqian4b6829f2008-07-03 22:38:12 +00001509// Tests the TestResult class
1510
1511// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001512class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001513 protected:
zhanyong.wan93d13a82010-02-25 01:09:07 +00001514 typedef std::vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001515
1516 // We make use of 2 TestPartResult objects,
1517 TestPartResult * pr1, * pr2;
1518
1519 // ... and 3 TestResult objects.
1520 TestResult * r0, * r1, * r2;
1521
1522 virtual void SetUp() {
1523 // pr1 is for success.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001524 pr1 = new TestPartResult(TestPartResult::kSuccess,
1525 "foo/bar.cc",
1526 10,
1527 "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001528
1529 // pr2 is for fatal failure.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001530 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1531 "foo/bar.cc",
shiqian760af5c2008-08-06 21:43:15 +00001532 -1, // This line number means "unknown"
1533 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001534
1535 // Creates the TestResult objects.
1536 r0 = new TestResult();
1537 r1 = new TestResult();
1538 r2 = new TestResult();
1539
1540 // In order to test TestResult, we need to modify its internal
zhanyong.wan93d13a82010-02-25 01:09:07 +00001541 // state, in particular the TestPartResult vector it holds.
1542 // test_part_results() returns a const reference to this vector.
shiqian4b6829f2008-07-03 22:38:12 +00001543 // We cast it to a non-const object s.t. it can be modified (yes,
1544 // this is a hack).
zhanyong.wan93d13a82010-02-25 01:09:07 +00001545 TPRVector* results1 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001546 &TestResultAccessor::test_part_results(*r1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001547 TPRVector* results2 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001548 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001549
1550 // r0 is an empty TestResult.
1551
1552 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001553 results1->push_back(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001554
1555 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001556 results2->push_back(*pr1);
1557 results2->push_back(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001558 }
1559
1560 virtual void TearDown() {
1561 delete pr1;
1562 delete pr2;
1563
1564 delete r0;
1565 delete r1;
1566 delete r2;
1567 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001568
1569 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001570 static void CompareTestPartResult(const TestPartResult& expected,
1571 const TestPartResult& actual) {
1572 EXPECT_EQ(expected.type(), actual.type());
1573 EXPECT_STREQ(expected.file_name(), actual.file_name());
1574 EXPECT_EQ(expected.line_number(), actual.line_number());
1575 EXPECT_STREQ(expected.summary(), actual.summary());
1576 EXPECT_STREQ(expected.message(), actual.message());
1577 EXPECT_EQ(expected.passed(), actual.passed());
1578 EXPECT_EQ(expected.failed(), actual.failed());
1579 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1580 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001581 }
shiqian4b6829f2008-07-03 22:38:12 +00001582};
1583
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001584// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001585TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001586 ASSERT_EQ(0, r0->total_part_count());
1587 ASSERT_EQ(1, r1->total_part_count());
1588 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001589}
1590
zhanyong.wan9644db82009-06-24 23:02:50 +00001591// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001592TEST_F(TestResultTest, Passed) {
1593 ASSERT_TRUE(r0->Passed());
1594 ASSERT_TRUE(r1->Passed());
1595 ASSERT_FALSE(r2->Passed());
1596}
1597
zhanyong.wan9644db82009-06-24 23:02:50 +00001598// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001599TEST_F(TestResultTest, Failed) {
1600 ASSERT_FALSE(r0->Failed());
1601 ASSERT_FALSE(r1->Failed());
1602 ASSERT_TRUE(r2->Failed());
1603}
1604
zhanyong.wan9644db82009-06-24 23:02:50 +00001605// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001606
1607typedef TestResultTest TestResultDeathTest;
1608
1609TEST_F(TestResultDeathTest, GetTestPartResult) {
1610 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1611 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001612 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1613 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001614}
1615
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001616// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001617TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1618 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001619 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001620}
1621
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001622// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001623TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1624 TestResult test_result;
1625 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001626 TestResultAccessor::RecordProperty(&test_result, property);
1627 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001628 const TestProperty& actual_property = test_result.GetTestProperty(0);
1629 EXPECT_STREQ("key_1", actual_property.key());
1630 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001631}
1632
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001633// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001634TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1635 TestResult test_result;
1636 TestProperty property_1("key_1", "1");
1637 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001638 TestResultAccessor::RecordProperty(&test_result, property_1);
1639 TestResultAccessor::RecordProperty(&test_result, property_2);
1640 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001641 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1642 EXPECT_STREQ("key_1", actual_property_1.key());
1643 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001644
zhanyong.wan449f84d2009-07-01 22:55:05 +00001645 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1646 EXPECT_STREQ("key_2", actual_property_2.key());
1647 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001648}
1649
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001650// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001651TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1652 TestResult test_result;
1653 TestProperty property_1_1("key_1", "1");
1654 TestProperty property_2_1("key_2", "2");
1655 TestProperty property_1_2("key_1", "12");
1656 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001657 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1658 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1659 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1660 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001661
zhanyong.wan9644db82009-06-24 23:02:50 +00001662 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001663 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1664 EXPECT_STREQ("key_1", actual_property_1.key());
1665 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001666
zhanyong.wan449f84d2009-07-01 22:55:05 +00001667 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1668 EXPECT_STREQ("key_2", actual_property_2.key());
1669 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001670}
1671
1672// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001673TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001674 TestResult test_result;
1675 TestProperty property_1("key_1", "1");
1676 TestProperty property_2("key_2", "2");
1677 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001678 TestResultAccessor::RecordProperty(&test_result, property_1);
1679 TestResultAccessor::RecordProperty(&test_result, property_2);
1680 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001681
zhanyong.wan449f84d2009-07-01 22:55:05 +00001682 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1683 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1684 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001685
zhanyong.wan449f84d2009-07-01 22:55:05 +00001686 EXPECT_STREQ("key_1", fetched_property_1.key());
1687 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001688
zhanyong.wan449f84d2009-07-01 22:55:05 +00001689 EXPECT_STREQ("key_2", fetched_property_2.key());
1690 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001691
zhanyong.wan449f84d2009-07-01 22:55:05 +00001692 EXPECT_STREQ("key_3", fetched_property_3.key());
1693 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001694
zhanyong.wan93d13a82010-02-25 01:09:07 +00001695 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1696 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001697}
1698
shiqian4b6829f2008-07-03 22:38:12 +00001699// When a property using a reserved key is supplied to this function, it tests
1700// that a non-fatal failure is added, a fatal failure is not added, and that the
1701// property is not recorded.
1702void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1703 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001704 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001705 EXPECT_NONFATAL_FAILURE(
1706 TestResultAccessor::RecordProperty(&test_result, property),
1707 "Reserved key");
1708 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001709}
1710
1711// Attempting to recording a property with the Reserved literal "name"
1712// should add a non-fatal failure and the property should not be recorded.
1713TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1714 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1715}
1716
1717// Attempting to recording a property with the Reserved literal "status"
1718// should add a non-fatal failure and the property should not be recorded.
1719TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1720 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1721}
1722
1723// Attempting to recording a property with the Reserved literal "time"
1724// should add a non-fatal failure and the property should not be recorded.
1725TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1726 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1727}
1728
1729// Attempting to recording a property with the Reserved literal "classname"
1730// should add a non-fatal failure and the property should not be recorded.
1731TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1732 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1733}
1734
1735// Tests that GTestFlagSaver works on Windows and Mac.
1736
shiqian760af5c2008-08-06 21:43:15 +00001737class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001738 protected:
1739 // Saves the Google Test flags such that we can restore them later, and
1740 // then sets them to their default values. This will be called
1741 // before the first test in this test case is run.
1742 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001743 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001744
shiqianca6949f2009-01-10 01:16:33 +00001745 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001746 GTEST_FLAG(break_on_failure) = false;
1747 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001748 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001749 GTEST_FLAG(color) = "auto";
1750 GTEST_FLAG(filter) = "";
1751 GTEST_FLAG(list_tests) = false;
1752 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001753 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001754 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001755 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001756 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00001757 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00001758 GTEST_FLAG(stream_result_to) = "";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001759 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001760 }
1761
1762 // Restores the Google Test flags that the tests have modified. This will
1763 // be called after the last test in this test case is run.
1764 static void TearDownTestCase() {
1765 delete saver_;
1766 saver_ = NULL;
1767 }
1768
1769 // Verifies that the Google Test flags have their default values, and then
1770 // modifies each of them.
1771 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001772 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001773 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1774 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1775 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001776 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001777 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1778 EXPECT_FALSE(GTEST_FLAG(list_tests));
1779 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001780 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001781 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001782 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001783 EXPECT_FALSE(GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00001784 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanc95489e2010-08-19 22:16:00 +00001785 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001786 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001787
shiqianca6949f2009-01-10 01:16:33 +00001788 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001789 GTEST_FLAG(break_on_failure) = true;
1790 GTEST_FLAG(catch_exceptions) = true;
1791 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001792 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001793 GTEST_FLAG(filter) = "abc";
1794 GTEST_FLAG(list_tests) = true;
1795 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001796 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001797 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001798 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001799 GTEST_FLAG(shuffle) = true;
vladlosevba015a92009-11-17 22:43:15 +00001800 GTEST_FLAG(stack_trace_depth) = 1;
zhanyong.wanc95489e2010-08-19 22:16:00 +00001801 GTEST_FLAG(stream_result_to) = "localhost:1234";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001802 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001803 }
1804 private:
1805 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001806 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001807};
1808
shiqian760af5c2008-08-06 21:43:15 +00001809GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001810
1811// Google Test doesn't guarantee the order of tests. The following two
1812// tests are designed to work regardless of their order.
1813
1814// Modifies the Google Test flags in the test body.
1815TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1816 VerifyAndModifyFlags();
1817}
1818
1819// Verifies that the Google Test flags in the body of the previous test were
1820// restored to their original values.
1821TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1822 VerifyAndModifyFlags();
1823}
1824
1825// Sets an environment variable with the given name to the given
1826// value. If the value argument is "", unsets the environment
1827// variable. The caller must ensure that both arguments are not NULL.
1828static void SetEnv(const char* name, const char* value) {
zhanyong.wanfff03342009-09-24 21:15:59 +00001829#if GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001830 // Environment variables are not supported on Windows CE.
1831 return;
vladlosev673a0cb2010-02-03 02:27:02 +00001832#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
zhanyong.wan98efcc42009-04-28 00:28:09 +00001833 // C++Builder's putenv only stores a pointer to its parameter; we have to
1834 // ensure that the string remains valid as long as it might be needed.
1835 // We use an std::map to do so.
1836 static std::map<String, String*> added_env;
1837
1838 // Because putenv stores a pointer to the string buffer, we can't delete the
1839 // previous string (if present) until after it's replaced.
1840 String *prev_env = NULL;
1841 if (added_env.find(name) != added_env.end()) {
1842 prev_env = added_env[name];
1843 }
1844 added_env[name] = new String((Message() << name << "=" << value).GetString());
vladlosev673a0cb2010-02-03 02:27:02 +00001845
1846 // The standard signature of putenv accepts a 'char*' argument. Other
1847 // implementations, like C++Builder's, accept a 'const char*'.
1848 // We cast away the 'const' since that would work for both variants.
1849 putenv(const_cast<char*>(added_env[name]->c_str()));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001850 delete prev_env;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001851#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001852 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001853#else
1854 if (*value == '\0') {
1855 unsetenv(name);
1856 } else {
1857 setenv(name, value, 1);
1858 }
zhanyong.wanfff03342009-09-24 21:15:59 +00001859#endif // GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001860}
1861
zhanyong.wanfff03342009-09-24 21:15:59 +00001862#if !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001863// Environment variables are not supported on Windows CE.
1864
shiqian760af5c2008-08-06 21:43:15 +00001865using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001866
1867// Tests Int32FromGTestEnv().
1868
1869// Tests that Int32FromGTestEnv() returns the default value when the
1870// environment variable is not set.
1871TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001872 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001873 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1874}
1875
1876// Tests that Int32FromGTestEnv() returns the default value when the
1877// environment variable overflows as an Int32.
1878TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1879 printf("(expecting 2 warnings)\n");
1880
zhanyong.wan4cd62602009-02-23 23:21:55 +00001881 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001882 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1883
zhanyong.wan4cd62602009-02-23 23:21:55 +00001884 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001885 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1886}
1887
1888// Tests that Int32FromGTestEnv() returns the default value when the
1889// environment variable does not represent a valid decimal integer.
1890TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1891 printf("(expecting 2 warnings)\n");
1892
zhanyong.wan4cd62602009-02-23 23:21:55 +00001893 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001894 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1895
zhanyong.wan4cd62602009-02-23 23:21:55 +00001896 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001897 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1898}
1899
1900// Tests that Int32FromGTestEnv() parses and returns the value of the
1901// environment variable when it represents a valid decimal integer in
1902// the range of an Int32.
1903TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001904 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001905 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1906
zhanyong.wan4cd62602009-02-23 23:21:55 +00001907 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001908 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1909}
zhanyong.wanfff03342009-09-24 21:15:59 +00001910#endif // !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001911
1912// Tests ParseInt32Flag().
1913
1914// Tests that ParseInt32Flag() returns false and doesn't change the
1915// output value when the flag has wrong format
1916TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1917 Int32 value = 123;
1918 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1919 EXPECT_EQ(123, value);
1920
1921 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1922 EXPECT_EQ(123, value);
1923}
1924
1925// Tests that ParseInt32Flag() returns false and doesn't change the
1926// output value when the flag overflows as an Int32.
1927TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1928 printf("(expecting 2 warnings)\n");
1929
1930 Int32 value = 123;
1931 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1932 EXPECT_EQ(123, value);
1933
1934 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1935 EXPECT_EQ(123, value);
1936}
1937
1938// Tests that ParseInt32Flag() returns false and doesn't change the
1939// output value when the flag does not represent a valid decimal
1940// integer.
1941TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1942 printf("(expecting 2 warnings)\n");
1943
1944 Int32 value = 123;
1945 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1946 EXPECT_EQ(123, value);
1947
1948 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1949 EXPECT_EQ(123, value);
1950}
1951
1952// Tests that ParseInt32Flag() parses the value of the flag and
1953// returns true when the flag represents a valid decimal integer in
1954// the range of an Int32.
1955TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1956 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001957 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001958 EXPECT_EQ(456, value);
1959
zhanyong.wan98efcc42009-04-28 00:28:09 +00001960 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1961 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001962 EXPECT_EQ(-789, value);
1963}
1964
zhanyong.wan905074c2009-02-09 18:05:21 +00001965// Tests that Int32FromEnvOrDie() parses the value of the var or
1966// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001967// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00001968#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001969TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001970 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1971 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1972 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1973 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1974 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001975}
zhanyong.wanfff03342009-09-24 21:15:59 +00001976#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001977
1978// Tests that Int32FromEnvOrDie() aborts with an error message
1979// if the variable is not an Int32.
1980TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001981 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan535de532009-08-07 06:47:47 +00001982 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001983 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1984 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001985}
1986
1987// Tests that Int32FromEnvOrDie() aborts with an error message
1988// if the variable cannot be represnted by an Int32.
1989TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001990 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan535de532009-08-07 06:47:47 +00001991 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001992 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1993 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001994}
1995
zhanyong.wan905074c2009-02-09 18:05:21 +00001996// Tests that ShouldRunTestOnShard() selects all tests
1997// where there is 1 shard.
1998TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1999 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
2000 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
2001 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
2002 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
2003 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
2004}
2005
2006class ShouldShardTest : public testing::Test {
2007 protected:
2008 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002009 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
2010 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00002011 }
2012
2013 virtual void TearDown() {
2014 SetEnv(index_var_, "");
2015 SetEnv(total_var_, "");
2016 }
2017
2018 const char* index_var_;
2019 const char* total_var_;
2020};
2021
2022// Tests that sharding is disabled if neither of the environment variables
2023// are set.
2024TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
2025 SetEnv(index_var_, "");
2026 SetEnv(total_var_, "");
2027
2028 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
2029 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2030}
2031
2032// Tests that sharding is not enabled if total_shards == 1.
2033TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
2034 SetEnv(index_var_, "0");
2035 SetEnv(total_var_, "1");
2036 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
2037 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2038}
2039
2040// Tests that sharding is enabled if total_shards > 1 and
2041// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00002042// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00002043#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002044TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
2045 SetEnv(index_var_, "4");
2046 SetEnv(total_var_, "22");
2047 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2048 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2049
2050 SetEnv(index_var_, "8");
2051 SetEnv(total_var_, "9");
2052 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2053 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2054
2055 SetEnv(index_var_, "0");
2056 SetEnv(total_var_, "9");
2057 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2058 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2059}
zhanyong.wanfff03342009-09-24 21:15:59 +00002060#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002061
2062// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00002063
2064typedef ShouldShardTest ShouldShardDeathTest;
2065
2066TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00002067 SetEnv(index_var_, "4");
2068 SetEnv(total_var_, "4");
zhanyong.wan535de532009-08-07 06:47:47 +00002069 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002070
2071 SetEnv(index_var_, "4");
2072 SetEnv(total_var_, "-2");
zhanyong.wan535de532009-08-07 06:47:47 +00002073 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002074
2075 SetEnv(index_var_, "5");
2076 SetEnv(total_var_, "");
zhanyong.wan535de532009-08-07 06:47:47 +00002077 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002078
2079 SetEnv(index_var_, "");
2080 SetEnv(total_var_, "5");
zhanyong.wan535de532009-08-07 06:47:47 +00002081 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002082}
2083
zhanyong.wan905074c2009-02-09 18:05:21 +00002084// Tests that ShouldRunTestOnShard is a partition when 5
2085// shards are used.
2086TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
2087 // Choose an arbitrary number of tests and shards.
2088 const int num_tests = 17;
2089 const int num_shards = 5;
2090
2091 // Check partitioning: each test should be on exactly 1 shard.
2092 for (int test_id = 0; test_id < num_tests; test_id++) {
2093 int prev_selected_shard_index = -1;
2094 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2095 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
2096 if (prev_selected_shard_index < 0) {
2097 prev_selected_shard_index = shard_index;
2098 } else {
2099 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
2100 << shard_index << " are both selected to run test " << test_id;
2101 }
2102 }
2103 }
2104 }
2105
2106 // Check balance: This is not required by the sharding protocol, but is a
2107 // desirable property for performance.
2108 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2109 int num_tests_on_shard = 0;
2110 for (int test_id = 0; test_id < num_tests; test_id++) {
2111 num_tests_on_shard +=
2112 ShouldRunTestOnShard(num_shards, shard_index, test_id);
2113 }
2114 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
2115 }
2116}
2117
shiqian4b6829f2008-07-03 22:38:12 +00002118// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00002119// Test class, there are no separate tests for the following classes
2120// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00002121//
2122// TestCase, UnitTest, UnitTestResultPrinter.
2123//
2124// Similarly, there are no separate tests for the following macros:
2125//
2126// TEST, TEST_F, RUN_ALL_TESTS
2127
shiqianc3b4de32008-09-12 04:01:37 +00002128TEST(UnitTestTest, CanGetOriginalWorkingDir) {
2129 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
2130 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2131}
2132
shiqian4b6829f2008-07-03 22:38:12 +00002133// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2134// of various arities. They do not attempt to be exhaustive. Rather,
2135// view them as smoke tests that can be easily reviewed and verified.
2136// A more complete set of tests for predicate assertions can be found
2137// in gtest_pred_impl_unittest.cc.
2138
2139// First, some predicates and predicate-formatters needed by the tests.
2140
2141// Returns true iff the argument is an even number.
2142bool IsEven(int n) {
2143 return (n % 2) == 0;
2144}
2145
2146// A functor that returns true iff the argument is an even number.
2147struct IsEvenFunctor {
2148 bool operator()(int n) { return IsEven(n); }
2149};
2150
2151// A predicate-formatter function that asserts the argument is an even
2152// number.
shiqian760af5c2008-08-06 21:43:15 +00002153AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002154 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00002155 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002156 }
2157
shiqian760af5c2008-08-06 21:43:15 +00002158 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002159 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002160 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002161}
2162
vladlosevfbd53a52009-10-20 21:03:10 +00002163// A predicate function that returns AssertionResult for use in
2164// EXPECT/ASSERT_TRUE/FALSE.
2165AssertionResult ResultIsEven(int n) {
2166 if (IsEven(n))
2167 return AssertionSuccess() << n << " is even";
2168 else
2169 return AssertionFailure() << n << " is odd";
2170}
2171
2172// A predicate function that returns AssertionResult but gives no
2173// explanation why it succeeds. Needed for testing that
2174// EXPECT/ASSERT_FALSE handles such functions correctly.
2175AssertionResult ResultIsEvenNoExplanation(int n) {
2176 if (IsEven(n))
2177 return AssertionSuccess();
2178 else
2179 return AssertionFailure() << n << " is odd";
2180}
2181
shiqian4b6829f2008-07-03 22:38:12 +00002182// A predicate-formatter functor that asserts the argument is an even
2183// number.
2184struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00002185 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002186 return AssertIsEven(expr, n);
2187 }
2188};
2189
2190// Returns true iff the sum of the arguments is an even number.
2191bool SumIsEven2(int n1, int n2) {
2192 return IsEven(n1 + n2);
2193}
2194
2195// A functor that returns true iff the sum of the arguments is an even
2196// number.
2197struct SumIsEven3Functor {
2198 bool operator()(int n1, int n2, int n3) {
2199 return IsEven(n1 + n2 + n3);
2200 }
2201};
2202
2203// A predicate-formatter function that asserts the sum of the
2204// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00002205AssertionResult AssertSumIsEven4(
2206 const char* e1, const char* e2, const char* e3, const char* e4,
2207 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00002208 const int sum = n1 + n2 + n3 + n4;
2209 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002210 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002211 }
2212
shiqian760af5c2008-08-06 21:43:15 +00002213 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002214 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2215 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2216 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002217 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002218}
2219
2220// A predicate-formatter functor that asserts the sum of the arguments
2221// is an even number.
2222struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00002223 AssertionResult operator()(
2224 const char* e1, const char* e2, const char* e3, const char* e4,
2225 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00002226 const int sum = n1 + n2 + n3 + n4 + n5;
2227 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002228 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002229 }
2230
shiqian760af5c2008-08-06 21:43:15 +00002231 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002232 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2233 << " ("
2234 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2235 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002236 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002237 }
2238};
2239
2240
2241// Tests unary predicate assertions.
2242
2243// Tests unary predicate assertions that don't use a custom formatter.
2244TEST(Pred1Test, WithoutFormat) {
2245 // Success cases.
2246 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2247 ASSERT_PRED1(IsEven, 4);
2248
2249 // Failure cases.
2250 EXPECT_NONFATAL_FAILURE({ // NOLINT
2251 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2252 }, "This failure is expected.");
2253 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2254 "evaluates to false");
2255}
2256
2257// Tests unary predicate assertions that use a custom formatter.
2258TEST(Pred1Test, WithFormat) {
2259 // Success cases.
2260 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2261 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2262 << "This failure is UNEXPECTED!";
2263
2264 // Failure cases.
2265 const int n = 5;
2266 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2267 "n evaluates to 5, which is not even.");
2268 EXPECT_FATAL_FAILURE({ // NOLINT
2269 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2270 }, "This failure is expected.");
2271}
2272
2273// Tests that unary predicate assertions evaluates their arguments
2274// exactly once.
2275TEST(Pred1Test, SingleEvaluationOnFailure) {
2276 // A success case.
2277 static int n = 0;
2278 EXPECT_PRED1(IsEven, n++);
2279 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2280
2281 // A failure case.
2282 EXPECT_FATAL_FAILURE({ // NOLINT
2283 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2284 << "This failure is expected.";
2285 }, "This failure is expected.");
2286 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2287}
2288
2289
2290// Tests predicate assertions whose arity is >= 2.
2291
2292// Tests predicate assertions that don't use a custom formatter.
2293TEST(PredTest, WithoutFormat) {
2294 // Success cases.
2295 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2296 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2297
2298 // Failure cases.
2299 const int n1 = 1;
2300 const int n2 = 2;
2301 EXPECT_NONFATAL_FAILURE({ // NOLINT
2302 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2303 }, "This failure is expected.");
2304 EXPECT_FATAL_FAILURE({ // NOLINT
2305 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2306 }, "evaluates to false");
2307}
2308
2309// Tests predicate assertions that use a custom formatter.
2310TEST(PredTest, WithFormat) {
2311 // Success cases.
2312 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2313 "This failure is UNEXPECTED!";
2314 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2315
2316 // Failure cases.
2317 const int n1 = 1;
2318 const int n2 = 2;
2319 const int n3 = 4;
2320 const int n4 = 6;
2321 EXPECT_NONFATAL_FAILURE({ // NOLINT
2322 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2323 }, "evaluates to 13, which is not even.");
2324 EXPECT_FATAL_FAILURE({ // NOLINT
2325 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2326 << "This failure is expected.";
2327 }, "This failure is expected.");
2328}
2329
2330// Tests that predicate assertions evaluates their arguments
2331// exactly once.
2332TEST(PredTest, SingleEvaluationOnFailure) {
2333 // A success case.
2334 int n1 = 0;
2335 int n2 = 0;
2336 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2337 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2338 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2339
2340 // Another success case.
2341 n1 = n2 = 0;
2342 int n3 = 0;
2343 int n4 = 0;
2344 int n5 = 0;
2345 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2346 n1++, n2++, n3++, n4++, n5++)
2347 << "This failure is UNEXPECTED!";
2348 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2349 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2350 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2351 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2352 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2353
2354 // A failure case.
2355 n1 = n2 = n3 = 0;
2356 EXPECT_NONFATAL_FAILURE({ // NOLINT
2357 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2358 << "This failure is expected.";
2359 }, "This failure is expected.");
2360 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2361 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2362 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2363
2364 // Another failure case.
2365 n1 = n2 = n3 = n4 = 0;
2366 EXPECT_NONFATAL_FAILURE({ // NOLINT
2367 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2368 }, "evaluates to 1, which is not even.");
2369 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2370 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2371 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2372 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2373}
2374
2375
2376// Some helper functions for testing using overloaded/template
2377// functions with ASSERT_PREDn and EXPECT_PREDn.
2378
shiqian4b6829f2008-07-03 22:38:12 +00002379bool IsPositive(double x) {
2380 return x > 0;
2381}
2382
2383template <typename T>
2384bool IsNegative(T x) {
2385 return x < 0;
2386}
2387
2388template <typename T1, typename T2>
2389bool GreaterThan(T1 x1, T2 x2) {
2390 return x1 > x2;
2391}
2392
2393// Tests that overloaded functions can be used in *_PRED* as long as
2394// their types are explicitly specified.
2395TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002396 // C++Builder requires C-style casts rather than static_cast.
2397 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2398 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002399}
2400
2401// Tests that template functions can be used in *_PRED* as long as
2402// their types are explicitly specified.
2403TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2404 EXPECT_PRED1(IsNegative<int>, -5);
2405 // Makes sure that we can handle templates with more than one
2406 // parameter.
2407 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2408}
2409
2410
2411// Some helper functions for testing using overloaded/template
2412// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2413
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002414AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002415 return n > 0 ? AssertionSuccess() :
2416 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002417}
2418
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002419AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002420 return x > 0 ? AssertionSuccess() :
2421 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002422}
2423
2424template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002425AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002426 return x < 0 ? AssertionSuccess() :
2427 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002428}
2429
2430template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002431AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002432 const T1& x1, const T2& x2) {
2433 return x1 == x2 ? AssertionSuccess() :
2434 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002435}
2436
2437// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002438// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002439TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2440 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2441 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2442}
2443
2444// Tests that template functions can be used in *_PRED_FORMAT* without
2445// explicitly specifying their types.
2446TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2447 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2448 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2449}
2450
2451
2452// Tests string assertions.
2453
2454// Tests ASSERT_STREQ with non-NULL arguments.
2455TEST(StringAssertionTest, ASSERT_STREQ) {
2456 const char * const p1 = "good";
2457 ASSERT_STREQ(p1, p1);
2458
2459 // Let p2 have the same content as p1, but be at a different address.
2460 const char p2[] = "good";
2461 ASSERT_STREQ(p1, p2);
2462
2463 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2464 "Expected: \"bad\"");
2465}
2466
2467// Tests ASSERT_STREQ with NULL arguments.
2468TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2469 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2470 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2471 "non-null");
2472}
2473
2474// Tests ASSERT_STREQ with NULL arguments.
2475TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2476 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2477 "non-null");
2478}
2479
2480// Tests ASSERT_STRNE.
2481TEST(StringAssertionTest, ASSERT_STRNE) {
2482 ASSERT_STRNE("hi", "Hi");
2483 ASSERT_STRNE("Hi", NULL);
2484 ASSERT_STRNE(NULL, "Hi");
2485 ASSERT_STRNE("", NULL);
2486 ASSERT_STRNE(NULL, "");
2487 ASSERT_STRNE("", "Hi");
2488 ASSERT_STRNE("Hi", "");
2489 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2490 "\"Hi\" vs \"Hi\"");
2491}
2492
2493// Tests ASSERT_STRCASEEQ.
2494TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2495 ASSERT_STRCASEEQ("hi", "Hi");
2496 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2497
2498 ASSERT_STRCASEEQ("", "");
2499 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2500 "(ignoring case)");
2501}
2502
2503// Tests ASSERT_STRCASENE.
2504TEST(StringAssertionTest, ASSERT_STRCASENE) {
2505 ASSERT_STRCASENE("hi1", "Hi2");
2506 ASSERT_STRCASENE("Hi", NULL);
2507 ASSERT_STRCASENE(NULL, "Hi");
2508 ASSERT_STRCASENE("", NULL);
2509 ASSERT_STRCASENE(NULL, "");
2510 ASSERT_STRCASENE("", "Hi");
2511 ASSERT_STRCASENE("Hi", "");
2512 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2513 "(ignoring case)");
2514}
2515
2516// Tests *_STREQ on wide strings.
2517TEST(StringAssertionTest, STREQ_Wide) {
2518 // NULL strings.
2519 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2520
2521 // Empty strings.
2522 ASSERT_STREQ(L"", L"");
2523
2524 // Non-null vs NULL.
2525 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2526 "non-null");
2527
2528 // Equal strings.
2529 EXPECT_STREQ(L"Hi", L"Hi");
2530
2531 // Unequal strings.
2532 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2533 "Abc");
2534
2535 // Strings containing wide characters.
2536 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2537 "abc");
2538}
2539
2540// Tests *_STRNE on wide strings.
2541TEST(StringAssertionTest, STRNE_Wide) {
2542 // NULL strings.
2543 EXPECT_NONFATAL_FAILURE({ // NOLINT
2544 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2545 }, "");
2546
2547 // Empty strings.
2548 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2549 "L\"\"");
2550
2551 // Non-null vs NULL.
2552 ASSERT_STRNE(L"non-null", NULL);
2553
2554 // Equal strings.
2555 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2556 "L\"Hi\"");
2557
2558 // Unequal strings.
2559 EXPECT_STRNE(L"abc", L"Abc");
2560
2561 // Strings containing wide characters.
2562 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2563 "abc");
2564}
2565
2566// Tests for ::testing::IsSubstring().
2567
2568// Tests that IsSubstring() returns the correct result when the input
2569// argument type is const char*.
2570TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002571 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2572 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2573 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2574
2575 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2576 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2577}
2578
2579// Tests that IsSubstring() returns the correct result when the input
2580// argument type is const wchar_t*.
2581TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002582 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2583 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002584 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2585
2586 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2587 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2588}
2589
2590// Tests that IsSubstring() generates the correct message when the input
2591// argument type is const char*.
2592TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2593 EXPECT_STREQ("Value of: needle_expr\n"
2594 " Actual: \"needle\"\n"
2595 "Expected: a substring of haystack_expr\n"
2596 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002597 IsSubstring("needle_expr", "haystack_expr",
2598 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002599}
2600
shiqian4b6829f2008-07-03 22:38:12 +00002601// Tests that IsSubstring returns the correct result when the input
2602// argument type is ::std::string.
2603TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002604 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2605 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002606}
2607
shiqian4b6829f2008-07-03 22:38:12 +00002608#if GTEST_HAS_STD_WSTRING
2609// Tests that IsSubstring returns the correct result when the input
2610// argument type is ::std::wstring.
2611TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002612 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2613 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2614}
2615
2616// Tests that IsSubstring() generates the correct message when the input
2617// argument type is ::std::wstring.
2618TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2619 EXPECT_STREQ("Value of: needle_expr\n"
2620 " Actual: L\"needle\"\n"
2621 "Expected: a substring of haystack_expr\n"
2622 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002623 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002624 "needle_expr", "haystack_expr",
2625 ::std::wstring(L"needle"), L"haystack").failure_message());
2626}
2627
2628#endif // GTEST_HAS_STD_WSTRING
2629
2630// Tests for ::testing::IsNotSubstring().
2631
2632// Tests that IsNotSubstring() returns the correct result when the input
2633// argument type is const char*.
2634TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002635 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2636 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2637}
2638
2639// Tests that IsNotSubstring() returns the correct result when the input
2640// argument type is const wchar_t*.
2641TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002642 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2643 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2644}
2645
2646// Tests that IsNotSubstring() generates the correct message when the input
2647// argument type is const wchar_t*.
2648TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2649 EXPECT_STREQ("Value of: needle_expr\n"
2650 " Actual: L\"needle\"\n"
2651 "Expected: not a substring of haystack_expr\n"
2652 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002653 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002654 "needle_expr", "haystack_expr",
2655 L"needle", L"two needles").failure_message());
2656}
2657
shiqian4b6829f2008-07-03 22:38:12 +00002658// Tests that IsNotSubstring returns the correct result when the input
2659// argument type is ::std::string.
2660TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002661 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2662 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2663}
2664
2665// Tests that IsNotSubstring() generates the correct message when the input
2666// argument type is ::std::string.
2667TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2668 EXPECT_STREQ("Value of: needle_expr\n"
2669 " Actual: \"needle\"\n"
2670 "Expected: not a substring of haystack_expr\n"
2671 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002672 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002673 "needle_expr", "haystack_expr",
2674 ::std::string("needle"), "two needles").failure_message());
2675}
2676
shiqian4b6829f2008-07-03 22:38:12 +00002677#if GTEST_HAS_STD_WSTRING
2678
2679// Tests that IsNotSubstring returns the correct result when the input
2680// argument type is ::std::wstring.
2681TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002682 EXPECT_FALSE(
2683 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2684 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2685}
2686
2687#endif // GTEST_HAS_STD_WSTRING
2688
2689// Tests floating-point assertions.
2690
2691template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002692class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002693 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002694
2695 // Pre-calculated numbers to be used by the tests.
2696 struct TestValues {
2697 RawType close_to_positive_zero;
2698 RawType close_to_negative_zero;
2699 RawType further_from_negative_zero;
2700
2701 RawType close_to_one;
2702 RawType further_from_one;
2703
2704 RawType infinity;
2705 RawType close_to_infinity;
2706 RawType further_from_infinity;
2707
2708 RawType nan1;
2709 RawType nan2;
2710 };
2711
shiqian4b6829f2008-07-03 22:38:12 +00002712 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2713 typedef typename Floating::Bits Bits;
2714
2715 virtual void SetUp() {
2716 const size_t max_ulps = Floating::kMaxUlps;
2717
2718 // The bits that represent 0.0.
2719 const Bits zero_bits = Floating(0).bits();
2720
2721 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002722 values_.close_to_positive_zero = Floating::ReinterpretBits(
2723 zero_bits + max_ulps/2);
2724 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002725 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002726 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002727 zero_bits + max_ulps + 1 - max_ulps/2);
2728
2729 // The bits that represent 1.0.
2730 const Bits one_bits = Floating(1).bits();
2731
2732 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002733 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2734 values_.further_from_one = Floating::ReinterpretBits(
2735 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002736
2737 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002738 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002739
2740 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002741 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002742
2743 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002744 values_.close_to_infinity = Floating::ReinterpretBits(
2745 infinity_bits - max_ulps);
2746 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002747 infinity_bits - max_ulps - 1);
2748
zhanyong.wan98efcc42009-04-28 00:28:09 +00002749 // Makes some NAN's. Sets the most significant bit of the fraction so that
2750 // our NaN's are quiet; trying to process a signaling NaN would raise an
2751 // exception if our environment enables floating point exceptions.
2752 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2753 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2754 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2755 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002756 }
2757
2758 void TestSize() {
2759 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2760 }
2761
zhanyong.wan98efcc42009-04-28 00:28:09 +00002762 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002763};
2764
2765template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002766typename FloatingPointTest<RawType>::TestValues
2767 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002768
2769// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2770typedef FloatingPointTest<float> FloatTest;
2771
2772// Tests that the size of Float::Bits matches the size of float.
2773TEST_F(FloatTest, Size) {
2774 TestSize();
2775}
2776
2777// Tests comparing with +0 and -0.
2778TEST_F(FloatTest, Zeros) {
2779 EXPECT_FLOAT_EQ(0.0, -0.0);
2780 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2781 "1.0");
2782 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2783 "1.5");
2784}
2785
2786// Tests comparing numbers close to 0.
2787//
2788// This ensures that *_FLOAT_EQ handles the sign correctly and no
2789// overflow occurs when comparing numbers whose absolute value is very
2790// small.
2791TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002792 // In C++Builder, names within local classes (such as used by
2793 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2794 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002795 // We use the assignment syntax since some compilers, like Sun Studio,
2796 // don't allow initializing references using construction syntax
2797 // (parentheses).
2798 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002799
2800 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2801 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2802 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002803
2804 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002805 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2806 v.further_from_negative_zero);
2807 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002808}
2809
2810// Tests comparing numbers close to each other.
2811TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002812 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2813 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2814 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002815}
2816
2817// Tests comparing numbers far apart.
2818TEST_F(FloatTest, LargeDiff) {
2819 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2820 "3.0");
2821}
2822
2823// Tests comparing with infinity.
2824//
2825// This ensures that no overflow occurs when comparing numbers whose
2826// absolute value is very large.
2827TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002828 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2829 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002830#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002831 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002832 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2833 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002834
zhanyong.wan98efcc42009-04-28 00:28:09 +00002835 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002836 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002837 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2838 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002839#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002840}
2841
2842// Tests that comparing with NAN always returns false.
2843TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002844#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002845// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002846
zhanyong.wan98efcc42009-04-28 00:28:09 +00002847 // In C++Builder, names within local classes (such as used by
2848 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2849 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002850 // We use the assignment syntax since some compilers, like Sun Studio,
2851 // don't allow initializing references using construction syntax
2852 // (parentheses).
2853 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002854
2855 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2856 "v.nan1");
2857 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2858 "v.nan2");
2859 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2860 "v.nan1");
2861
2862 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2863 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002864#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002865}
2866
2867// Tests that *_FLOAT_EQ are reflexive.
2868TEST_F(FloatTest, Reflexive) {
2869 EXPECT_FLOAT_EQ(0.0, 0.0);
2870 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002871 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002872}
2873
2874// Tests that *_FLOAT_EQ are commutative.
2875TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002876 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2877 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002878
zhanyong.wan98efcc42009-04-28 00:28:09 +00002879 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2880 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002881 "1.0");
2882}
2883
2884// Tests EXPECT_NEAR.
2885TEST_F(FloatTest, EXPECT_NEAR) {
2886 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2887 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002888 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2889 "The difference between 1.0f and 1.5f is 0.5, "
2890 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002891 // To work around a bug in gcc 2.95.0, there is intentionally no
2892 // space after the first comma in the previous line.
2893}
2894
2895// Tests ASSERT_NEAR.
2896TEST_F(FloatTest, ASSERT_NEAR) {
2897 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2898 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002899 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2900 "The difference between 1.0f and 1.5f is 0.5, "
2901 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002902 // To work around a bug in gcc 2.95.0, there is intentionally no
2903 // space after the first comma in the previous line.
2904}
2905
2906// Tests the cases where FloatLE() should succeed.
2907TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002908 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2909 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002910
2911 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002912 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002913}
2914
2915// Tests the cases where FloatLE() should fail.
2916TEST_F(FloatTest, FloatLEFails) {
2917 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002918 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002919 "(2.0f) <= (1.0f)");
2920
2921 // or by a small yet non-negligible margin,
2922 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002923 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2924 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002925
zhanyong.wan98efcc42009-04-28 00:28:09 +00002926#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002927 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002928 // C++Builder gives bad results for ordered comparisons involving NaNs
2929 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002930 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002931 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2932 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002933 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002934 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2935 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002936 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002937 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2938 }, "(values_.nan1) <= (values_.nan1)");
2939#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002940}
2941
2942// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2943typedef FloatingPointTest<double> DoubleTest;
2944
2945// Tests that the size of Double::Bits matches the size of double.
2946TEST_F(DoubleTest, Size) {
2947 TestSize();
2948}
2949
2950// Tests comparing with +0 and -0.
2951TEST_F(DoubleTest, Zeros) {
2952 EXPECT_DOUBLE_EQ(0.0, -0.0);
2953 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2954 "1.0");
2955 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2956 "1.0");
2957}
2958
2959// Tests comparing numbers close to 0.
2960//
2961// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2962// overflow occurs when comparing numbers whose absolute value is very
2963// small.
2964TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002965 // In C++Builder, names within local classes (such as used by
2966 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2967 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002968 // We use the assignment syntax since some compilers, like Sun Studio,
2969 // don't allow initializing references using construction syntax
2970 // (parentheses).
2971 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002972
2973 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2974 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2975 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002976
2977 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002978 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2979 v.further_from_negative_zero);
2980 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002981}
2982
2983// Tests comparing numbers close to each other.
2984TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002985 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2986 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2987 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002988}
2989
2990// Tests comparing numbers far apart.
2991TEST_F(DoubleTest, LargeDiff) {
2992 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2993 "3.0");
2994}
2995
2996// Tests comparing with infinity.
2997//
2998// This ensures that no overflow occurs when comparing numbers whose
2999// absolute value is very large.
3000TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003001 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3002 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003003#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003004 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003005 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3006 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00003007
3008 // This is interesting as the representations of infinity_ and nan1_
3009 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003010 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3011 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003012#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003013}
3014
3015// Tests that comparing with NAN always returns false.
3016TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003017#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00003018 // In C++Builder, names within local classes (such as used by
3019 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3020 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00003021 // We use the assignment syntax since some compilers, like Sun Studio,
3022 // don't allow initializing references using construction syntax
3023 // (parentheses).
3024 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00003025
shiqiane44602e2008-10-11 07:20:02 +00003026 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003027 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3028 "v.nan1");
3029 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3030 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3031 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3032 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003033#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003034}
3035
3036// Tests that *_DOUBLE_EQ are reflexive.
3037TEST_F(DoubleTest, Reflexive) {
3038 EXPECT_DOUBLE_EQ(0.0, 0.0);
3039 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003040#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003041 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003042 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003043#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003044}
3045
3046// Tests that *_DOUBLE_EQ are commutative.
3047TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003048 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3049 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00003050
zhanyong.wan98efcc42009-04-28 00:28:09 +00003051 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3052 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3053 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00003054}
3055
3056// Tests EXPECT_NEAR.
3057TEST_F(DoubleTest, EXPECT_NEAR) {
3058 EXPECT_NEAR(-1.0, -1.1, 0.2);
3059 EXPECT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003060 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3061 "The difference between 1.0 and 1.5 is 0.5, "
3062 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003063 // To work around a bug in gcc 2.95.0, there is intentionally no
3064 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003065}
3066
3067// Tests ASSERT_NEAR.
3068TEST_F(DoubleTest, ASSERT_NEAR) {
3069 ASSERT_NEAR(-1.0, -1.1, 0.2);
3070 ASSERT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003071 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3072 "The difference between 1.0 and 1.5 is 0.5, "
3073 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003074 // To work around a bug in gcc 2.95.0, there is intentionally no
3075 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003076}
3077
3078// Tests the cases where DoubleLE() should succeed.
3079TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00003080 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3081 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00003082
3083 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003084 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00003085}
3086
3087// Tests the cases where DoubleLE() should fail.
3088TEST_F(DoubleTest, DoubleLEFails) {
3089 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003090 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003091 "(2.0) <= (1.0)");
3092
3093 // or by a small yet non-negligible margin,
3094 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003095 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3096 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00003097
zhanyong.wan98efcc42009-04-28 00:28:09 +00003098#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003099 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003100 // C++Builder gives bad results for ordered comparisons involving NaNs
3101 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003102 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003103 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3104 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003105 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003106 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3107 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003108 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003109 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3110 }, "(values_.nan1) <= (values_.nan1)");
3111#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003112}
3113
3114
3115// Verifies that a test or test case whose name starts with DISABLED_ is
3116// not run.
3117
3118// A test whose name starts with DISABLED_.
3119// Should not run.
3120TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3121 FAIL() << "Unexpected failure: Disabled test should not be run.";
3122}
3123
3124// A test whose name does not start with DISABLED_.
3125// Should run.
3126TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3127 EXPECT_EQ(1, 1);
3128}
3129
3130// A test case whose name starts with DISABLED_.
3131// Should not run.
3132TEST(DISABLED_TestCase, TestShouldNotRun) {
3133 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3134}
3135
3136// A test case and test whose names start with DISABLED_.
3137// Should not run.
3138TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3139 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3140}
3141
3142// Check that when all tests in a test case are disabled, SetupTestCase() and
3143// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00003144class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00003145 protected:
3146 static void SetUpTestCase() {
3147 FAIL() << "Unexpected failure: All tests disabled in test case. "
3148 "SetupTestCase() should not be called.";
3149 }
3150
3151 static void TearDownTestCase() {
3152 FAIL() << "Unexpected failure: All tests disabled in test case. "
3153 "TearDownTestCase() should not be called.";
3154 }
3155};
3156
3157TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3158 FAIL() << "Unexpected failure: Disabled test should not be run.";
3159}
3160
3161TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3162 FAIL() << "Unexpected failure: Disabled test should not be run.";
3163}
3164
shiqiane8ff1482008-09-08 17:55:52 +00003165// Tests that disabled typed tests aren't run.
3166
zhanyong.wan4cd62602009-02-23 23:21:55 +00003167#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00003168
3169template <typename T>
3170class TypedTest : public Test {
3171};
3172
3173typedef testing::Types<int, double> NumericTypes;
3174TYPED_TEST_CASE(TypedTest, NumericTypes);
3175
3176TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3177 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3178}
3179
3180template <typename T>
3181class DISABLED_TypedTest : public Test {
3182};
3183
3184TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3185
3186TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3187 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3188}
3189
3190#endif // GTEST_HAS_TYPED_TEST
3191
3192// Tests that disabled type-parameterized tests aren't run.
3193
zhanyong.wan4cd62602009-02-23 23:21:55 +00003194#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00003195
3196template <typename T>
3197class TypedTestP : public Test {
3198};
3199
3200TYPED_TEST_CASE_P(TypedTestP);
3201
3202TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3203 FAIL() << "Unexpected failure: "
3204 << "Disabled type-parameterized test should not run.";
3205}
3206
3207REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3208
3209INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3210
3211template <typename T>
3212class DISABLED_TypedTestP : public Test {
3213};
3214
3215TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3216
3217TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3218 FAIL() << "Unexpected failure: "
3219 << "Disabled type-parameterized test should not run.";
3220}
3221
3222REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3223
3224INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3225
3226#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00003227
3228// Tests that assertion macros evaluate their arguments exactly once.
3229
shiqian760af5c2008-08-06 21:43:15 +00003230class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00003231 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003232 // This helper function is needed by the FailedASSERT_STREQ test
3233 // below. It's public to work around C++Builder's bug with scoping local
3234 // classes.
3235 static void CompareAndIncrementCharPtrs() {
3236 ASSERT_STREQ(p1_++, p2_++);
3237 }
3238
3239 // This helper function is needed by the FailedASSERT_NE test below. It's
3240 // public to work around C++Builder's bug with scoping local classes.
3241 static void CompareAndIncrementInts() {
3242 ASSERT_NE(a_++, b_++);
3243 }
3244
shiqian4b6829f2008-07-03 22:38:12 +00003245 protected:
3246 SingleEvaluationTest() {
3247 p1_ = s1_;
3248 p2_ = s2_;
3249 a_ = 0;
3250 b_ = 0;
3251 }
3252
shiqian4b6829f2008-07-03 22:38:12 +00003253 static const char* const s1_;
3254 static const char* const s2_;
3255 static const char* p1_;
3256 static const char* p2_;
3257
3258 static int a_;
3259 static int b_;
3260};
3261
3262const char* const SingleEvaluationTest::s1_ = "01234";
3263const char* const SingleEvaluationTest::s2_ = "abcde";
3264const char* SingleEvaluationTest::p1_;
3265const char* SingleEvaluationTest::p2_;
3266int SingleEvaluationTest::a_;
3267int SingleEvaluationTest::b_;
3268
3269// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3270// exactly once.
3271TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003272 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003273 "p2_++");
3274 EXPECT_EQ(s1_ + 1, p1_);
3275 EXPECT_EQ(s2_ + 1, p2_);
3276}
3277
3278// Tests that string assertion arguments are evaluated exactly once.
3279TEST_F(SingleEvaluationTest, ASSERT_STR) {
3280 // successful EXPECT_STRNE
3281 EXPECT_STRNE(p1_++, p2_++);
3282 EXPECT_EQ(s1_ + 1, p1_);
3283 EXPECT_EQ(s2_ + 1, p2_);
3284
3285 // failed EXPECT_STRCASEEQ
3286 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3287 "ignoring case");
3288 EXPECT_EQ(s1_ + 2, p1_);
3289 EXPECT_EQ(s2_ + 2, p2_);
3290}
3291
3292// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3293// once.
3294TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003295 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3296 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003297 EXPECT_EQ(1, a_);
3298 EXPECT_EQ(1, b_);
3299}
3300
3301// Tests that assertion arguments are evaluated exactly once.
3302TEST_F(SingleEvaluationTest, OtherCases) {
3303 // successful EXPECT_TRUE
3304 EXPECT_TRUE(0 == a_++); // NOLINT
3305 EXPECT_EQ(1, a_);
3306
3307 // failed EXPECT_TRUE
3308 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3309 EXPECT_EQ(2, a_);
3310
3311 // successful EXPECT_GT
3312 EXPECT_GT(a_++, b_++);
3313 EXPECT_EQ(3, a_);
3314 EXPECT_EQ(1, b_);
3315
3316 // failed EXPECT_LT
3317 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3318 EXPECT_EQ(4, a_);
3319 EXPECT_EQ(2, b_);
3320
3321 // successful ASSERT_TRUE
3322 ASSERT_TRUE(0 < a_++); // NOLINT
3323 EXPECT_EQ(5, a_);
3324
3325 // successful ASSERT_GT
3326 ASSERT_GT(a_++, b_++);
3327 EXPECT_EQ(6, a_);
3328 EXPECT_EQ(3, b_);
3329}
3330
shiqian9204c8e2008-09-12 20:57:22 +00003331#if GTEST_HAS_EXCEPTIONS
3332
3333void ThrowAnInteger() {
3334 throw 1;
3335}
3336
3337// Tests that assertion arguments are evaluated exactly once.
3338TEST_F(SingleEvaluationTest, ExceptionTests) {
3339 // successful EXPECT_THROW
3340 EXPECT_THROW({ // NOLINT
3341 a_++;
3342 ThrowAnInteger();
3343 }, int);
3344 EXPECT_EQ(1, a_);
3345
3346 // failed EXPECT_THROW, throws different
3347 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3348 a_++;
3349 ThrowAnInteger();
3350 }, bool), "throws a different type");
3351 EXPECT_EQ(2, a_);
3352
3353 // failed EXPECT_THROW, throws nothing
3354 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3355 EXPECT_EQ(3, a_);
3356
3357 // successful EXPECT_NO_THROW
3358 EXPECT_NO_THROW(a_++);
3359 EXPECT_EQ(4, a_);
3360
3361 // failed EXPECT_NO_THROW
3362 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3363 a_++;
3364 ThrowAnInteger();
3365 }), "it throws");
3366 EXPECT_EQ(5, a_);
3367
3368 // successful EXPECT_ANY_THROW
3369 EXPECT_ANY_THROW({ // NOLINT
3370 a_++;
3371 ThrowAnInteger();
3372 });
3373 EXPECT_EQ(6, a_);
3374
3375 // failed EXPECT_ANY_THROW
3376 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3377 EXPECT_EQ(7, a_);
3378}
3379
3380#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003381
shiqiane44602e2008-10-11 07:20:02 +00003382// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3383class NoFatalFailureTest : public Test {
3384 protected:
3385 void Succeeds() {}
3386 void FailsNonFatal() {
3387 ADD_FAILURE() << "some non-fatal failure";
3388 }
3389 void Fails() {
3390 FAIL() << "some fatal failure";
3391 }
3392
3393 void DoAssertNoFatalFailureOnFails() {
3394 ASSERT_NO_FATAL_FAILURE(Fails());
3395 ADD_FAILURE() << "shold not reach here.";
3396 }
3397
3398 void DoExpectNoFatalFailureOnFails() {
3399 EXPECT_NO_FATAL_FAILURE(Fails());
3400 ADD_FAILURE() << "other failure";
3401 }
3402};
3403
3404TEST_F(NoFatalFailureTest, NoFailure) {
3405 EXPECT_NO_FATAL_FAILURE(Succeeds());
3406 ASSERT_NO_FATAL_FAILURE(Succeeds());
3407}
3408
3409TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3410 EXPECT_NONFATAL_FAILURE(
3411 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3412 "some non-fatal failure");
3413 EXPECT_NONFATAL_FAILURE(
3414 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3415 "some non-fatal failure");
3416}
3417
3418TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3419 TestPartResultArray gtest_failures;
3420 {
3421 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3422 DoAssertNoFatalFailureOnFails();
3423 }
3424 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003425 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003426 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003427 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003428 gtest_failures.GetTestPartResult(1).type());
3429 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3430 gtest_failures.GetTestPartResult(0).message());
3431 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3432 gtest_failures.GetTestPartResult(1).message());
3433}
3434
3435TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3436 TestPartResultArray gtest_failures;
3437 {
3438 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3439 DoExpectNoFatalFailureOnFails();
3440 }
3441 ASSERT_EQ(3, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003442 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003443 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003444 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003445 gtest_failures.GetTestPartResult(1).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003446 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003447 gtest_failures.GetTestPartResult(2).type());
3448 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3449 gtest_failures.GetTestPartResult(0).message());
3450 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3451 gtest_failures.GetTestPartResult(1).message());
3452 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3453 gtest_failures.GetTestPartResult(2).message());
3454}
3455
3456TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3457 TestPartResultArray gtest_failures;
3458 {
3459 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3460 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3461 }
3462 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003463 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003464 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003465 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003466 gtest_failures.GetTestPartResult(1).type());
3467 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3468 gtest_failures.GetTestPartResult(0).message());
3469 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3470 gtest_failures.GetTestPartResult(1).message());
3471}
3472
shiqian4b6829f2008-07-03 22:38:12 +00003473// Tests non-string assertions.
3474
3475// Tests EqFailure(), used for implementing *EQ* assertions.
3476TEST(AssertionTest, EqFailure) {
3477 const String foo_val("5"), bar_val("6");
3478 const String msg1(
3479 EqFailure("foo", "bar", foo_val, bar_val, false)
3480 .failure_message());
3481 EXPECT_STREQ(
3482 "Value of: bar\n"
3483 " Actual: 6\n"
3484 "Expected: foo\n"
3485 "Which is: 5",
3486 msg1.c_str());
3487
3488 const String msg2(
3489 EqFailure("foo", "6", foo_val, bar_val, false)
3490 .failure_message());
3491 EXPECT_STREQ(
3492 "Value of: 6\n"
3493 "Expected: foo\n"
3494 "Which is: 5",
3495 msg2.c_str());
3496
3497 const String msg3(
3498 EqFailure("5", "bar", foo_val, bar_val, false)
3499 .failure_message());
3500 EXPECT_STREQ(
3501 "Value of: bar\n"
3502 " Actual: 6\n"
3503 "Expected: 5",
3504 msg3.c_str());
3505
3506 const String msg4(
3507 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3508 EXPECT_STREQ(
3509 "Value of: 6\n"
3510 "Expected: 5",
3511 msg4.c_str());
3512
3513 const String msg5(
3514 EqFailure("foo", "bar",
3515 String("\"x\""), String("\"y\""),
3516 true).failure_message());
3517 EXPECT_STREQ(
3518 "Value of: bar\n"
3519 " Actual: \"y\"\n"
3520 "Expected: foo (ignoring case)\n"
3521 "Which is: \"x\"",
3522 msg5.c_str());
3523}
3524
3525// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3526TEST(AssertionTest, AppendUserMessage) {
3527 const String foo("foo");
3528
shiqian760af5c2008-08-06 21:43:15 +00003529 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003530 EXPECT_STREQ("foo",
3531 AppendUserMessage(foo, msg).c_str());
3532
3533 msg << "bar";
3534 EXPECT_STREQ("foo\nbar",
3535 AppendUserMessage(foo, msg).c_str());
3536}
3537
zhanyong.wan98efcc42009-04-28 00:28:09 +00003538#ifdef __BORLANDC__
3539// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00003540# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00003541#endif
3542
shiqian4b6829f2008-07-03 22:38:12 +00003543// Tests ASSERT_TRUE.
3544TEST(AssertionTest, ASSERT_TRUE) {
3545 ASSERT_TRUE(2 > 1); // NOLINT
3546 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3547 "2 < 1");
3548}
3549
vladlosevfbd53a52009-10-20 21:03:10 +00003550// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3551TEST(AssertionTest, AssertTrueWithAssertionResult) {
3552 ASSERT_TRUE(ResultIsEven(2));
zhanyong.waned1042b2011-03-05 08:04:01 +00003553#ifndef __BORLANDC__
3554 // ICE's in C++Builder.
vladlosevfbd53a52009-10-20 21:03:10 +00003555 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3556 "Value of: ResultIsEven(3)\n"
3557 " Actual: false (3 is odd)\n"
3558 "Expected: true");
vladlosevd6b49412010-04-07 05:32:34 +00003559#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003560 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3561 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3562 "Value of: ResultIsEvenNoExplanation(3)\n"
3563 " Actual: false (3 is odd)\n"
3564 "Expected: true");
3565}
3566
shiqian4b6829f2008-07-03 22:38:12 +00003567// Tests ASSERT_FALSE.
3568TEST(AssertionTest, ASSERT_FALSE) {
3569 ASSERT_FALSE(2 < 1); // NOLINT
3570 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3571 "Value of: 2 > 1\n"
3572 " Actual: true\n"
3573 "Expected: false");
3574}
3575
vladlosevfbd53a52009-10-20 21:03:10 +00003576// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3577TEST(AssertionTest, AssertFalseWithAssertionResult) {
3578 ASSERT_FALSE(ResultIsEven(3));
zhanyong.waned1042b2011-03-05 08:04:01 +00003579#ifndef __BORLANDC__
3580 // ICE's in C++Builder.
vladlosevfbd53a52009-10-20 21:03:10 +00003581 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3582 "Value of: ResultIsEven(2)\n"
3583 " Actual: true (2 is even)\n"
3584 "Expected: false");
vladlosevd6b49412010-04-07 05:32:34 +00003585#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003586 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3587 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3588 "Value of: ResultIsEvenNoExplanation(2)\n"
3589 " Actual: true\n"
3590 "Expected: false");
3591}
3592
zhanyong.wan98efcc42009-04-28 00:28:09 +00003593#ifdef __BORLANDC__
3594// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00003595# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00003596#endif
3597
shiqian4b6829f2008-07-03 22:38:12 +00003598// Tests using ASSERT_EQ on double values. The purpose is to make
3599// sure that the specialization we did for integer and anonymous enums
3600// isn't used for double arguments.
3601TEST(ExpectTest, ASSERT_EQ_Double) {
3602 // A success.
3603 ASSERT_EQ(5.6, 5.6);
3604
3605 // A failure.
3606 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3607 "5.1");
3608}
3609
3610// Tests ASSERT_EQ.
3611TEST(AssertionTest, ASSERT_EQ) {
3612 ASSERT_EQ(5, 2 + 3);
3613 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3614 "Value of: 2*3\n"
3615 " Actual: 6\n"
3616 "Expected: 5");
3617}
3618
3619// Tests ASSERT_EQ(NULL, pointer).
vladlosev5147b452010-03-17 18:22:59 +00003620#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003621TEST(AssertionTest, ASSERT_EQ_NULL) {
3622 // A success.
3623 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003624 // Some older GCC versions may issue a spurious waring in this or the next
3625 // assertion statement. This warning should not be suppressed with
3626 // static_cast since the test verifies the ability to use bare NULL as the
3627 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003628 ASSERT_EQ(NULL, p);
3629
3630 // A failure.
3631 static int n = 0;
3632 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3633 "Value of: &n\n");
3634}
vladlosev5147b452010-03-17 18:22:59 +00003635#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003636
3637// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3638// treated as a null pointer by the compiler, we need to make sure
3639// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3640// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3641TEST(ExpectTest, ASSERT_EQ_0) {
3642 int n = 0;
3643
3644 // A success.
3645 ASSERT_EQ(0, n);
3646
3647 // A failure.
3648 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3649 "Expected: 0");
3650}
3651
3652// Tests ASSERT_NE.
3653TEST(AssertionTest, ASSERT_NE) {
3654 ASSERT_NE(6, 7);
3655 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3656 "Expected: ('a') != ('a'), "
3657 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3658}
3659
3660// Tests ASSERT_LE.
3661TEST(AssertionTest, ASSERT_LE) {
3662 ASSERT_LE(2, 3);
3663 ASSERT_LE(2, 2);
3664 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3665 "Expected: (2) <= (0), actual: 2 vs 0");
3666}
3667
3668// Tests ASSERT_LT.
3669TEST(AssertionTest, ASSERT_LT) {
3670 ASSERT_LT(2, 3);
3671 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3672 "Expected: (2) < (2), actual: 2 vs 2");
3673}
3674
3675// Tests ASSERT_GE.
3676TEST(AssertionTest, ASSERT_GE) {
3677 ASSERT_GE(2, 1);
3678 ASSERT_GE(2, 2);
3679 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3680 "Expected: (2) >= (3), actual: 2 vs 3");
3681}
3682
3683// Tests ASSERT_GT.
3684TEST(AssertionTest, ASSERT_GT) {
3685 ASSERT_GT(2, 1);
3686 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3687 "Expected: (2) > (2), actual: 2 vs 2");
3688}
3689
shiqian9204c8e2008-09-12 20:57:22 +00003690#if GTEST_HAS_EXCEPTIONS
3691
zhanyong.wanac60cef2009-02-08 04:53:35 +00003692void ThrowNothing() {}
3693
shiqian9204c8e2008-09-12 20:57:22 +00003694// Tests ASSERT_THROW.
3695TEST(AssertionTest, ASSERT_THROW) {
3696 ASSERT_THROW(ThrowAnInteger(), int);
vladlosevd6b49412010-04-07 05:32:34 +00003697
zhanyong.wan733a54a2011-02-22 22:08:59 +00003698# ifndef __BORLANDC__
3699
vladlosevd6b49412010-04-07 05:32:34 +00003700 // ICE's in C++Builder 2007 and 2009.
zhanyong.wanac60cef2009-02-08 04:53:35 +00003701 EXPECT_FATAL_FAILURE(
3702 ASSERT_THROW(ThrowAnInteger(), bool),
3703 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3704 " Actual: it throws a different type.");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003705# endif
vladlosevd6b49412010-04-07 05:32:34 +00003706
zhanyong.wanac60cef2009-02-08 04:53:35 +00003707 EXPECT_FATAL_FAILURE(
3708 ASSERT_THROW(ThrowNothing(), bool),
3709 "Expected: ThrowNothing() throws an exception of type bool.\n"
3710 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003711}
3712
3713// Tests ASSERT_NO_THROW.
3714TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003715 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003716 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003717 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003718 "\n Actual: it throws.");
3719}
3720
3721// Tests ASSERT_ANY_THROW.
3722TEST(AssertionTest, ASSERT_ANY_THROW) {
3723 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003724 EXPECT_FATAL_FAILURE(
3725 ASSERT_ANY_THROW(ThrowNothing()),
3726 "Expected: ThrowNothing() throws an exception.\n"
3727 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003728}
3729
3730#endif // GTEST_HAS_EXCEPTIONS
3731
shiqian4b6829f2008-07-03 22:38:12 +00003732// Makes sure we deal with the precedence of <<. This test should
3733// compile.
3734TEST(AssertionTest, AssertPrecedence) {
3735 ASSERT_EQ(1 < 2, true);
zhanyong.wan5e255e02011-01-10 18:17:59 +00003736 bool false_value = false;
3737 ASSERT_EQ(true && false_value, false);
shiqian4b6829f2008-07-03 22:38:12 +00003738}
3739
3740// A subroutine used by the following test.
3741void TestEq1(int x) {
3742 ASSERT_EQ(1, x);
3743}
3744
3745// Tests calling a test subroutine that's not part of a fixture.
3746TEST(AssertionTest, NonFixtureSubroutine) {
3747 EXPECT_FATAL_FAILURE(TestEq1(2),
3748 "Value of: x");
3749}
3750
3751// An uncopyable class.
3752class Uncopyable {
3753 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00003754 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqian4b6829f2008-07-03 22:38:12 +00003755
3756 int value() const { return value_; }
3757 bool operator==(const Uncopyable& rhs) const {
3758 return value() == rhs.value();
3759 }
3760 private:
3761 // This constructor deliberately has no implementation, as we don't
3762 // want this class to be copyable.
3763 Uncopyable(const Uncopyable&); // NOLINT
3764
3765 int value_;
3766};
3767
3768::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3769 return os << value.value();
3770}
3771
3772
3773bool IsPositiveUncopyable(const Uncopyable& x) {
3774 return x.value() > 0;
3775}
3776
3777// A subroutine used by the following test.
3778void TestAssertNonPositive() {
3779 Uncopyable y(-1);
3780 ASSERT_PRED1(IsPositiveUncopyable, y);
3781}
3782// A subroutine used by the following test.
3783void TestAssertEqualsUncopyable() {
3784 Uncopyable x(5);
3785 Uncopyable y(-1);
3786 ASSERT_EQ(x, y);
3787}
3788
3789// Tests that uncopyable objects can be used in assertions.
3790TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3791 Uncopyable x(5);
3792 ASSERT_PRED1(IsPositiveUncopyable, x);
3793 ASSERT_EQ(x, x);
3794 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3795 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3796 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3797 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3798}
3799
3800// Tests that uncopyable objects can be used in expects.
3801TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3802 Uncopyable x(5);
3803 EXPECT_PRED1(IsPositiveUncopyable, x);
3804 Uncopyable y(-1);
3805 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3806 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3807 EXPECT_EQ(x, x);
3808 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3809 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3810}
3811
zhanyong.wan739d3042010-08-09 18:19:15 +00003812enum NamedEnum {
3813 kE1 = 0,
zhanyong.wan66d8d6b2011-03-05 01:16:12 +00003814 kE2 = 1
zhanyong.wan739d3042010-08-09 18:19:15 +00003815};
3816
3817TEST(AssertionTest, NamedEnum) {
3818 EXPECT_EQ(kE1, kE1);
3819 EXPECT_LT(kE1, kE2);
3820 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3821 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
3822}
shiqian4b6829f2008-07-03 22:38:12 +00003823
3824// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003825// anonymous enums in assertions. Therefore the following test is not
3826// done on Mac.
vladlosev673a0cb2010-02-03 02:27:02 +00003827// Sun Studio also rejects this code.
3828#if !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian4b6829f2008-07-03 22:38:12 +00003829
3830// Tests using assertions with anonymous enums.
3831enum {
zhanyong.wan739d3042010-08-09 18:19:15 +00003832 kCaseA = -1,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003833
3834# if GTEST_OS_LINUX
3835
shiqian4b6829f2008-07-03 22:38:12 +00003836 // We want to test the case where the size of the anonymous enum is
3837 // larger than sizeof(int), to make sure our implementation of the
3838 // assertions doesn't truncate the enums. However, MSVC
3839 // (incorrectly) doesn't allow an enum value to exceed the range of
3840 // an int, so this has to be conditionally compiled.
3841 //
zhanyong.wan739d3042010-08-09 18:19:15 +00003842 // On Linux, kCaseB and kCaseA have the same value when truncated to
shiqian4b6829f2008-07-03 22:38:12 +00003843 // int size. We want to test whether this will confuse the
3844 // assertions.
zhanyong.wan739d3042010-08-09 18:19:15 +00003845 kCaseB = testing::internal::kMaxBiggestInt,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003846
3847# else
3848
zhanyong.wan739d3042010-08-09 18:19:15 +00003849 kCaseB = INT_MAX,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003850
3851# endif // GTEST_OS_LINUX
3852
zhanyong.wan739d3042010-08-09 18:19:15 +00003853 kCaseC = 42,
shiqian4b6829f2008-07-03 22:38:12 +00003854};
3855
3856TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan733a54a2011-02-22 22:08:59 +00003857# if GTEST_OS_LINUX
3858
zhanyong.wan739d3042010-08-09 18:19:15 +00003859 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
zhanyong.wan733a54a2011-02-22 22:08:59 +00003860
3861# endif // GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003862
zhanyong.wan739d3042010-08-09 18:19:15 +00003863 EXPECT_EQ(kCaseA, kCaseA);
3864 EXPECT_NE(kCaseA, kCaseB);
3865 EXPECT_LT(kCaseA, kCaseB);
3866 EXPECT_LE(kCaseA, kCaseB);
3867 EXPECT_GT(kCaseB, kCaseA);
3868 EXPECT_GE(kCaseA, kCaseA);
3869 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3870 "(kCaseA) >= (kCaseB)");
3871 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3872 "-1 vs 42");
shiqian4b6829f2008-07-03 22:38:12 +00003873
zhanyong.wan739d3042010-08-09 18:19:15 +00003874 ASSERT_EQ(kCaseA, kCaseA);
3875 ASSERT_NE(kCaseA, kCaseB);
3876 ASSERT_LT(kCaseA, kCaseB);
3877 ASSERT_LE(kCaseA, kCaseB);
3878 ASSERT_GT(kCaseB, kCaseA);
3879 ASSERT_GE(kCaseA, kCaseA);
zhanyong.waned1042b2011-03-05 08:04:01 +00003880
3881# ifndef __BORLANDC__
3882
3883 // ICE's in C++Builder.
zhanyong.wan739d3042010-08-09 18:19:15 +00003884 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3885 "Value of: kCaseB");
3886 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3887 "Actual: 42");
zhanyong.waned1042b2011-03-05 08:04:01 +00003888# endif
3889
zhanyong.wan739d3042010-08-09 18:19:15 +00003890 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3891 "Which is: -1");
shiqian4b6829f2008-07-03 22:38:12 +00003892}
3893
vladlosev673a0cb2010-02-03 02:27:02 +00003894#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian4b6829f2008-07-03 22:38:12 +00003895
zhanyong.wan4cd62602009-02-23 23:21:55 +00003896#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003897
3898static HRESULT UnexpectedHRESULTFailure() {
3899 return E_UNEXPECTED;
3900}
3901
3902static HRESULT OkHRESULTSuccess() {
3903 return S_OK;
3904}
3905
3906static HRESULT FalseHRESULTSuccess() {
3907 return S_FALSE;
3908}
3909
3910// HRESULT assertion tests test both zero and non-zero
3911// success codes as well as failure message for each.
3912//
3913// Windows CE doesn't support message texts.
3914TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3915 EXPECT_HRESULT_SUCCEEDED(S_OK);
3916 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3917
shiqian4b6829f2008-07-03 22:38:12 +00003918 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003919 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3920 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003921}
3922
3923TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3924 ASSERT_HRESULT_SUCCEEDED(S_OK);
3925 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3926
shiqian4b6829f2008-07-03 22:38:12 +00003927 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003928 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3929 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003930}
3931
3932TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3933 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3934
shiqian4b6829f2008-07-03 22:38:12 +00003935 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003936 "Expected: (OkHRESULTSuccess()) fails.\n"
3937 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00003938 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003939 "Expected: (FalseHRESULTSuccess()) fails.\n"
3940 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003941}
3942
3943TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3944 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3945
zhanyong.wan733a54a2011-02-22 22:08:59 +00003946# ifndef __BORLANDC__
3947
zhanyong.wan98efcc42009-04-28 00:28:09 +00003948 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003949 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003950 "Expected: (OkHRESULTSuccess()) fails.\n"
3951 " Actual: 0x00000000");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003952# endif
3953
shiqian4b6829f2008-07-03 22:38:12 +00003954 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003955 "Expected: (FalseHRESULTSuccess()) fails.\n"
3956 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003957}
3958
3959// Tests that streaming to the HRESULT macros works.
3960TEST(HRESULTAssertionTest, Streaming) {
3961 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3962 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3963 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3964 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3965
3966 EXPECT_NONFATAL_FAILURE(
3967 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3968 "expected failure");
3969
zhanyong.wan733a54a2011-02-22 22:08:59 +00003970# ifndef __BORLANDC__
3971
zhanyong.wan98efcc42009-04-28 00:28:09 +00003972 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003973 EXPECT_FATAL_FAILURE(
3974 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3975 "expected failure");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003976# endif
shiqian4b6829f2008-07-03 22:38:12 +00003977
3978 EXPECT_NONFATAL_FAILURE(
3979 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3980 "expected failure");
3981
3982 EXPECT_FATAL_FAILURE(
3983 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3984 "expected failure");
3985}
3986
zhanyong.wan4cd62602009-02-23 23:21:55 +00003987#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003988
zhanyong.wan98efcc42009-04-28 00:28:09 +00003989#ifdef __BORLANDC__
3990// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00003991# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00003992#endif
3993
shiqian4b6829f2008-07-03 22:38:12 +00003994// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003995TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003996 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00003997 ASSERT_TRUE(false) << "This should never be executed; "
3998 "It's a compilation test only.";
3999
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004000 if (AlwaysTrue())
shiqian4b6829f2008-07-03 22:38:12 +00004001 EXPECT_FALSE(false);
4002 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004003 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00004004
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004005 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00004006 ASSERT_LT(1, 3);
4007
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004008 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004009 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00004010 else
4011 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00004012}
shiqian9204c8e2008-09-12 20:57:22 +00004013
4014#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00004015// Tests that the compiler will not complain about unreachable code in the
4016// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4017TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4018 int n = 0;
4019
4020 EXPECT_THROW(throw 1, int);
4021 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4022 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4023 EXPECT_NO_THROW(n++);
4024 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4025 EXPECT_ANY_THROW(throw 1);
4026 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4027}
4028
shiqiane44602e2008-10-11 07:20:02 +00004029TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004030 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004031 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00004032
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004033 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004034 EXPECT_THROW(ThrowAnInteger(), int);
4035 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004036 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004037
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004038 if (AlwaysFalse())
shiqian9204c8e2008-09-12 20:57:22 +00004039 EXPECT_NO_THROW(ThrowAnInteger());
4040
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004041 if (AlwaysTrue())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004042 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004043 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004044 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004045
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004046 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004047 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004048
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004049 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004050 EXPECT_ANY_THROW(ThrowAnInteger());
4051 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004052 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004053}
shiqian9204c8e2008-09-12 20:57:22 +00004054#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00004055
4056TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004057 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004058 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4059 << "It's a compilation test only.";
4060 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004061 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004062
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004063 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004064 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4065 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004066 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004067
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004068 if (AlwaysTrue())
shiqiane44602e2008-10-11 07:20:02 +00004069 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4070 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004071 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004072
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004073 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004074 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004075 else
4076 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00004077}
4078
4079// Tests that the assertion macros work well with switch statements.
4080TEST(AssertionSyntaxTest, WorksWithSwitch) {
4081 switch (0) {
4082 case 1:
4083 break;
4084 default:
4085 ASSERT_TRUE(true);
4086 }
4087
4088 switch (0)
4089 case 0:
4090 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4091
4092 // Binary assertions are implemented using a different code path
4093 // than the Boolean assertions. Hence we test them separately.
4094 switch (0) {
4095 case 1:
4096 default:
4097 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4098 }
4099
4100 switch (0)
4101 case 0:
4102 EXPECT_NE(1, 2);
4103}
4104
shiqian9204c8e2008-09-12 20:57:22 +00004105#if GTEST_HAS_EXCEPTIONS
4106
4107void ThrowAString() {
4108 throw "String";
4109}
4110
4111// Test that the exception assertion macros compile and work with const
4112// type qualifier.
4113TEST(AssertionSyntaxTest, WorksWithConst) {
4114 ASSERT_THROW(ThrowAString(), const char*);
4115
4116 EXPECT_THROW(ThrowAString(), const char*);
4117}
4118
4119#endif // GTEST_HAS_EXCEPTIONS
4120
shiqian4b6829f2008-07-03 22:38:12 +00004121} // namespace
4122
shiqian4b6829f2008-07-03 22:38:12 +00004123namespace testing {
4124
4125// Tests that Google Test tracks SUCCEED*.
4126TEST(SuccessfulAssertionTest, SUCCEED) {
4127 SUCCEED();
4128 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004129 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004130}
4131
4132// Tests that Google Test doesn't track successful EXPECT_*.
4133TEST(SuccessfulAssertionTest, EXPECT) {
4134 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004135 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004136}
4137
4138// Tests that Google Test doesn't track successful EXPECT_STR*.
4139TEST(SuccessfulAssertionTest, EXPECT_STR) {
4140 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004141 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004142}
4143
4144// Tests that Google Test doesn't track successful ASSERT_*.
4145TEST(SuccessfulAssertionTest, ASSERT) {
4146 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004147 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004148}
4149
4150// Tests that Google Test doesn't track successful ASSERT_STR*.
4151TEST(SuccessfulAssertionTest, ASSERT_STR) {
4152 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004153 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004154}
4155
4156} // namespace testing
4157
4158namespace {
4159
4160// Tests EXPECT_TRUE.
4161TEST(ExpectTest, EXPECT_TRUE) {
4162 EXPECT_TRUE(2 > 1); // NOLINT
4163 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4164 "Value of: 2 < 1\n"
4165 " Actual: false\n"
4166 "Expected: true");
4167 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4168 "2 > 3");
4169}
4170
vladlosevfbd53a52009-10-20 21:03:10 +00004171// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4172TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4173 EXPECT_TRUE(ResultIsEven(2));
4174 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4175 "Value of: ResultIsEven(3)\n"
4176 " Actual: false (3 is odd)\n"
4177 "Expected: true");
4178 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4179 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4180 "Value of: ResultIsEvenNoExplanation(3)\n"
4181 " Actual: false (3 is odd)\n"
4182 "Expected: true");
4183}
4184
shiqian4b6829f2008-07-03 22:38:12 +00004185// Tests EXPECT_FALSE.
4186TEST(ExpectTest, EXPECT_FALSE) {
4187 EXPECT_FALSE(2 < 1); // NOLINT
4188 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4189 "Value of: 2 > 1\n"
4190 " Actual: true\n"
4191 "Expected: false");
4192 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4193 "2 < 3");
4194}
4195
vladlosevfbd53a52009-10-20 21:03:10 +00004196// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4197TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4198 EXPECT_FALSE(ResultIsEven(3));
4199 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4200 "Value of: ResultIsEven(2)\n"
4201 " Actual: true (2 is even)\n"
4202 "Expected: false");
4203 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4204 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4205 "Value of: ResultIsEvenNoExplanation(2)\n"
4206 " Actual: true\n"
4207 "Expected: false");
4208}
4209
zhanyong.wan98efcc42009-04-28 00:28:09 +00004210#ifdef __BORLANDC__
4211// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00004212# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00004213#endif
4214
shiqian4b6829f2008-07-03 22:38:12 +00004215// Tests EXPECT_EQ.
4216TEST(ExpectTest, EXPECT_EQ) {
4217 EXPECT_EQ(5, 2 + 3);
4218 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4219 "Value of: 2*3\n"
4220 " Actual: 6\n"
4221 "Expected: 5");
4222 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4223 "2 - 3");
4224}
4225
4226// Tests using EXPECT_EQ on double values. The purpose is to make
4227// sure that the specialization we did for integer and anonymous enums
4228// isn't used for double arguments.
4229TEST(ExpectTest, EXPECT_EQ_Double) {
4230 // A success.
4231 EXPECT_EQ(5.6, 5.6);
4232
4233 // A failure.
4234 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4235 "5.1");
4236}
4237
vladlosev5147b452010-03-17 18:22:59 +00004238#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004239// Tests EXPECT_EQ(NULL, pointer).
4240TEST(ExpectTest, EXPECT_EQ_NULL) {
4241 // A success.
4242 const char* p = NULL;
zhanyong.wan5e255e02011-01-10 18:17:59 +00004243 // Some older GCC versions may issue a spurious warning in this or the next
zhanyong.wan9644db82009-06-24 23:02:50 +00004244 // assertion statement. This warning should not be suppressed with
4245 // static_cast since the test verifies the ability to use bare NULL as the
4246 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00004247 EXPECT_EQ(NULL, p);
4248
4249 // A failure.
4250 int n = 0;
4251 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4252 "Value of: &n\n");
4253}
vladlosev5147b452010-03-17 18:22:59 +00004254#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004255
4256// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4257// treated as a null pointer by the compiler, we need to make sure
4258// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4259// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4260TEST(ExpectTest, EXPECT_EQ_0) {
4261 int n = 0;
4262
4263 // A success.
4264 EXPECT_EQ(0, n);
4265
4266 // A failure.
4267 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4268 "Expected: 0");
4269}
4270
4271// Tests EXPECT_NE.
4272TEST(ExpectTest, EXPECT_NE) {
4273 EXPECT_NE(6, 7);
4274
4275 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4276 "Expected: ('a') != ('a'), "
4277 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4278 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4279 "2");
4280 char* const p0 = NULL;
4281 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4282 "p0");
4283 // Only way to get the Nokia compiler to compile the cast
4284 // is to have a separate void* variable first. Putting
4285 // the two casts on the same line doesn't work, neither does
4286 // a direct C-style to char*.
4287 void* pv1 = (void*)0x1234; // NOLINT
4288 char* const p1 = reinterpret_cast<char*>(pv1);
4289 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4290 "p1");
4291}
4292
4293// Tests EXPECT_LE.
4294TEST(ExpectTest, EXPECT_LE) {
4295 EXPECT_LE(2, 3);
4296 EXPECT_LE(2, 2);
4297 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4298 "Expected: (2) <= (0), actual: 2 vs 0");
4299 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4300 "(1.1) <= (0.9)");
4301}
4302
4303// Tests EXPECT_LT.
4304TEST(ExpectTest, EXPECT_LT) {
4305 EXPECT_LT(2, 3);
4306 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4307 "Expected: (2) < (2), actual: 2 vs 2");
4308 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4309 "(2) < (1)");
4310}
4311
4312// Tests EXPECT_GE.
4313TEST(ExpectTest, EXPECT_GE) {
4314 EXPECT_GE(2, 1);
4315 EXPECT_GE(2, 2);
4316 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4317 "Expected: (2) >= (3), actual: 2 vs 3");
4318 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4319 "(0.9) >= (1.1)");
4320}
4321
4322// Tests EXPECT_GT.
4323TEST(ExpectTest, EXPECT_GT) {
4324 EXPECT_GT(2, 1);
4325 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4326 "Expected: (2) > (2), actual: 2 vs 2");
4327 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4328 "(2) > (3)");
4329}
4330
shiqian9204c8e2008-09-12 20:57:22 +00004331#if GTEST_HAS_EXCEPTIONS
4332
4333// Tests EXPECT_THROW.
4334TEST(ExpectTest, EXPECT_THROW) {
4335 EXPECT_THROW(ThrowAnInteger(), int);
4336 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004337 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00004338 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00004339 EXPECT_NONFATAL_FAILURE(
4340 EXPECT_THROW(ThrowNothing(), bool),
4341 "Expected: ThrowNothing() throws an exception of type bool.\n"
4342 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00004343}
4344
4345// Tests EXPECT_NO_THROW.
4346TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00004347 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004348 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004349 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00004350 "exception.\n Actual: it throws.");
4351}
4352
4353// Tests EXPECT_ANY_THROW.
4354TEST(ExpectTest, EXPECT_ANY_THROW) {
4355 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004356 EXPECT_NONFATAL_FAILURE(
4357 EXPECT_ANY_THROW(ThrowNothing()),
4358 "Expected: ThrowNothing() throws an exception.\n"
4359 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004360}
4361
4362#endif // GTEST_HAS_EXCEPTIONS
4363
shiqian4b6829f2008-07-03 22:38:12 +00004364// Make sure we deal with the precedence of <<.
4365TEST(ExpectTest, ExpectPrecedence) {
4366 EXPECT_EQ(1 < 2, true);
4367 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4368 "Value of: true && false");
4369}
4370
4371
4372// Tests the StreamableToString() function.
4373
4374// Tests using StreamableToString() on a scalar.
4375TEST(StreamableToStringTest, Scalar) {
4376 EXPECT_STREQ("5", StreamableToString(5).c_str());
4377}
4378
4379// Tests using StreamableToString() on a non-char pointer.
4380TEST(StreamableToStringTest, Pointer) {
4381 int n = 0;
4382 int* p = &n;
4383 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4384}
4385
4386// Tests using StreamableToString() on a NULL non-char pointer.
4387TEST(StreamableToStringTest, NullPointer) {
4388 int* p = NULL;
4389 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4390}
4391
4392// Tests using StreamableToString() on a C string.
4393TEST(StreamableToStringTest, CString) {
4394 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4395}
4396
4397// Tests using StreamableToString() on a NULL C string.
4398TEST(StreamableToStringTest, NullCString) {
4399 char* p = NULL;
4400 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4401}
4402
4403// Tests using streamable values as assertion messages.
4404
shiqian4b6829f2008-07-03 22:38:12 +00004405// Tests using std::string as an assertion message.
4406TEST(StreamableTest, string) {
4407 static const std::string str(
4408 "This failure message is a std::string, and is expected.");
4409 EXPECT_FATAL_FAILURE(FAIL() << str,
4410 str.c_str());
4411}
4412
4413// Tests that we can output strings containing embedded NULs.
4414// Limited to Linux because we can only do this with std::string's.
4415TEST(StreamableTest, stringWithEmbeddedNUL) {
4416 static const char char_array_with_nul[] =
4417 "Here's a NUL\0 and some more string";
4418 static const std::string string_with_nul(char_array_with_nul,
4419 sizeof(char_array_with_nul)
4420 - 1); // drops the trailing NUL
4421 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4422 "Here's a NUL\\0 and some more string");
4423}
4424
shiqian4b6829f2008-07-03 22:38:12 +00004425// Tests that we can output a NUL char.
4426TEST(StreamableTest, NULChar) {
4427 EXPECT_FATAL_FAILURE({ // NOLINT
4428 FAIL() << "A NUL" << '\0' << " and some more string";
4429 }, "A NUL\\0 and some more string");
4430}
4431
4432// Tests using int as an assertion message.
4433TEST(StreamableTest, int) {
4434 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4435 "900913");
4436}
4437
4438// Tests using NULL char pointer as an assertion message.
4439//
4440// In MSVC, streaming a NULL char * causes access violation. Google Test
4441// implemented a workaround (substituting "(null)" for NULL). This
4442// tests whether the workaround works.
4443TEST(StreamableTest, NullCharPtr) {
4444 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4445 "(null)");
4446}
4447
4448// Tests that basic IO manipulators (endl, ends, and flush) can be
4449// streamed to testing::Message.
4450TEST(StreamableTest, BasicIoManip) {
4451 EXPECT_FATAL_FAILURE({ // NOLINT
4452 FAIL() << "Line 1." << std::endl
4453 << "A NUL char " << std::ends << std::flush << " in line 2.";
4454 }, "Line 1.\nA NUL char \\0 in line 2.");
4455}
4456
shiqian4b6829f2008-07-03 22:38:12 +00004457// Tests the macros that haven't been covered so far.
4458
4459void AddFailureHelper(bool* aborted) {
4460 *aborted = true;
4461 ADD_FAILURE() << "Failure";
4462 *aborted = false;
4463}
4464
4465// Tests ADD_FAILURE.
4466TEST(MacroTest, ADD_FAILURE) {
4467 bool aborted = true;
4468 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4469 "Failure");
4470 EXPECT_FALSE(aborted);
4471}
4472
zhanyong.wand5ad2ca2010-07-26 21:59:50 +00004473// Tests ADD_FAILURE_AT.
4474TEST(MacroTest, ADD_FAILURE_AT) {
4475 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4476 // the failure message contains the user-streamed part.
4477 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4478
4479 // Verifies that the user-streamed part is optional.
4480 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4481
4482 // Unfortunately, we cannot verify that the failure message contains
4483 // the right file path and line number the same way, as
4484 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4485 // line number. Instead, we do that in gtest_output_test_.cc.
4486}
4487
shiqian4b6829f2008-07-03 22:38:12 +00004488// Tests FAIL.
4489TEST(MacroTest, FAIL) {
4490 EXPECT_FATAL_FAILURE(FAIL(),
4491 "Failed");
4492 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4493 "Intentional failure.");
4494}
4495
4496// Tests SUCCEED
4497TEST(MacroTest, SUCCEED) {
4498 SUCCEED();
4499 SUCCEED() << "Explicit success.";
4500}
4501
4502
4503// Tests for EXPECT_EQ() and ASSERT_EQ().
4504//
4505// These tests fail *intentionally*, s.t. the failure messages can be
4506// generated and tested.
4507//
4508// We have different tests for different argument types.
4509
4510// Tests using bool values in {EXPECT|ASSERT}_EQ.
4511TEST(EqAssertionTest, Bool) {
4512 EXPECT_EQ(true, true);
zhanyong.wan5e255e02011-01-10 18:17:59 +00004513 EXPECT_FATAL_FAILURE({
4514 bool false_value = false;
4515 ASSERT_EQ(false_value, true);
4516 }, "Value of: true");
shiqian4b6829f2008-07-03 22:38:12 +00004517}
4518
4519// Tests using int values in {EXPECT|ASSERT}_EQ.
4520TEST(EqAssertionTest, Int) {
4521 ASSERT_EQ(32, 32);
4522 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4523 "33");
4524}
4525
4526// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4527TEST(EqAssertionTest, Time_T) {
4528 EXPECT_EQ(static_cast<time_t>(0),
4529 static_cast<time_t>(0));
4530 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4531 static_cast<time_t>(1234)),
4532 "1234");
4533}
4534
4535// Tests using char values in {EXPECT|ASSERT}_EQ.
4536TEST(EqAssertionTest, Char) {
4537 ASSERT_EQ('z', 'z');
4538 const char ch = 'b';
4539 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4540 "ch");
4541 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4542 "ch");
4543}
4544
4545// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4546TEST(EqAssertionTest, WideChar) {
4547 EXPECT_EQ(L'b', L'b');
4548
4549 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4550 "Value of: L'x'\n"
4551 " Actual: L'x' (120, 0x78)\n"
4552 "Expected: L'\0'\n"
4553 "Which is: L'\0' (0, 0x0)");
4554
4555 static wchar_t wchar;
4556 wchar = L'b';
4557 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4558 "wchar");
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004559 wchar = 0x8119;
4560 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
shiqian4b6829f2008-07-03 22:38:12 +00004561 "Value of: wchar");
4562}
4563
shiqian4b6829f2008-07-03 22:38:12 +00004564// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4565TEST(EqAssertionTest, StdString) {
4566 // Compares a const char* to an std::string that has identical
4567 // content.
4568 ASSERT_EQ("Test", ::std::string("Test"));
4569
4570 // Compares two identical std::strings.
4571 static const ::std::string str1("A * in the middle");
4572 static const ::std::string str2(str1);
4573 EXPECT_EQ(str1, str2);
4574
4575 // Compares a const char* to an std::string that has different
4576 // content
4577 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4578 "::std::string(\"test\")");
4579
4580 // Compares an std::string to a char* that has different content.
4581 char* const p1 = const_cast<char*>("foo");
4582 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4583 "p1");
4584
4585 // Compares two std::strings that have different contents, one of
4586 // which having a NUL character in the middle. This should fail.
4587 static ::std::string str3(str1);
4588 str3.at(2) = '\0';
4589 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4590 "Value of: str3\n"
4591 " Actual: \"A \\0 in the middle\"");
4592}
4593
shiqian4b6829f2008-07-03 22:38:12 +00004594#if GTEST_HAS_STD_WSTRING
4595
4596// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4597TEST(EqAssertionTest, StdWideString) {
shiqian4b6829f2008-07-03 22:38:12 +00004598 // Compares two identical std::wstrings.
4599 const ::std::wstring wstr1(L"A * in the middle");
4600 const ::std::wstring wstr2(wstr1);
4601 ASSERT_EQ(wstr1, wstr2);
4602
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004603 // Compares an std::wstring to a const wchar_t* that has identical
4604 // content.
4605 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4606 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4607
shiqian4b6829f2008-07-03 22:38:12 +00004608 // Compares an std::wstring to a const wchar_t* that has different
4609 // content.
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004610 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
shiqian4b6829f2008-07-03 22:38:12 +00004611 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004612 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4613 }, "kTestX8120");
shiqian4b6829f2008-07-03 22:38:12 +00004614
4615 // Compares two std::wstrings that have different contents, one of
4616 // which having a NUL character in the middle.
4617 ::std::wstring wstr3(wstr1);
4618 wstr3.at(2) = L'\0';
4619 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4620 "wstr3");
4621
4622 // Compares a wchar_t* to an std::wstring that has different
4623 // content.
4624 EXPECT_FATAL_FAILURE({ // NOLINT
4625 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4626 }, "");
4627}
4628
4629#endif // GTEST_HAS_STD_WSTRING
4630
4631#if GTEST_HAS_GLOBAL_STRING
4632// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4633TEST(EqAssertionTest, GlobalString) {
4634 // Compares a const char* to a ::string that has identical content.
4635 EXPECT_EQ("Test", ::string("Test"));
4636
4637 // Compares two identical ::strings.
4638 const ::string str1("A * in the middle");
4639 const ::string str2(str1);
4640 ASSERT_EQ(str1, str2);
4641
4642 // Compares a ::string to a const char* that has different content.
4643 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4644 "test");
4645
4646 // Compares two ::strings that have different contents, one of which
4647 // having a NUL character in the middle.
4648 ::string str3(str1);
4649 str3.at(2) = '\0';
4650 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4651 "str3");
4652
4653 // Compares a ::string to a char* that has different content.
4654 EXPECT_FATAL_FAILURE({ // NOLINT
4655 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4656 }, "");
4657}
4658
4659#endif // GTEST_HAS_GLOBAL_STRING
4660
4661#if GTEST_HAS_GLOBAL_WSTRING
4662
4663// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4664TEST(EqAssertionTest, GlobalWideString) {
shiqian4b6829f2008-07-03 22:38:12 +00004665 // Compares two identical ::wstrings.
4666 static const ::wstring wstr1(L"A * in the middle");
4667 static const ::wstring wstr2(wstr1);
4668 EXPECT_EQ(wstr1, wstr2);
4669
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004670 // Compares a const wchar_t* to a ::wstring that has identical content.
4671 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4672 ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4673
shiqian4b6829f2008-07-03 22:38:12 +00004674 // Compares a const wchar_t* to a ::wstring that has different
4675 // content.
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004676 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
shiqian4b6829f2008-07-03 22:38:12 +00004677 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004678 EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
shiqian4b6829f2008-07-03 22:38:12 +00004679 }, "Test\\x8119");
4680
4681 // Compares a wchar_t* to a ::wstring that has different content.
4682 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4683 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4684 "bar");
4685
4686 // Compares two ::wstrings that have different contents, one of which
4687 // having a NUL character in the middle.
4688 static ::wstring wstr3;
4689 wstr3 = wstr1;
4690 wstr3.at(2) = L'\0';
4691 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4692 "wstr3");
4693}
4694
4695#endif // GTEST_HAS_GLOBAL_WSTRING
4696
4697// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4698TEST(EqAssertionTest, CharPointer) {
4699 char* const p0 = NULL;
4700 // Only way to get the Nokia compiler to compile the cast
4701 // is to have a separate void* variable first. Putting
4702 // the two casts on the same line doesn't work, neither does
4703 // a direct C-style to char*.
4704 void* pv1 = (void*)0x1234; // NOLINT
4705 void* pv2 = (void*)0xABC0; // NOLINT
4706 char* const p1 = reinterpret_cast<char*>(pv1);
4707 char* const p2 = reinterpret_cast<char*>(pv2);
4708 ASSERT_EQ(p1, p1);
4709
4710 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4711 "Value of: p2");
4712 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4713 "p2");
4714 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4715 reinterpret_cast<char*>(0xABC0)),
4716 "ABC0");
4717}
4718
4719// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4720TEST(EqAssertionTest, WideCharPointer) {
4721 wchar_t* const p0 = NULL;
4722 // Only way to get the Nokia compiler to compile the cast
4723 // is to have a separate void* variable first. Putting
4724 // the two casts on the same line doesn't work, neither does
4725 // a direct C-style to char*.
4726 void* pv1 = (void*)0x1234; // NOLINT
4727 void* pv2 = (void*)0xABC0; // NOLINT
4728 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4729 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4730 EXPECT_EQ(p0, p0);
4731
4732 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4733 "Value of: p2");
4734 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4735 "p2");
4736 void* pv3 = (void*)0x1234; // NOLINT
4737 void* pv4 = (void*)0xABC0; // NOLINT
4738 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4739 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4740 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4741 "p4");
4742}
4743
4744// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4745TEST(EqAssertionTest, OtherPointer) {
4746 ASSERT_EQ(static_cast<const int*>(NULL),
4747 static_cast<const int*>(NULL));
4748 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4749 reinterpret_cast<const int*>(0x1234)),
4750 "0x1234");
4751}
4752
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004753// A class that supports binary comparison operators but not streaming.
4754class UnprintableChar {
4755 public:
4756 explicit UnprintableChar(char ch) : char_(ch) {}
4757
4758 bool operator==(const UnprintableChar& rhs) const {
4759 return char_ == rhs.char_;
4760 }
4761 bool operator!=(const UnprintableChar& rhs) const {
4762 return char_ != rhs.char_;
4763 }
4764 bool operator<(const UnprintableChar& rhs) const {
4765 return char_ < rhs.char_;
4766 }
4767 bool operator<=(const UnprintableChar& rhs) const {
4768 return char_ <= rhs.char_;
4769 }
4770 bool operator>(const UnprintableChar& rhs) const {
4771 return char_ > rhs.char_;
4772 }
4773 bool operator>=(const UnprintableChar& rhs) const {
4774 return char_ >= rhs.char_;
4775 }
4776
4777 private:
4778 char char_;
4779};
4780
4781// Tests that ASSERT_EQ() and friends don't require the arguments to
4782// be printable.
4783TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4784 const UnprintableChar x('x'), y('y');
4785 ASSERT_EQ(x, x);
4786 EXPECT_NE(x, y);
4787 ASSERT_LT(x, y);
4788 EXPECT_LE(x, y);
4789 ASSERT_GT(y, x);
4790 EXPECT_GE(x, x);
4791
4792 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4793 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4794 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4795 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4796 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4797
4798 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4799 // variables, so we have to write UnprintableChar('x') instead of x.
zhanyong.waned1042b2011-03-05 08:04:01 +00004800#ifndef __BORLANDC__
4801 // ICE's in C++Builder.
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004802 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4803 "1-byte object <78>");
4804 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4805 "1-byte object <78>");
zhanyong.waned1042b2011-03-05 08:04:01 +00004806#endif
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004807 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4808 "1-byte object <79>");
4809 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4810 "1-byte object <78>");
4811 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4812 "1-byte object <79>");
4813}
4814
shiqian4b6829f2008-07-03 22:38:12 +00004815// Tests the FRIEND_TEST macro.
4816
4817// This class has a private member we want to test. We will test it
4818// both in a TEST and in a TEST_F.
4819class Foo {
4820 public:
4821 Foo() {}
4822
4823 private:
4824 int Bar() const { return 1; }
4825
4826 // Declares the friend tests that can access the private member
4827 // Bar().
4828 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4829 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4830};
4831
4832// Tests that the FRIEND_TEST declaration allows a TEST to access a
4833// class's private members. This should compile.
4834TEST(FRIEND_TEST_Test, TEST) {
4835 ASSERT_EQ(1, Foo().Bar());
4836}
4837
4838// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004839class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004840 protected:
4841 Foo foo;
4842};
4843
4844// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4845// class's private members. This should compile.
4846TEST_F(FRIEND_TEST_Test2, TEST_F) {
4847 ASSERT_EQ(1, foo.Bar());
4848}
4849
4850// Tests the life cycle of Test objects.
4851
4852// The test fixture for testing the life cycle of Test objects.
4853//
4854// This class counts the number of live test objects that uses this
4855// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004856class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004857 protected:
4858 // Constructor. Increments the number of test objects that uses
4859 // this fixture.
4860 TestLifeCycleTest() { count_++; }
4861
4862 // Destructor. Decrements the number of test objects that uses this
4863 // fixture.
4864 ~TestLifeCycleTest() { count_--; }
4865
4866 // Returns the number of live test objects that uses this fixture.
4867 int count() const { return count_; }
4868
4869 private:
4870 static int count_;
4871};
4872
4873int TestLifeCycleTest::count_ = 0;
4874
4875// Tests the life cycle of test objects.
4876TEST_F(TestLifeCycleTest, Test1) {
4877 // There should be only one test object in this test case that's
4878 // currently alive.
4879 ASSERT_EQ(1, count());
4880}
4881
4882// Tests the life cycle of test objects.
4883TEST_F(TestLifeCycleTest, Test2) {
4884 // After Test1 is done and Test2 is started, there should still be
4885 // only one live test object, as the object for Test1 should've been
4886 // deleted.
4887 ASSERT_EQ(1, count());
4888}
4889
4890} // namespace
4891
vladlosevfbd53a52009-10-20 21:03:10 +00004892// Tests that the copy constructor works when it is NOT optimized away by
4893// the compiler.
4894TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
4895 // Checks that the copy constructor doesn't try to dereference NULL pointers
4896 // in the source object.
4897 AssertionResult r1 = AssertionSuccess();
4898 AssertionResult r2 = r1;
4899 // The following line is added to prevent the compiler from optimizing
4900 // away the constructor call.
4901 r1 << "abc";
4902
4903 AssertionResult r3 = r1;
4904 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
4905 EXPECT_STREQ("abc", r1.message());
4906}
4907
4908// Tests that AssertionSuccess and AssertionFailure construct
4909// AssertionResult objects as expected.
4910TEST(AssertionResultTest, ConstructionWorks) {
4911 AssertionResult r1 = AssertionSuccess();
4912 EXPECT_TRUE(r1);
4913 EXPECT_STREQ("", r1.message());
4914
4915 AssertionResult r2 = AssertionSuccess() << "abc";
4916 EXPECT_TRUE(r2);
4917 EXPECT_STREQ("abc", r2.message());
4918
4919 AssertionResult r3 = AssertionFailure();
4920 EXPECT_FALSE(r3);
4921 EXPECT_STREQ("", r3.message());
4922
4923 AssertionResult r4 = AssertionFailure() << "def";
4924 EXPECT_FALSE(r4);
4925 EXPECT_STREQ("def", r4.message());
4926
4927 AssertionResult r5 = AssertionFailure(Message() << "ghi");
4928 EXPECT_FALSE(r5);
4929 EXPECT_STREQ("ghi", r5.message());
4930}
4931
vladlosev12878402010-10-22 01:33:11 +00004932// Tests that the negation flips the predicate result but keeps the message.
vladlosevfbd53a52009-10-20 21:03:10 +00004933TEST(AssertionResultTest, NegationWorks) {
4934 AssertionResult r1 = AssertionSuccess() << "abc";
4935 EXPECT_FALSE(!r1);
4936 EXPECT_STREQ("abc", (!r1).message());
4937
4938 AssertionResult r2 = AssertionFailure() << "def";
4939 EXPECT_TRUE(!r2);
4940 EXPECT_STREQ("def", (!r2).message());
4941}
4942
4943TEST(AssertionResultTest, StreamingWorks) {
4944 AssertionResult r = AssertionSuccess();
4945 r << "abc" << 'd' << 0 << true;
4946 EXPECT_STREQ("abcd0true", r.message());
4947}
4948
vladlosev12878402010-10-22 01:33:11 +00004949TEST(AssertionResultTest, CanStreamOstreamManipulators) {
4950 AssertionResult r = AssertionSuccess();
4951 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
4952 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
4953}
4954
shiqian4b6829f2008-07-03 22:38:12 +00004955// Tests streaming a user type whose definition and operator << are
4956// both in the global namespace.
4957class Base {
4958 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004959 explicit Base(int an_x) : x_(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004960 int x() const { return x_; }
4961 private:
4962 int x_;
4963};
4964std::ostream& operator<<(std::ostream& os,
4965 const Base& val) {
4966 return os << val.x();
4967}
4968std::ostream& operator<<(std::ostream& os,
4969 const Base* pointer) {
4970 return os << "(" << pointer->x() << ")";
4971}
4972
4973TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004974 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004975 Base a(1);
4976
4977 msg << a << &a; // Uses ::operator<<.
4978 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4979}
4980
4981// Tests streaming a user type whose definition and operator<< are
4982// both in an unnamed namespace.
4983namespace {
4984class MyTypeInUnnamedNameSpace : public Base {
4985 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004986 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004987};
4988std::ostream& operator<<(std::ostream& os,
4989 const MyTypeInUnnamedNameSpace& val) {
4990 return os << val.x();
4991}
4992std::ostream& operator<<(std::ostream& os,
4993 const MyTypeInUnnamedNameSpace* pointer) {
4994 return os << "(" << pointer->x() << ")";
4995}
4996} // namespace
4997
4998TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004999 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005000 MyTypeInUnnamedNameSpace a(1);
5001
5002 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5003 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5004}
5005
5006// Tests streaming a user type whose definition and operator<< are
5007// both in a user namespace.
5008namespace namespace1 {
5009class MyTypeInNameSpace1 : public Base {
5010 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005011 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005012};
5013std::ostream& operator<<(std::ostream& os,
5014 const MyTypeInNameSpace1& val) {
5015 return os << val.x();
5016}
5017std::ostream& operator<<(std::ostream& os,
5018 const MyTypeInNameSpace1* pointer) {
5019 return os << "(" << pointer->x() << ")";
5020}
5021} // namespace namespace1
5022
5023TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005024 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005025 namespace1::MyTypeInNameSpace1 a(1);
5026
5027 msg << a << &a; // Uses namespace1::operator<<.
5028 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5029}
5030
5031// Tests streaming a user type whose definition is in a user namespace
5032// but whose operator<< is in the global namespace.
5033namespace namespace2 {
5034class MyTypeInNameSpace2 : public ::Base {
5035 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005036 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005037};
5038} // namespace namespace2
5039std::ostream& operator<<(std::ostream& os,
5040 const namespace2::MyTypeInNameSpace2& val) {
5041 return os << val.x();
5042}
5043std::ostream& operator<<(std::ostream& os,
5044 const namespace2::MyTypeInNameSpace2* pointer) {
5045 return os << "(" << pointer->x() << ")";
5046}
5047
5048TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00005049 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005050 namespace2::MyTypeInNameSpace2 a(1);
5051
5052 msg << a << &a; // Uses ::operator<<.
5053 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5054}
5055
5056// Tests streaming NULL pointers to testing::Message.
5057TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00005058 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005059 char* const p1 = NULL;
5060 unsigned char* const p2 = NULL;
5061 int* p3 = NULL;
5062 double* p4 = NULL;
5063 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00005064 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005065
5066 msg << p1 << p2 << p3 << p4 << p5 << p6;
5067 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5068 msg.GetString().c_str());
5069}
5070
5071// Tests streaming wide strings to testing::Message.
5072TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00005073 // Streams a NULL of type const wchar_t*.
5074 const wchar_t* const_wstr = NULL;
5075 EXPECT_STREQ("(null)",
5076 (Message() << const_wstr).GetString().c_str());
5077
5078 // Streams a NULL of type wchar_t*.
5079 wchar_t* wstr = NULL;
5080 EXPECT_STREQ("(null)",
5081 (Message() << wstr).GetString().c_str());
5082
5083 // Streams a non-NULL of type const wchar_t*.
5084 const_wstr = L"abc\x8119";
5085 EXPECT_STREQ("abc\xe8\x84\x99",
5086 (Message() << const_wstr).GetString().c_str());
5087
5088 // Streams a non-NULL of type wchar_t*.
5089 wstr = const_cast<wchar_t*>(const_wstr);
5090 EXPECT_STREQ("abc\xe8\x84\x99",
5091 (Message() << wstr).GetString().c_str());
5092}
5093
5094
5095// This line tests that we can define tests in the testing namespace.
5096namespace testing {
5097
5098// Tests the TestInfo class.
5099
shiqian760af5c2008-08-06 21:43:15 +00005100class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005101 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005102 static const TestInfo* GetTestInfo(const char* test_name) {
5103 const TestCase* const test_case = GetUnitTestImpl()->
5104 GetTestCase("TestInfoTest", "", NULL, NULL);
5105
5106 for (int i = 0; i < test_case->total_test_count(); ++i) {
5107 const TestInfo* const test_info = test_case->GetTestInfo(i);
5108 if (strcmp(test_name, test_info->name()) == 0)
5109 return test_info;
5110 }
5111 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005112 }
5113
5114 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00005115 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00005116 return test_info->result();
5117 }
5118};
5119
5120// Tests TestInfo::test_case_name() and TestInfo::name().
5121TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005122 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00005123
5124 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5125 ASSERT_STREQ("Names", test_info->name());
5126}
5127
5128// Tests TestInfo::result().
5129TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005130 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00005131
5132 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005133 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005134
5135 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005136 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005137}
5138
5139// Tests setting up and tearing down a test case.
5140
shiqian760af5c2008-08-06 21:43:15 +00005141class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005142 protected:
5143 // This will be called once before the first test in this test case
5144 // is run.
5145 static void SetUpTestCase() {
5146 printf("Setting up the test case . . .\n");
5147
5148 // Initializes some shared resource. In this simple example, we
5149 // just create a C string. More complex stuff can be done if
5150 // desired.
5151 shared_resource_ = "123";
5152
5153 // Increments the number of test cases that have been set up.
5154 counter_++;
5155
5156 // SetUpTestCase() should be called only once.
5157 EXPECT_EQ(1, counter_);
5158 }
5159
5160 // This will be called once after the last test in this test case is
5161 // run.
5162 static void TearDownTestCase() {
5163 printf("Tearing down the test case . . .\n");
5164
5165 // Decrements the number of test cases that have been set up.
5166 counter_--;
5167
5168 // TearDownTestCase() should be called only once.
5169 EXPECT_EQ(0, counter_);
5170
5171 // Cleans up the shared resource.
5172 shared_resource_ = NULL;
5173 }
5174
5175 // This will be called before each test in this test case.
5176 virtual void SetUp() {
5177 // SetUpTestCase() should be called only once, so counter_ should
5178 // always be 1.
5179 EXPECT_EQ(1, counter_);
5180 }
5181
5182 // Number of test cases that have been set up.
5183 static int counter_;
5184
5185 // Some resource to be shared by all tests in this test case.
5186 static const char* shared_resource_;
5187};
5188
5189int SetUpTestCaseTest::counter_ = 0;
5190const char* SetUpTestCaseTest::shared_resource_ = NULL;
5191
5192// A test that uses the shared resource.
5193TEST_F(SetUpTestCaseTest, Test1) {
5194 EXPECT_STRNE(NULL, shared_resource_);
5195}
5196
5197// Another test that uses the shared resource.
5198TEST_F(SetUpTestCaseTest, Test2) {
5199 EXPECT_STREQ("123", shared_resource_);
5200}
5201
5202// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5203
5204// The Flags struct stores a copy of all Google Test flags.
5205struct Flags {
5206 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00005207 Flags() : also_run_disabled_tests(false),
5208 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00005209 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00005210 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00005211 filter(""),
5212 list_tests(false),
5213 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005214 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005215 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005216 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005217 shuffle(false),
vladlosevba015a92009-11-17 22:43:15 +00005218 stack_trace_depth(kMaxStackTraceDepth),
zhanyong.wanc95489e2010-08-19 22:16:00 +00005219 stream_result_to(""),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005220 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00005221
5222 // Factory methods.
5223
shiqianca6949f2009-01-10 01:16:33 +00005224 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5225 // the given value.
5226 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5227 Flags flags;
5228 flags.also_run_disabled_tests = also_run_disabled_tests;
5229 return flags;
5230 }
5231
shiqian4b6829f2008-07-03 22:38:12 +00005232 // Creates a Flags struct where the gtest_break_on_failure flag has
5233 // the given value.
5234 static Flags BreakOnFailure(bool break_on_failure) {
5235 Flags flags;
5236 flags.break_on_failure = break_on_failure;
5237 return flags;
5238 }
5239
5240 // Creates a Flags struct where the gtest_catch_exceptions flag has
5241 // the given value.
5242 static Flags CatchExceptions(bool catch_exceptions) {
5243 Flags flags;
5244 flags.catch_exceptions = catch_exceptions;
5245 return flags;
5246 }
5247
shiqian21d43d12009-01-08 01:10:31 +00005248 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5249 // the given value.
5250 static Flags DeathTestUseFork(bool death_test_use_fork) {
5251 Flags flags;
5252 flags.death_test_use_fork = death_test_use_fork;
5253 return flags;
5254 }
5255
shiqian4b6829f2008-07-03 22:38:12 +00005256 // Creates a Flags struct where the gtest_filter flag has the given
5257 // value.
5258 static Flags Filter(const char* filter) {
5259 Flags flags;
5260 flags.filter = filter;
5261 return flags;
5262 }
5263
5264 // Creates a Flags struct where the gtest_list_tests flag has the
5265 // given value.
5266 static Flags ListTests(bool list_tests) {
5267 Flags flags;
5268 flags.list_tests = list_tests;
5269 return flags;
5270 }
5271
5272 // Creates a Flags struct where the gtest_output flag has the given
5273 // value.
5274 static Flags Output(const char* output) {
5275 Flags flags;
5276 flags.output = output;
5277 return flags;
5278 }
5279
shiqiand981cee2008-07-25 04:06:16 +00005280 // Creates a Flags struct where the gtest_print_time flag has the given
5281 // value.
5282 static Flags PrintTime(bool print_time) {
5283 Flags flags;
5284 flags.print_time = print_time;
5285 return flags;
5286 }
5287
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005288 // Creates a Flags struct where the gtest_random_seed flag has
5289 // the given value.
5290 static Flags RandomSeed(Int32 random_seed) {
5291 Flags flags;
5292 flags.random_seed = random_seed;
5293 return flags;
5294 }
5295
shiqian4b6829f2008-07-03 22:38:12 +00005296 // Creates a Flags struct where the gtest_repeat flag has the given
5297 // value.
5298 static Flags Repeat(Int32 repeat) {
5299 Flags flags;
5300 flags.repeat = repeat;
5301 return flags;
5302 }
5303
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005304 // Creates a Flags struct where the gtest_shuffle flag has
5305 // the given value.
5306 static Flags Shuffle(bool shuffle) {
5307 Flags flags;
5308 flags.shuffle = shuffle;
5309 return flags;
5310 }
5311
vladlosevba015a92009-11-17 22:43:15 +00005312 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5313 // the given value.
5314 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5315 Flags flags;
5316 flags.stack_trace_depth = stack_trace_depth;
5317 return flags;
5318 }
5319
zhanyong.wanc95489e2010-08-19 22:16:00 +00005320 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5321 // the given value.
5322 static Flags StreamResultTo(const char* stream_result_to) {
5323 Flags flags;
5324 flags.stream_result_to = stream_result_to;
5325 return flags;
5326 }
5327
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005328 // Creates a Flags struct where the gtest_throw_on_failure flag has
5329 // the given value.
5330 static Flags ThrowOnFailure(bool throw_on_failure) {
5331 Flags flags;
5332 flags.throw_on_failure = throw_on_failure;
5333 return flags;
5334 }
5335
shiqian4b6829f2008-07-03 22:38:12 +00005336 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00005337 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00005338 bool break_on_failure;
5339 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00005340 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00005341 const char* filter;
5342 bool list_tests;
5343 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00005344 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005345 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00005346 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005347 bool shuffle;
vladlosevba015a92009-11-17 22:43:15 +00005348 Int32 stack_trace_depth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00005349 const char* stream_result_to;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005350 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00005351};
5352
5353// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00005354class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005355 protected:
5356 // Clears the flags before each test.
5357 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00005358 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005359 GTEST_FLAG(break_on_failure) = false;
5360 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00005361 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005362 GTEST_FLAG(filter) = "";
5363 GTEST_FLAG(list_tests) = false;
5364 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005365 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005366 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00005367 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005368 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00005369 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00005370 GTEST_FLAG(stream_result_to) = "";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005371 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005372 }
5373
5374 // Asserts that two narrow or wide string arrays are equal.
5375 template <typename CharType>
5376 static void AssertStringArrayEq(size_t size1, CharType** array1,
5377 size_t size2, CharType** array2) {
5378 ASSERT_EQ(size1, size2) << " Array sizes different.";
5379
5380 for (size_t i = 0; i != size1; i++) {
5381 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5382 }
5383 }
5384
5385 // Verifies that the flag values match the expected values.
5386 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00005387 EXPECT_EQ(expected.also_run_disabled_tests,
5388 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00005389 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5390 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00005391 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00005392 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5393 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5394 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00005395 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005396 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00005397 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005398 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00005399 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanc95489e2010-08-19 22:16:00 +00005400 EXPECT_STREQ(expected.stream_result_to,
5401 GTEST_FLAG(stream_result_to).c_str());
5402 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00005403 }
5404
5405 // Parses a command line (specified by argc1 and argv1), then
5406 // verifies that the flag values are expected and that the
5407 // recognized flags are removed from the command line.
5408 template <typename CharType>
5409 static void TestParsingFlags(int argc1, const CharType** argv1,
5410 int argc2, const CharType** argv2,
vladlosevba015a92009-11-17 22:43:15 +00005411 const Flags& expected, bool should_print_help) {
5412 const bool saved_help_flag = ::testing::internal::g_help_flag;
5413 ::testing::internal::g_help_flag = false;
5414
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005415#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +00005416 CaptureStdout();
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005417#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +00005418
shiqian4b6829f2008-07-03 22:38:12 +00005419 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00005420 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00005421
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005422#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +00005423 const String captured_stdout = GetCapturedStdout();
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005424#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +00005425
shiqian4b6829f2008-07-03 22:38:12 +00005426 // Verifies the flag values.
5427 CheckFlags(expected);
5428
5429 // Verifies that the recognized flags are removed from the command
5430 // line.
5431 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
vladlosevba015a92009-11-17 22:43:15 +00005432
5433 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5434 // help message for the flags it recognizes.
5435 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5436
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005437#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +00005438 const char* const expected_help_fragment =
5439 "This program contains tests written using";
5440 if (should_print_help) {
5441 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5442 } else {
5443 EXPECT_PRED_FORMAT2(IsNotSubstring,
5444 expected_help_fragment, captured_stdout);
5445 }
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005446#endif // GTEST_HAS_STREAM_REDIRECTION
vladlosevba015a92009-11-17 22:43:15 +00005447
5448 ::testing::internal::g_help_flag = saved_help_flag;
shiqian4b6829f2008-07-03 22:38:12 +00005449 }
5450
5451 // This macro wraps TestParsingFlags s.t. the user doesn't need
5452 // to specify the array sizes.
zhanyong.wan733a54a2011-02-22 22:08:59 +00005453
vladlosevba015a92009-11-17 22:43:15 +00005454#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
shiqian4b6829f2008-07-03 22:38:12 +00005455 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
vladlosevba015a92009-11-17 22:43:15 +00005456 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5457 expected, should_print_help)
shiqian4b6829f2008-07-03 22:38:12 +00005458};
5459
5460// Tests parsing an empty command line.
5461TEST_F(InitGoogleTestTest, Empty) {
5462 const char* argv[] = {
5463 NULL
5464 };
5465
5466 const char* argv2[] = {
5467 NULL
5468 };
5469
vladlosevba015a92009-11-17 22:43:15 +00005470 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005471}
5472
5473// Tests parsing a command line that has no flag.
5474TEST_F(InitGoogleTestTest, NoFlag) {
5475 const char* argv[] = {
5476 "foo.exe",
5477 NULL
5478 };
5479
5480 const char* argv2[] = {
5481 "foo.exe",
5482 NULL
5483 };
5484
vladlosevba015a92009-11-17 22:43:15 +00005485 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005486}
5487
5488// Tests parsing a bad --gtest_filter flag.
5489TEST_F(InitGoogleTestTest, FilterBad) {
5490 const char* argv[] = {
5491 "foo.exe",
5492 "--gtest_filter",
5493 NULL
5494 };
5495
5496 const char* argv2[] = {
5497 "foo.exe",
5498 "--gtest_filter",
5499 NULL
5500 };
5501
vladlosevba015a92009-11-17 22:43:15 +00005502 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
shiqian4b6829f2008-07-03 22:38:12 +00005503}
5504
5505// Tests parsing an empty --gtest_filter flag.
5506TEST_F(InitGoogleTestTest, FilterEmpty) {
5507 const char* argv[] = {
5508 "foo.exe",
5509 "--gtest_filter=",
5510 NULL
5511 };
5512
5513 const char* argv2[] = {
5514 "foo.exe",
5515 NULL
5516 };
5517
vladlosevba015a92009-11-17 22:43:15 +00005518 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
shiqian4b6829f2008-07-03 22:38:12 +00005519}
5520
5521// Tests parsing a non-empty --gtest_filter flag.
5522TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5523 const char* argv[] = {
5524 "foo.exe",
5525 "--gtest_filter=abc",
5526 NULL
5527 };
5528
5529 const char* argv2[] = {
5530 "foo.exe",
5531 NULL
5532 };
5533
vladlosevba015a92009-11-17 22:43:15 +00005534 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005535}
5536
5537// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005538TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00005539 const char* argv[] = {
5540 "foo.exe",
5541 "--gtest_break_on_failure",
5542 NULL
5543};
5544
5545 const char* argv2[] = {
5546 "foo.exe",
5547 NULL
5548 };
5549
vladlosevba015a92009-11-17 22:43:15 +00005550 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005551}
5552
5553// Tests parsing --gtest_break_on_failure=0.
5554TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5555 const char* argv[] = {
5556 "foo.exe",
5557 "--gtest_break_on_failure=0",
5558 NULL
5559 };
5560
5561 const char* argv2[] = {
5562 "foo.exe",
5563 NULL
5564 };
5565
vladlosevba015a92009-11-17 22:43:15 +00005566 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005567}
5568
5569// Tests parsing --gtest_break_on_failure=f.
5570TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5571 const char* argv[] = {
5572 "foo.exe",
5573 "--gtest_break_on_failure=f",
5574 NULL
5575 };
5576
5577 const char* argv2[] = {
5578 "foo.exe",
5579 NULL
5580 };
5581
vladlosevba015a92009-11-17 22:43:15 +00005582 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005583}
5584
5585// Tests parsing --gtest_break_on_failure=F.
5586TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5587 const char* argv[] = {
5588 "foo.exe",
5589 "--gtest_break_on_failure=F",
5590 NULL
5591 };
5592
5593 const char* argv2[] = {
5594 "foo.exe",
5595 NULL
5596 };
5597
vladlosevba015a92009-11-17 22:43:15 +00005598 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005599}
5600
5601// Tests parsing a --gtest_break_on_failure flag that has a "true"
5602// definition.
5603TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5604 const char* argv[] = {
5605 "foo.exe",
5606 "--gtest_break_on_failure=1",
5607 NULL
5608 };
5609
5610 const char* argv2[] = {
5611 "foo.exe",
5612 NULL
5613 };
5614
vladlosevba015a92009-11-17 22:43:15 +00005615 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005616}
5617
5618// Tests parsing --gtest_catch_exceptions.
5619TEST_F(InitGoogleTestTest, CatchExceptions) {
5620 const char* argv[] = {
5621 "foo.exe",
5622 "--gtest_catch_exceptions",
5623 NULL
5624 };
5625
5626 const char* argv2[] = {
5627 "foo.exe",
5628 NULL
5629 };
5630
vladlosevba015a92009-11-17 22:43:15 +00005631 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005632}
5633
shiqian21d43d12009-01-08 01:10:31 +00005634// Tests parsing --gtest_death_test_use_fork.
5635TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5636 const char* argv[] = {
5637 "foo.exe",
5638 "--gtest_death_test_use_fork",
5639 NULL
5640 };
5641
5642 const char* argv2[] = {
5643 "foo.exe",
5644 NULL
5645 };
5646
vladlosevba015a92009-11-17 22:43:15 +00005647 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
shiqian21d43d12009-01-08 01:10:31 +00005648}
5649
shiqian4b6829f2008-07-03 22:38:12 +00005650// Tests having the same flag twice with different values. The
5651// expected behavior is that the one coming last takes precedence.
5652TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5653 const char* argv[] = {
5654 "foo.exe",
5655 "--gtest_filter=a",
5656 "--gtest_filter=b",
5657 NULL
5658 };
5659
5660 const char* argv2[] = {
5661 "foo.exe",
5662 NULL
5663 };
5664
vladlosevba015a92009-11-17 22:43:15 +00005665 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005666}
5667
5668// Tests having an unrecognized flag on the command line.
5669TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5670 const char* argv[] = {
5671 "foo.exe",
5672 "--gtest_break_on_failure",
5673 "bar", // Unrecognized by Google Test.
5674 "--gtest_filter=b",
5675 NULL
5676 };
5677
5678 const char* argv2[] = {
5679 "foo.exe",
5680 "bar",
5681 NULL
5682 };
5683
5684 Flags flags;
5685 flags.break_on_failure = true;
5686 flags.filter = "b";
vladlosevba015a92009-11-17 22:43:15 +00005687 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00005688}
5689
5690// Tests having a --gtest_list_tests flag
5691TEST_F(InitGoogleTestTest, ListTestsFlag) {
5692 const char* argv[] = {
5693 "foo.exe",
5694 "--gtest_list_tests",
5695 NULL
5696 };
5697
5698 const char* argv2[] = {
5699 "foo.exe",
5700 NULL
5701 };
5702
vladlosevba015a92009-11-17 22:43:15 +00005703 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005704}
5705
5706// Tests having a --gtest_list_tests flag with a "true" value
5707TEST_F(InitGoogleTestTest, ListTestsTrue) {
5708 const char* argv[] = {
5709 "foo.exe",
5710 "--gtest_list_tests=1",
5711 NULL
5712 };
5713
5714 const char* argv2[] = {
5715 "foo.exe",
5716 NULL
5717 };
5718
vladlosevba015a92009-11-17 22:43:15 +00005719 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005720}
5721
5722// Tests having a --gtest_list_tests flag with a "false" value
5723TEST_F(InitGoogleTestTest, ListTestsFalse) {
5724 const char* argv[] = {
5725 "foo.exe",
5726 "--gtest_list_tests=0",
5727 NULL
5728 };
5729
5730 const char* argv2[] = {
5731 "foo.exe",
5732 NULL
5733 };
5734
vladlosevba015a92009-11-17 22:43:15 +00005735 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005736}
5737
5738// Tests parsing --gtest_list_tests=f.
5739TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5740 const char* argv[] = {
5741 "foo.exe",
5742 "--gtest_list_tests=f",
5743 NULL
5744 };
5745
5746 const char* argv2[] = {
5747 "foo.exe",
5748 NULL
5749 };
5750
vladlosevba015a92009-11-17 22:43:15 +00005751 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005752}
5753
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005754// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005755TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5756 const char* argv[] = {
5757 "foo.exe",
5758 "--gtest_list_tests=F",
5759 NULL
5760 };
5761
5762 const char* argv2[] = {
5763 "foo.exe",
5764 NULL
5765 };
5766
vladlosevba015a92009-11-17 22:43:15 +00005767 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005768}
5769
5770// Tests parsing --gtest_output (invalid).
5771TEST_F(InitGoogleTestTest, OutputEmpty) {
5772 const char* argv[] = {
5773 "foo.exe",
5774 "--gtest_output",
5775 NULL
5776 };
5777
5778 const char* argv2[] = {
5779 "foo.exe",
5780 "--gtest_output",
5781 NULL
5782 };
5783
vladlosevba015a92009-11-17 22:43:15 +00005784 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
shiqian4b6829f2008-07-03 22:38:12 +00005785}
5786
5787// Tests parsing --gtest_output=xml
5788TEST_F(InitGoogleTestTest, OutputXml) {
5789 const char* argv[] = {
5790 "foo.exe",
5791 "--gtest_output=xml",
5792 NULL
5793 };
5794
5795 const char* argv2[] = {
5796 "foo.exe",
5797 NULL
5798 };
5799
vladlosevba015a92009-11-17 22:43:15 +00005800 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005801}
5802
5803// Tests parsing --gtest_output=xml:file
5804TEST_F(InitGoogleTestTest, OutputXmlFile) {
5805 const char* argv[] = {
5806 "foo.exe",
5807 "--gtest_output=xml:file",
5808 NULL
5809 };
5810
5811 const char* argv2[] = {
5812 "foo.exe",
5813 NULL
5814 };
5815
vladlosevba015a92009-11-17 22:43:15 +00005816 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005817}
5818
5819// Tests parsing --gtest_output=xml:directory/path/
5820TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5821 const char* argv[] = {
5822 "foo.exe",
5823 "--gtest_output=xml:directory/path/",
5824 NULL
5825 };
5826
5827 const char* argv2[] = {
5828 "foo.exe",
5829 NULL
5830 };
5831
vladlosevba015a92009-11-17 22:43:15 +00005832 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5833 Flags::Output("xml:directory/path/"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005834}
5835
shiqiand981cee2008-07-25 04:06:16 +00005836// Tests having a --gtest_print_time flag
5837TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5838 const char* argv[] = {
5839 "foo.exe",
5840 "--gtest_print_time",
5841 NULL
5842 };
5843
5844 const char* argv2[] = {
5845 "foo.exe",
5846 NULL
5847 };
5848
vladlosevba015a92009-11-17 22:43:15 +00005849 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005850}
5851
5852// Tests having a --gtest_print_time flag with a "true" value
5853TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5854 const char* argv[] = {
5855 "foo.exe",
5856 "--gtest_print_time=1",
5857 NULL
5858 };
5859
5860 const char* argv2[] = {
5861 "foo.exe",
5862 NULL
5863 };
5864
vladlosevba015a92009-11-17 22:43:15 +00005865 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005866}
5867
5868// Tests having a --gtest_print_time flag with a "false" value
5869TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5870 const char* argv[] = {
5871 "foo.exe",
5872 "--gtest_print_time=0",
5873 NULL
5874 };
5875
5876 const char* argv2[] = {
5877 "foo.exe",
5878 NULL
5879 };
5880
vladlosevba015a92009-11-17 22:43:15 +00005881 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005882}
5883
5884// Tests parsing --gtest_print_time=f.
5885TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5886 const char* argv[] = {
5887 "foo.exe",
5888 "--gtest_print_time=f",
5889 NULL
5890 };
5891
5892 const char* argv2[] = {
5893 "foo.exe",
5894 NULL
5895 };
5896
vladlosevba015a92009-11-17 22:43:15 +00005897 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005898}
5899
5900// Tests parsing --gtest_print_time=F.
5901TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5902 const char* argv[] = {
5903 "foo.exe",
5904 "--gtest_print_time=F",
5905 NULL
5906 };
5907
5908 const char* argv2[] = {
5909 "foo.exe",
5910 NULL
5911 };
5912
vladlosevba015a92009-11-17 22:43:15 +00005913 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005914}
5915
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005916// Tests parsing --gtest_random_seed=number
5917TEST_F(InitGoogleTestTest, RandomSeed) {
5918 const char* argv[] = {
5919 "foo.exe",
5920 "--gtest_random_seed=1000",
5921 NULL
5922 };
5923
5924 const char* argv2[] = {
5925 "foo.exe",
5926 NULL
5927 };
5928
vladlosevba015a92009-11-17 22:43:15 +00005929 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005930}
5931
shiqian4b6829f2008-07-03 22:38:12 +00005932// Tests parsing --gtest_repeat=number
5933TEST_F(InitGoogleTestTest, Repeat) {
5934 const char* argv[] = {
5935 "foo.exe",
5936 "--gtest_repeat=1000",
5937 NULL
5938 };
5939
5940 const char* argv2[] = {
5941 "foo.exe",
5942 NULL
5943 };
5944
vladlosevba015a92009-11-17 22:43:15 +00005945 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
shiqian4b6829f2008-07-03 22:38:12 +00005946}
5947
shiqianca6949f2009-01-10 01:16:33 +00005948// Tests having a --gtest_also_run_disabled_tests flag
5949TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5950 const char* argv[] = {
5951 "foo.exe",
5952 "--gtest_also_run_disabled_tests",
5953 NULL
5954 };
5955
5956 const char* argv2[] = {
5957 "foo.exe",
5958 NULL
5959 };
5960
vladlosevba015a92009-11-17 22:43:15 +00005961 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5962 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00005963}
5964
5965// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5966TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5967 const char* argv[] = {
5968 "foo.exe",
5969 "--gtest_also_run_disabled_tests=1",
5970 NULL
5971 };
5972
5973 const char* argv2[] = {
5974 "foo.exe",
5975 NULL
5976 };
5977
vladlosevba015a92009-11-17 22:43:15 +00005978 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5979 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00005980}
5981
5982// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5983TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5984 const char* argv[] = {
5985 "foo.exe",
5986 "--gtest_also_run_disabled_tests=0",
5987 NULL
5988 };
5989
5990 const char* argv2[] = {
5991 "foo.exe",
5992 NULL
5993 };
5994
vladlosevba015a92009-11-17 22:43:15 +00005995 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5996 Flags::AlsoRunDisabledTests(false), false);
shiqianca6949f2009-01-10 01:16:33 +00005997}
5998
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005999// Tests parsing --gtest_shuffle.
6000TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6001 const char* argv[] = {
6002 "foo.exe",
6003 "--gtest_shuffle",
6004 NULL
6005};
6006
6007 const char* argv2[] = {
6008 "foo.exe",
6009 NULL
6010 };
6011
vladlosevba015a92009-11-17 22:43:15 +00006012 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006013}
6014
6015// Tests parsing --gtest_shuffle=0.
6016TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6017 const char* argv[] = {
6018 "foo.exe",
6019 "--gtest_shuffle=0",
6020 NULL
6021 };
6022
6023 const char* argv2[] = {
6024 "foo.exe",
6025 NULL
6026 };
6027
vladlosevba015a92009-11-17 22:43:15 +00006028 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006029}
6030
6031// Tests parsing a --gtest_shuffle flag that has a "true"
6032// definition.
6033TEST_F(InitGoogleTestTest, ShuffleTrue) {
6034 const char* argv[] = {
6035 "foo.exe",
6036 "--gtest_shuffle=1",
6037 NULL
6038 };
6039
6040 const char* argv2[] = {
6041 "foo.exe",
6042 NULL
6043 };
6044
vladlosevba015a92009-11-17 22:43:15 +00006045 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6046}
6047
6048// Tests parsing --gtest_stack_trace_depth=number.
6049TEST_F(InitGoogleTestTest, StackTraceDepth) {
6050 const char* argv[] = {
6051 "foo.exe",
6052 "--gtest_stack_trace_depth=5",
6053 NULL
6054 };
6055
6056 const char* argv2[] = {
6057 "foo.exe",
6058 NULL
6059 };
6060
6061 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006062}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006063
zhanyong.wanc95489e2010-08-19 22:16:00 +00006064TEST_F(InitGoogleTestTest, StreamResultTo) {
6065 const char* argv[] = {
6066 "foo.exe",
6067 "--gtest_stream_result_to=localhost:1234",
6068 NULL
6069 };
6070
6071 const char* argv2[] = {
6072 "foo.exe",
6073 NULL
6074 };
6075
6076 GTEST_TEST_PARSING_FLAGS_(
6077 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6078}
6079
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006080// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006081TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006082 const char* argv[] = {
6083 "foo.exe",
6084 "--gtest_throw_on_failure",
6085 NULL
6086};
6087
6088 const char* argv2[] = {
6089 "foo.exe",
6090 NULL
6091 };
6092
vladlosevba015a92009-11-17 22:43:15 +00006093 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006094}
6095
6096// Tests parsing --gtest_throw_on_failure=0.
6097TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6098 const char* argv[] = {
6099 "foo.exe",
6100 "--gtest_throw_on_failure=0",
6101 NULL
6102 };
6103
6104 const char* argv2[] = {
6105 "foo.exe",
6106 NULL
6107 };
6108
vladlosevba015a92009-11-17 22:43:15 +00006109 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006110}
6111
6112// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6113// definition.
6114TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6115 const char* argv[] = {
6116 "foo.exe",
6117 "--gtest_throw_on_failure=1",
6118 NULL
6119 };
6120
6121 const char* argv2[] = {
6122 "foo.exe",
6123 NULL
6124 };
6125
vladlosevba015a92009-11-17 22:43:15 +00006126 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006127}
6128
zhanyong.wan4cd62602009-02-23 23:21:55 +00006129#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006130// Tests parsing wide strings.
6131TEST_F(InitGoogleTestTest, WideStrings) {
6132 const wchar_t* argv[] = {
6133 L"foo.exe",
6134 L"--gtest_filter=Foo*",
6135 L"--gtest_list_tests=1",
6136 L"--gtest_break_on_failure",
6137 L"--non_gtest_flag",
6138 NULL
6139 };
6140
6141 const wchar_t* argv2[] = {
6142 L"foo.exe",
6143 L"--non_gtest_flag",
6144 NULL
6145 };
6146
6147 Flags expected_flags;
6148 expected_flags.break_on_failure = true;
6149 expected_flags.filter = "Foo*";
6150 expected_flags.list_tests = true;
6151
vladlosevba015a92009-11-17 22:43:15 +00006152 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00006153}
6154#endif // GTEST_OS_WINDOWS
6155
6156// Tests current_test_info() in UnitTest.
6157class CurrentTestInfoTest : public Test {
6158 protected:
6159 // Tests that current_test_info() returns NULL before the first test in
6160 // the test case is run.
6161 static void SetUpTestCase() {
6162 // There should be no tests running at this point.
6163 const TestInfo* test_info =
6164 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006165 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006166 << "There should be no tests running at this point.";
6167 }
6168
6169 // Tests that current_test_info() returns NULL after the last test in
6170 // the test case has run.
6171 static void TearDownTestCase() {
6172 const TestInfo* test_info =
6173 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006174 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006175 << "There should be no tests running at this point.";
6176 }
6177};
6178
6179// Tests that current_test_info() returns TestInfo for currently running
6180// test by checking the expected test name against the actual one.
6181TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6182 const TestInfo* test_info =
6183 UnitTest::GetInstance()->current_test_info();
6184 ASSERT_TRUE(NULL != test_info)
6185 << "There is a test running so we should have a valid TestInfo.";
6186 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6187 << "Expected the name of the currently running test case.";
6188 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6189 << "Expected the name of the currently running test.";
6190}
6191
6192// Tests that current_test_info() returns TestInfo for currently running
6193// test by checking the expected test name against the actual one. We
6194// use this test to see that the TestInfo object actually changed from
6195// the previous invocation.
6196TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6197 const TestInfo* test_info =
6198 UnitTest::GetInstance()->current_test_info();
6199 ASSERT_TRUE(NULL != test_info)
6200 << "There is a test running so we should have a valid TestInfo.";
6201 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6202 << "Expected the name of the currently running test case.";
6203 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6204 << "Expected the name of the currently running test.";
6205}
6206
6207} // namespace testing
6208
6209// These two lines test that we can define tests in a namespace that
6210// has the name "testing" and is nested in another namespace.
6211namespace my_namespace {
6212namespace testing {
6213
6214// Makes sure that TEST knows to use ::testing::Test instead of
6215// ::my_namespace::testing::Test.
6216class Test {};
6217
6218// Makes sure that an assertion knows to use ::testing::Message instead of
6219// ::my_namespace::testing::Message.
6220class Message {};
6221
6222// Makes sure that an assertion knows to use
6223// ::testing::AssertionResult instead of
6224// ::my_namespace::testing::AssertionResult.
6225class AssertionResult {};
6226
6227// Tests that an assertion that should succeed works as expected.
6228TEST(NestedTestingNamespaceTest, Success) {
6229 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6230}
6231
6232// Tests that an assertion that should fail works as expected.
6233TEST(NestedTestingNamespaceTest, Failure) {
6234 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6235 "This failure is expected.");
6236}
6237
6238} // namespace testing
6239} // namespace my_namespace
6240
6241// Tests that one can call superclass SetUp and TearDown methods--
6242// that is, that they are not private.
6243// No tests are based on this fixture; the test "passes" if it compiles
6244// successfully.
shiqian760af5c2008-08-06 21:43:15 +00006245class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00006246 protected:
6247 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00006248 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00006249 }
6250 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00006251 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00006252 }
6253};
6254
6255// StreamingAssertionsTest tests the streaming versions of a representative
6256// sample of assertions.
6257TEST(StreamingAssertionsTest, Unconditional) {
6258 SUCCEED() << "expected success";
6259 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6260 "expected failure");
6261 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6262 "expected failure");
6263}
6264
zhanyong.wan98efcc42009-04-28 00:28:09 +00006265#ifdef __BORLANDC__
6266// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00006267# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00006268#endif
6269
shiqian4b6829f2008-07-03 22:38:12 +00006270TEST(StreamingAssertionsTest, Truth) {
6271 EXPECT_TRUE(true) << "unexpected failure";
6272 ASSERT_TRUE(true) << "unexpected failure";
6273 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6274 "expected failure");
6275 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6276 "expected failure");
6277}
6278
6279TEST(StreamingAssertionsTest, Truth2) {
6280 EXPECT_FALSE(false) << "unexpected failure";
6281 ASSERT_FALSE(false) << "unexpected failure";
6282 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6283 "expected failure");
6284 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6285 "expected failure");
6286}
6287
zhanyong.wan98efcc42009-04-28 00:28:09 +00006288#ifdef __BORLANDC__
6289// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00006290# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00006291#endif
6292
shiqian4b6829f2008-07-03 22:38:12 +00006293TEST(StreamingAssertionsTest, IntegerEquals) {
6294 EXPECT_EQ(1, 1) << "unexpected failure";
6295 ASSERT_EQ(1, 1) << "unexpected failure";
6296 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6297 "expected failure");
6298 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6299 "expected failure");
6300}
6301
6302TEST(StreamingAssertionsTest, IntegerLessThan) {
6303 EXPECT_LT(1, 2) << "unexpected failure";
6304 ASSERT_LT(1, 2) << "unexpected failure";
6305 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6306 "expected failure");
6307 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6308 "expected failure");
6309}
6310
6311TEST(StreamingAssertionsTest, StringsEqual) {
6312 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6313 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6314 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6315 "expected failure");
6316 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6317 "expected failure");
6318}
6319
6320TEST(StreamingAssertionsTest, StringsNotEqual) {
6321 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6322 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6323 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6324 "expected failure");
6325 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6326 "expected failure");
6327}
6328
6329TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6330 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6331 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6332 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6333 "expected failure");
6334 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6335 "expected failure");
6336}
6337
6338TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6339 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6340 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6341 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6342 "expected failure");
6343 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6344 "expected failure");
6345}
6346
6347TEST(StreamingAssertionsTest, FloatingPointEquals) {
6348 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6349 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6350 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6351 "expected failure");
6352 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6353 "expected failure");
6354}
6355
shiqian9204c8e2008-09-12 20:57:22 +00006356#if GTEST_HAS_EXCEPTIONS
6357
6358TEST(StreamingAssertionsTest, Throw) {
6359 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6360 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6361 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6362 "expected failure", "expected failure");
6363 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6364 "expected failure", "expected failure");
6365}
6366
6367TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00006368 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6369 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00006370 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6371 "expected failure", "expected failure");
6372 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6373 "expected failure", "expected failure");
6374}
6375
6376TEST(StreamingAssertionsTest, AnyThrow) {
6377 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6378 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00006379 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006380 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00006381 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006382 "expected failure", "expected failure");
6383}
6384
6385#endif // GTEST_HAS_EXCEPTIONS
6386
shiqian4b6829f2008-07-03 22:38:12 +00006387// Tests that Google Test correctly decides whether to use colors in the output.
6388
6389TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6390 GTEST_FLAG(color) = "yes";
6391
6392 SetEnv("TERM", "xterm"); // TERM supports colors.
6393 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6394 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6395
6396 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6397 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6398 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6399}
6400
6401TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6402 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6403
6404 GTEST_FLAG(color) = "True";
6405 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6406
6407 GTEST_FLAG(color) = "t";
6408 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6409
6410 GTEST_FLAG(color) = "1";
6411 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6412}
6413
6414TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6415 GTEST_FLAG(color) = "no";
6416
6417 SetEnv("TERM", "xterm"); // TERM supports colors.
6418 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6419 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6420
6421 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6422 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6423 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6424}
6425
6426TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6427 SetEnv("TERM", "xterm"); // TERM supports colors.
6428
6429 GTEST_FLAG(color) = "F";
6430 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6431
6432 GTEST_FLAG(color) = "0";
6433 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6434
6435 GTEST_FLAG(color) = "unknown";
6436 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6437}
6438
6439TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6440 GTEST_FLAG(color) = "auto";
6441
6442 SetEnv("TERM", "xterm"); // TERM supports colors.
6443 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6444 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6445}
6446
6447TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6448 GTEST_FLAG(color) = "auto";
6449
zhanyong.wan4cd62602009-02-23 23:21:55 +00006450#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006451 // On Windows, we ignore the TERM variable as it's usually not set.
6452
6453 SetEnv("TERM", "dumb");
6454 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6455
6456 SetEnv("TERM", "");
6457 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6458
6459 SetEnv("TERM", "xterm");
6460 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6461#else
6462 // On non-Windows platforms, we rely on TERM to determine if the
6463 // terminal supports colors.
6464
6465 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6466 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6467
6468 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6469 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6470
6471 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6472 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6473
6474 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6475 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6476
6477 SetEnv("TERM", "xterm"); // TERM supports colors.
6478 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6479
6480 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6481 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00006482
vladlosev9f254912010-04-22 11:44:59 +00006483 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6484 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6485
6486 SetEnv("TERM", "screen"); // TERM supports colors.
6487 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6488
zhanyong.wana8a582f2009-07-13 19:25:02 +00006489 SetEnv("TERM", "linux"); // TERM supports colors.
6490 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
vladlosev9f254912010-04-22 11:44:59 +00006491
6492 SetEnv("TERM", "cygwin"); // TERM supports colors.
6493 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00006494#endif // GTEST_OS_WINDOWS
6495}
6496
shiqian21d43d12009-01-08 01:10:31 +00006497// Verifies that StaticAssertTypeEq works in a namespace scope.
6498
zhanyong.wan5e255e02011-01-10 18:17:59 +00006499static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6500static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6501 StaticAssertTypeEq<const int, const int>();
shiqian21d43d12009-01-08 01:10:31 +00006502
6503// Verifies that StaticAssertTypeEq works in a class.
6504
6505template <typename T>
6506class StaticAssertTypeEqTestHelper {
6507 public:
6508 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6509};
6510
6511TEST(StaticAssertTypeEqTest, WorksInClass) {
6512 StaticAssertTypeEqTestHelper<bool>();
6513}
6514
6515// Verifies that StaticAssertTypeEq works inside a function.
6516
6517typedef int IntAlias;
6518
6519TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6520 StaticAssertTypeEq<int, IntAlias>();
6521 StaticAssertTypeEq<int*, IntAlias*>();
6522}
6523
vladlosevf904a612008-11-20 01:40:35 +00006524TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6525 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6526
6527 // We don't have a stack walker in Google Test yet.
6528 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6529 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6530}
zhanyong.wan1b171102009-04-07 21:03:22 +00006531
6532TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6533 EXPECT_FALSE(HasNonfatalFailure());
6534}
6535
6536static void FailFatally() { FAIL(); }
6537
6538TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6539 FailFatally();
6540 const bool has_nonfatal_failure = HasNonfatalFailure();
6541 ClearCurrentTestPartResults();
6542 EXPECT_FALSE(has_nonfatal_failure);
6543}
6544
6545TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6546 ADD_FAILURE();
6547 const bool has_nonfatal_failure = HasNonfatalFailure();
6548 ClearCurrentTestPartResults();
6549 EXPECT_TRUE(has_nonfatal_failure);
6550}
6551
6552TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6553 FailFatally();
6554 ADD_FAILURE();
6555 const bool has_nonfatal_failure = HasNonfatalFailure();
6556 ClearCurrentTestPartResults();
6557 EXPECT_TRUE(has_nonfatal_failure);
6558}
6559
6560// A wrapper for calling HasNonfatalFailure outside of a test body.
6561static bool HasNonfatalFailureHelper() {
6562 return testing::Test::HasNonfatalFailure();
6563}
6564
6565TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6566 EXPECT_FALSE(HasNonfatalFailureHelper());
6567}
6568
6569TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6570 ADD_FAILURE();
6571 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6572 ClearCurrentTestPartResults();
6573 EXPECT_TRUE(has_nonfatal_failure);
6574}
6575
6576TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6577 EXPECT_FALSE(HasFailure());
6578}
6579
6580TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6581 FailFatally();
6582 const bool has_failure = HasFailure();
6583 ClearCurrentTestPartResults();
6584 EXPECT_TRUE(has_failure);
6585}
6586
6587TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6588 ADD_FAILURE();
6589 const bool has_failure = HasFailure();
6590 ClearCurrentTestPartResults();
6591 EXPECT_TRUE(has_failure);
6592}
6593
6594TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6595 FailFatally();
6596 ADD_FAILURE();
6597 const bool has_failure = HasFailure();
6598 ClearCurrentTestPartResults();
6599 EXPECT_TRUE(has_failure);
6600}
6601
6602// A wrapper for calling HasFailure outside of a test body.
6603static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6604
6605TEST(HasFailureTest, WorksOutsideOfTestBody) {
6606 EXPECT_FALSE(HasFailureHelper());
6607}
6608
6609TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6610 ADD_FAILURE();
6611 const bool has_failure = HasFailureHelper();
6612 ClearCurrentTestPartResults();
6613 EXPECT_TRUE(has_failure);
6614}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006615
6616class TestListener : public EmptyTestEventListener {
6617 public:
6618 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6619 TestListener(int* on_start_counter, bool* is_destroyed)
6620 : on_start_counter_(on_start_counter),
6621 is_destroyed_(is_destroyed) {}
6622
6623 virtual ~TestListener() {
6624 if (is_destroyed_)
6625 *is_destroyed_ = true;
6626 }
6627
6628 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006629 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006630 if (on_start_counter_ != NULL)
6631 (*on_start_counter_)++;
6632 }
6633
6634 private:
6635 int* on_start_counter_;
6636 bool* is_destroyed_;
6637};
6638
6639// Tests the constructor.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006640TEST(TestEventListenersTest, ConstructionWorks) {
6641 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006642
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006643 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006644 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6645 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6646}
6647
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006648// Tests that the TestEventListeners destructor deletes all the listeners it
zhanyong.wanf39160b2009-09-04 18:30:25 +00006649// owns.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006650TEST(TestEventListenersTest, DestructionWorks) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006651 bool default_result_printer_is_destroyed = false;
6652 bool default_xml_printer_is_destroyed = false;
6653 bool extra_listener_is_destroyed = false;
6654 TestListener* default_result_printer = new TestListener(
6655 NULL, &default_result_printer_is_destroyed);
6656 TestListener* default_xml_printer = new TestListener(
6657 NULL, &default_xml_printer_is_destroyed);
6658 TestListener* extra_listener = new TestListener(
6659 NULL, &extra_listener_is_destroyed);
6660
6661 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006662 TestEventListeners listeners;
6663 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6664 default_result_printer);
6665 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6666 default_xml_printer);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006667 listeners.Append(extra_listener);
6668 }
6669 EXPECT_TRUE(default_result_printer_is_destroyed);
6670 EXPECT_TRUE(default_xml_printer_is_destroyed);
6671 EXPECT_TRUE(extra_listener_is_destroyed);
6672}
6673
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006674// Tests that a listener Append'ed to a TestEventListeners list starts
zhanyong.wanf39160b2009-09-04 18:30:25 +00006675// receiving events.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006676TEST(TestEventListenersTest, Append) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006677 int on_start_counter = 0;
6678 bool is_destroyed = false;
6679 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6680 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006681 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006682 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006683 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006684 *UnitTest::GetInstance());
6685 EXPECT_EQ(1, on_start_counter);
6686 }
6687 EXPECT_TRUE(is_destroyed);
6688}
6689
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006690// Tests that listeners receive events in the order they were appended to
6691// the list, except for *End requests, which must be received in the reverse
6692// order.
zhanyong.wanf39160b2009-09-04 18:30:25 +00006693class SequenceTestingListener : public EmptyTestEventListener {
6694 public:
zhanyong.wan93d13a82010-02-25 01:09:07 +00006695 SequenceTestingListener(std::vector<String>* vector, const char* id)
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006696 : vector_(vector), id_(id) {}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006697
6698 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006699 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006700 vector_->push_back(GetEventDescription("OnTestProgramStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006701 }
6702
6703 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006704 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006705 }
6706
6707 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
6708 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006709 vector_->push_back(GetEventDescription("OnTestIterationStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006710 }
6711
6712 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6713 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006714 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
zhanyong.wanf39160b2009-09-04 18:30:25 +00006715 }
6716
6717 private:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006718 String GetEventDescription(const char* method) {
6719 Message message;
6720 message << id_ << "." << method;
6721 return message.GetString();
6722 }
6723
zhanyong.wan93d13a82010-02-25 01:09:07 +00006724 std::vector<String>* vector_;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006725 const char* const id_;
zhanyong.wand586f9f2009-09-18 16:35:15 +00006726
6727 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006728};
6729
6730TEST(EventListenerTest, AppendKeepsOrder) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006731 std::vector<String> vec;
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006732 TestEventListeners listeners;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006733 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6734 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6735 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6736
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006737 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006738 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006739 ASSERT_EQ(3U, vec.size());
6740 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6741 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6742 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006743
zhanyong.wan93d13a82010-02-25 01:09:07 +00006744 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006745 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006746 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006747 ASSERT_EQ(3U, vec.size());
6748 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6749 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6750 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006751
zhanyong.wan93d13a82010-02-25 01:09:07 +00006752 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006753 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006754 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006755 ASSERT_EQ(3U, vec.size());
6756 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6757 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6758 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006759
zhanyong.wan93d13a82010-02-25 01:09:07 +00006760 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006761 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006762 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006763 ASSERT_EQ(3U, vec.size());
6764 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6765 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6766 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
zhanyong.wanf39160b2009-09-04 18:30:25 +00006767}
6768
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006769// Tests that a listener removed from a TestEventListeners list stops receiving
zhanyong.wanf39160b2009-09-04 18:30:25 +00006770// events and is not deleted when the list is destroyed.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006771TEST(TestEventListenersTest, Release) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006772 int on_start_counter = 0;
6773 bool is_destroyed = false;
6774 // Although Append passes the ownership of this object to the list,
6775 // the following calls release it, and we need to delete it before the
6776 // test ends.
6777 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6778 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006779 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006780 listeners.Append(listener);
6781 EXPECT_EQ(listener, listeners.Release(listener));
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006782 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006783 *UnitTest::GetInstance());
6784 EXPECT_TRUE(listeners.Release(listener) == NULL);
6785 }
6786 EXPECT_EQ(0, on_start_counter);
6787 EXPECT_FALSE(is_destroyed);
6788 delete listener;
6789}
6790
6791// Tests that no events are forwarded when event forwarding is disabled.
6792TEST(EventListenerTest, SuppressEventForwarding) {
6793 int on_start_counter = 0;
6794 TestListener* listener = new TestListener(&on_start_counter, NULL);
6795
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006796 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006797 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006798 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6799 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6800 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6801 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006802 *UnitTest::GetInstance());
6803 EXPECT_EQ(0, on_start_counter);
6804}
6805
zhanyong.wanf39160b2009-09-04 18:30:25 +00006806// Tests that events generated by Google Test are not forwarded in
6807// death test subprocesses.
6808TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
zhanyong.wand541f022009-09-11 06:59:42 +00006809 EXPECT_DEATH_IF_SUPPORTED({
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006810 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006811 *GetUnitTestImpl()->listeners())) << "expected failure";},
6812 "expected failure");
6813}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006814
6815// Tests that a listener installed via SetDefaultResultPrinter() starts
6816// receiving events and is returned via default_result_printer() and that
6817// the previous default_result_printer is removed from the list and deleted.
6818TEST(EventListenerTest, default_result_printer) {
6819 int on_start_counter = 0;
6820 bool is_destroyed = false;
6821 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6822
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006823 TestEventListeners listeners;
6824 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006825
6826 EXPECT_EQ(listener, listeners.default_result_printer());
6827
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006828 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006829 *UnitTest::GetInstance());
6830
6831 EXPECT_EQ(1, on_start_counter);
6832
6833 // Replacing default_result_printer with something else should remove it
6834 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006835 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006836
6837 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6838 EXPECT_TRUE(is_destroyed);
6839
6840 // After broadcasting an event the counter is still the same, indicating
6841 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006842 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006843 *UnitTest::GetInstance());
6844 EXPECT_EQ(1, on_start_counter);
6845}
6846
6847// Tests that the default_result_printer listener stops receiving events
6848// when removed via Release and that is not owned by the list anymore.
6849TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6850 int on_start_counter = 0;
6851 bool is_destroyed = false;
6852 // Although Append passes the ownership of this object to the list,
6853 // the following calls release it, and we need to delete it before the
6854 // test ends.
6855 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6856 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006857 TestEventListeners listeners;
6858 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006859
6860 EXPECT_EQ(listener, listeners.Release(listener));
6861 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6862 EXPECT_FALSE(is_destroyed);
6863
6864 // Broadcasting events now should not affect default_result_printer.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006865 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006866 *UnitTest::GetInstance());
6867 EXPECT_EQ(0, on_start_counter);
6868 }
6869 // Destroying the list should not affect the listener now, too.
6870 EXPECT_FALSE(is_destroyed);
6871 delete listener;
6872}
6873
6874// Tests that a listener installed via SetDefaultXmlGenerator() starts
6875// receiving events and is returned via default_xml_generator() and that
6876// the previous default_xml_generator is removed from the list and deleted.
6877TEST(EventListenerTest, default_xml_generator) {
6878 int on_start_counter = 0;
6879 bool is_destroyed = false;
6880 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6881
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006882 TestEventListeners listeners;
6883 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006884
6885 EXPECT_EQ(listener, listeners.default_xml_generator());
6886
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006887 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006888 *UnitTest::GetInstance());
6889
6890 EXPECT_EQ(1, on_start_counter);
6891
6892 // Replacing default_xml_generator with something else should remove it
6893 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006894 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006895
6896 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6897 EXPECT_TRUE(is_destroyed);
6898
6899 // After broadcasting an event the counter is still the same, indicating
6900 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006901 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006902 *UnitTest::GetInstance());
6903 EXPECT_EQ(1, on_start_counter);
6904}
6905
6906// Tests that the default_xml_generator listener stops receiving events
6907// when removed via Release and that is not owned by the list anymore.
6908TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6909 int on_start_counter = 0;
6910 bool is_destroyed = false;
6911 // Although Append passes the ownership of this object to the list,
6912 // the following calls release it, and we need to delete it before the
6913 // test ends.
6914 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6915 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006916 TestEventListeners listeners;
6917 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006918
6919 EXPECT_EQ(listener, listeners.Release(listener));
6920 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6921 EXPECT_FALSE(is_destroyed);
6922
6923 // Broadcasting events now should not affect default_xml_generator.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006924 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006925 *UnitTest::GetInstance());
6926 EXPECT_EQ(0, on_start_counter);
6927 }
6928 // Destroying the list should not affect the listener now, too.
6929 EXPECT_FALSE(is_destroyed);
6930 delete listener;
6931}
zhanyong.wan1618bb42010-04-13 04:40:32 +00006932
6933// Sanity tests to ensure that the alternative, verbose spellings of
6934// some of the macros work. We don't test them thoroughly as that
6935// would be quite involved. Since their implementations are
6936// straightforward, and they are rarely used, we'll just rely on the
6937// users to tell us when they are broken.
6938GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
6939 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
6940
6941 // GTEST_FAIL is the same as FAIL.
6942 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
6943 "An expected failure");
zhanyong.wan0bfb5632010-09-15 04:56:58 +00006944
6945 // GTEST_ASSERT_XY is the same as ASSERT_XY.
6946
6947 GTEST_ASSERT_EQ(0, 0);
6948 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
6949 "An expected failure");
6950 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
6951 "An expected failure");
6952
6953 GTEST_ASSERT_NE(0, 1);
6954 GTEST_ASSERT_NE(1, 0);
6955 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
6956 "An expected failure");
6957
6958 GTEST_ASSERT_LE(0, 0);
6959 GTEST_ASSERT_LE(0, 1);
6960 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
6961 "An expected failure");
6962
6963 GTEST_ASSERT_LT(0, 1);
6964 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
6965 "An expected failure");
6966 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
6967 "An expected failure");
6968
6969 GTEST_ASSERT_GE(0, 0);
6970 GTEST_ASSERT_GE(1, 0);
6971 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
6972 "An expected failure");
6973
6974 GTEST_ASSERT_GT(1, 0);
6975 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
6976 "An expected failure");
6977 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
6978 "An expected failure");
zhanyong.wan1618bb42010-04-13 04:40:32 +00006979}
zhanyong.wan678f92b2010-05-10 17:11:58 +00006980
6981// Tests for internal utilities necessary for implementation of the universal
6982// printing.
6983// TODO(vladl@google.com): Find a better home for them.
6984
6985class ConversionHelperBase {};
6986class ConversionHelperDerived : public ConversionHelperBase {};
6987
6988// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
6989TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
6990 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
6991 const_true);
6992 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
6993}
6994
6995// Tests that IsAProtocolMessage<T>::value is true when T is
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00006996// proto2::Message or a sub-class of it.
zhanyong.wan678f92b2010-05-10 17:11:58 +00006997TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
6998 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
6999 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
zhanyong.wan678f92b2010-05-10 17:11:58 +00007000}
7001
7002// Tests that IsAProtocolMessage<T>::value is false when T is neither
7003// ProtocolMessage nor a sub-class of it.
7004TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7005 EXPECT_FALSE(IsAProtocolMessage<int>::value);
7006 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7007}
7008
7009// Tests that CompileAssertTypesEqual compiles when the type arguments are
7010// equal.
7011TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7012 CompileAssertTypesEqual<void, void>();
7013 CompileAssertTypesEqual<int*, int*>();
7014}
7015
7016// Tests that RemoveReference does not affect non-reference types.
7017TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7018 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7019 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7020}
7021
7022// Tests that RemoveReference removes reference from reference types.
7023TEST(RemoveReferenceTest, RemovesReference) {
7024 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7025 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7026}
7027
7028// Tests GTEST_REMOVE_REFERENCE_.
7029
7030template <typename T1, typename T2>
7031void TestGTestRemoveReference() {
7032 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7033}
7034
7035TEST(RemoveReferenceTest, MacroVersion) {
7036 TestGTestRemoveReference<int, int>();
7037 TestGTestRemoveReference<const char, const char&>();
7038}
7039
7040
7041// Tests that RemoveConst does not affect non-const types.
7042TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7043 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7044 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7045}
7046
7047// Tests that RemoveConst removes const from const types.
7048TEST(RemoveConstTest, RemovesConst) {
7049 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7050 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7051 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7052}
7053
7054// Tests GTEST_REMOVE_CONST_.
7055
7056template <typename T1, typename T2>
7057void TestGTestRemoveConst() {
7058 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7059}
7060
7061TEST(RemoveConstTest, MacroVersion) {
7062 TestGTestRemoveConst<int, int>();
7063 TestGTestRemoveConst<double&, double&>();
7064 TestGTestRemoveConst<char, const char>();
7065}
7066
zhanyong.wanc3ad6902010-05-17 19:31:00 +00007067// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7068
7069template <typename T1, typename T2>
7070void TestGTestRemoveReferenceAndConst() {
7071 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7072}
7073
7074TEST(RemoveReferenceToConstTest, Works) {
7075 TestGTestRemoveReferenceAndConst<int, int>();
7076 TestGTestRemoveReferenceAndConst<double, double&>();
7077 TestGTestRemoveReferenceAndConst<char, const char>();
7078 TestGTestRemoveReferenceAndConst<char, const char&>();
7079 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7080}
7081
zhanyong.wan678f92b2010-05-10 17:11:58 +00007082// Tests that AddReference does not affect reference types.
7083TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7084 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7085 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7086}
7087
7088// Tests that AddReference adds reference to non-reference types.
7089TEST(AddReferenceTest, AddsReference) {
7090 CompileAssertTypesEqual<int&, AddReference<int>::type>();
7091 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7092}
7093
7094// Tests GTEST_ADD_REFERENCE_.
7095
7096template <typename T1, typename T2>
7097void TestGTestAddReference() {
7098 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7099}
7100
7101TEST(AddReferenceTest, MacroVersion) {
7102 TestGTestAddReference<int&, int>();
7103 TestGTestAddReference<const char&, const char&>();
7104}
7105
7106// Tests GTEST_REFERENCE_TO_CONST_.
7107
7108template <typename T1, typename T2>
7109void TestGTestReferenceToConst() {
7110 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7111}
7112
7113TEST(GTestReferenceToConstTest, Works) {
7114 TestGTestReferenceToConst<const char&, char>();
7115 TestGTestReferenceToConst<const int&, const int>();
7116 TestGTestReferenceToConst<const double&, double>();
7117 TestGTestReferenceToConst<const String&, const String&>();
7118}
7119
7120// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7121TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7122 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7123 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7124 const_false);
7125}
7126
7127// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7128// be implicitly converted to T2.
7129TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7130 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7131 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7132 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7133 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7134 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7135 const ConversionHelperBase&>::value));
7136 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7137 ConversionHelperBase>::value));
7138}
7139
7140// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7141// cannot be implicitly converted to T2.
7142TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7143 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7144 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7145 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7146 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7147 ConversionHelperDerived&>::value));
7148}
7149
7150// Tests IsContainerTest.
7151
7152class NonContainer {};
7153
7154TEST(IsContainerTestTest, WorksForNonContainer) {
7155 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7156 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7157 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7158}
7159
7160TEST(IsContainerTestTest, WorksForContainer) {
7161 EXPECT_EQ(sizeof(IsContainer),
7162 sizeof(IsContainerTest<std::vector<bool> >(0)));
7163 EXPECT_EQ(sizeof(IsContainer),
7164 sizeof(IsContainerTest<std::map<int, double> >(0)));
7165}
7166
7167// Tests ArrayEq().
7168
7169TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7170 EXPECT_TRUE(ArrayEq(5, 5L));
7171 EXPECT_FALSE(ArrayEq('a', 0));
7172}
7173
7174TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7175 const int a[] = { 0, 1 };
7176 long b[] = { 0, 1 };
7177 EXPECT_TRUE(ArrayEq(a, b));
7178 EXPECT_TRUE(ArrayEq(a, 2, b));
7179
7180 b[0] = 2;
7181 EXPECT_FALSE(ArrayEq(a, b));
7182 EXPECT_FALSE(ArrayEq(a, 1, b));
7183}
7184
7185TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7186 const char a[][3] = { "hi", "lo" };
7187 const char b[][3] = { "hi", "lo" };
7188 const char c[][3] = { "hi", "li" };
7189
7190 EXPECT_TRUE(ArrayEq(a, b));
7191 EXPECT_TRUE(ArrayEq(a, 2, b));
7192
7193 EXPECT_FALSE(ArrayEq(a, c));
7194 EXPECT_FALSE(ArrayEq(a, 2, c));
7195}
7196
7197// Tests ArrayAwareFind().
7198
7199TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7200 const char a[] = "hello";
7201 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7202 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7203}
7204
7205TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7206 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7207 const int b[2] = { 2, 3 };
7208 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7209
7210 const int c[2] = { 6, 7 };
7211 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7212}
7213
7214// Tests CopyArray().
7215
7216TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7217 int n = 0;
7218 CopyArray('a', &n);
7219 EXPECT_EQ('a', n);
7220}
7221
7222TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7223 const char a[3] = "hi";
7224 int b[3];
zhanyong.waned1042b2011-03-05 08:04:01 +00007225#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007226 CopyArray(a, &b);
7227 EXPECT_TRUE(ArrayEq(a, b));
zhanyong.waned1042b2011-03-05 08:04:01 +00007228#endif
zhanyong.wan678f92b2010-05-10 17:11:58 +00007229
7230 int c[3];
7231 CopyArray(a, 3, c);
7232 EXPECT_TRUE(ArrayEq(a, c));
7233}
7234
7235TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7236 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7237 int b[2][3];
zhanyong.waned1042b2011-03-05 08:04:01 +00007238#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007239 CopyArray(a, &b);
7240 EXPECT_TRUE(ArrayEq(a, b));
zhanyong.waned1042b2011-03-05 08:04:01 +00007241#endif
zhanyong.wan678f92b2010-05-10 17:11:58 +00007242
7243 int c[2][3];
7244 CopyArray(a, 2, c);
7245 EXPECT_TRUE(ArrayEq(a, c));
7246}
7247
7248// Tests NativeArray.
7249
7250TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7251 const int a[3] = { 0, 1, 2 };
7252 NativeArray<int> na(a, 3, kReference);
7253 EXPECT_EQ(3U, na.size());
7254 EXPECT_EQ(a, na.begin());
7255}
7256
7257TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7258 typedef int Array[2];
7259 Array* a = new Array[1];
7260 (*a)[0] = 0;
7261 (*a)[1] = 1;
7262 NativeArray<int> na(*a, 2, kCopy);
7263 EXPECT_NE(*a, na.begin());
7264 delete[] a;
7265 EXPECT_EQ(0, na.begin()[0]);
7266 EXPECT_EQ(1, na.begin()[1]);
7267
7268 // We rely on the heap checker to verify that na deletes the copy of
7269 // array.
7270}
7271
7272TEST(NativeArrayTest, TypeMembersAreCorrect) {
7273 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7274 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7275
7276 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7277 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7278}
7279
7280TEST(NativeArrayTest, MethodsWork) {
7281 const int a[3] = { 0, 1, 2 };
7282 NativeArray<int> na(a, 3, kCopy);
7283 ASSERT_EQ(3U, na.size());
7284 EXPECT_EQ(3, na.end() - na.begin());
7285
7286 NativeArray<int>::const_iterator it = na.begin();
7287 EXPECT_EQ(0, *it);
7288 ++it;
7289 EXPECT_EQ(1, *it);
7290 it++;
7291 EXPECT_EQ(2, *it);
7292 ++it;
7293 EXPECT_EQ(na.end(), it);
7294
7295 EXPECT_TRUE(na == na);
7296
7297 NativeArray<int> na2(a, 3, kReference);
7298 EXPECT_TRUE(na == na2);
7299
7300 const int b1[3] = { 0, 1, 1 };
7301 const int b2[4] = { 0, 1, 2, 3 };
7302 EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
7303 EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
7304}
7305
7306TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7307 const char a[2][3] = { "hi", "lo" };
7308 NativeArray<char[3]> na(a, 2, kReference);
7309 ASSERT_EQ(2U, na.size());
7310 EXPECT_EQ(a, na.begin());
7311}
zhanyong.wan9748de02010-06-08 22:51:46 +00007312
7313// Tests SkipPrefix().
7314
7315TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7316 const char* const str = "hello";
7317
7318 const char* p = str;
7319 EXPECT_TRUE(SkipPrefix("", &p));
7320 EXPECT_EQ(str, p);
7321
7322 p = str;
7323 EXPECT_TRUE(SkipPrefix("hell", &p));
7324 EXPECT_EQ(str + 4, p);
7325}
7326
7327TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7328 const char* const str = "world";
7329
7330 const char* p = str;
7331 EXPECT_FALSE(SkipPrefix("W", &p));
7332 EXPECT_EQ(str, p);
7333
7334 p = str;
7335 EXPECT_FALSE(SkipPrefix("world!", &p));
7336 EXPECT_EQ(str, p);
7337}