blob: 9b95b138058ac64b208bb1dc8dddcf42dfc561cd [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
35#include <gtest/gtest.h>
zhanyong.wan93d13a82010-02-25 01:09:07 +000036#include <vector>
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000037
38// Verifies that the command line flag variables can be accessed
39// in code once <gtest/gtest.h> has been #included.
40// Do not move it after other #includes.
41TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
42 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
43 || testing::GTEST_FLAG(break_on_failure)
44 || testing::GTEST_FLAG(catch_exceptions)
45 || testing::GTEST_FLAG(color) != "unknown"
46 || testing::GTEST_FLAG(filter) != "unknown"
47 || testing::GTEST_FLAG(list_tests)
48 || testing::GTEST_FLAG(output) != "unknown"
49 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000050 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000051 || testing::GTEST_FLAG(repeat) > 0
52 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000053 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000054 || testing::GTEST_FLAG(stack_trace_depth) > 0
55 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000056 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
57}
58
shiqian4b6829f2008-07-03 22:38:12 +000059#include <gtest/gtest-spi.h>
60
61// Indicates that this translation unit is part of Google Test's
62// implementation. It must come before gtest-internal-inl.h is
63// included, or there will be a compiler error. This trick is to
64// prevent a user from accidentally including gtest-internal-inl.h in
65// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000066#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000067#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000068#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000069
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +000070#include <limits.h> // For INT_MAX.
shiqian4b6829f2008-07-03 22:38:12 +000071#include <stdlib.h>
zhanyong.wan98efcc42009-04-28 00:28:09 +000072#include <time.h>
shiqian4b6829f2008-07-03 22:38:12 +000073
zhanyong.wan98efcc42009-04-28 00:28:09 +000074#include <map>
zhanyong.wan98efcc42009-04-28 00:28:09 +000075
shiqian4b6829f2008-07-03 22:38:12 +000076namespace testing {
77namespace internal {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000078
zhanyong.wanf6d087b2009-09-30 20:23:50 +000079// Provides access to otherwise private parts of the TestEventListeners class
zhanyong.wanf39160b2009-09-04 18:30:25 +000080// that are needed to test it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +000081class TestEventListenersAccessor {
zhanyong.wanf39160b2009-09-04 18:30:25 +000082 public:
zhanyong.wanf6d087b2009-09-30 20:23:50 +000083 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
zhanyong.wanfff03342009-09-24 21:15:59 +000084 return listeners->repeater();
85 }
zhanyong.wanf39160b2009-09-04 18:30:25 +000086
zhanyong.wanf6d087b2009-09-30 20:23:50 +000087 static void SetDefaultResultPrinter(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +000088 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000089 listeners->SetDefaultResultPrinter(listener);
90 }
zhanyong.wanf6d087b2009-09-30 20:23:50 +000091 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +000092 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000093 listeners->SetDefaultXmlGenerator(listener);
94 }
95
zhanyong.wanf6d087b2009-09-30 20:23:50 +000096 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +000097 return listeners.EventForwardingEnabled();
98 }
99
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000100 static void SuppressEventForwarding(TestEventListeners* listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000101 listeners->SuppressEventForwarding();
102 }
103};
104
shiqian4b6829f2008-07-03 22:38:12 +0000105} // namespace internal
106} // namespace testing
107
shiqian760af5c2008-08-06 21:43:15 +0000108using testing::AssertionFailure;
109using testing::AssertionResult;
110using testing::AssertionSuccess;
111using testing::DoubleLE;
zhanyong.wanfff03342009-09-24 21:15:59 +0000112using testing::EmptyTestEventListener;
shiqian760af5c2008-08-06 21:43:15 +0000113using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000114using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000115using testing::GTEST_FLAG(break_on_failure);
116using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000117using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000118using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000119using testing::GTEST_FLAG(filter);
120using testing::GTEST_FLAG(list_tests);
121using testing::GTEST_FLAG(output);
122using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000123using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000124using testing::GTEST_FLAG(repeat);
125using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000126using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000127using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000128using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000129using testing::IsNotSubstring;
130using testing::IsSubstring;
131using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000132using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000133using testing::StaticAssertTypeEq;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000134using testing::Test;
zhanyong.wanfff03342009-09-24 21:15:59 +0000135using testing::TestCase;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000136using testing::TestEventListeners;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000137using testing::TestPartResult;
138using testing::TestPartResultArray;
zhanyong.wanfff03342009-09-24 21:15:59 +0000139using testing::TestProperty;
140using testing::TestResult;
shiqian4b6829f2008-07-03 22:38:12 +0000141using testing::UnitTest;
vladlosevba015a92009-11-17 22:43:15 +0000142using testing::kMaxStackTraceDepth;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000143using testing::internal::AddReference;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000144using testing::internal::AlwaysFalse;
145using testing::internal::AlwaysTrue;
shiqian4b6829f2008-07-03 22:38:12 +0000146using testing::internal::AppendUserMessage;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000147using testing::internal::ArrayAwareFind;
148using testing::internal::ArrayEq;
vladloseve006e682008-08-25 23:11:54 +0000149using testing::internal::CodePointToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000150using testing::internal::CompileAssertTypesEqual;
151using testing::internal::CopyArray;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000152using testing::internal::CountIf;
shiqian4b6829f2008-07-03 22:38:12 +0000153using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000154using testing::internal::FloatingPoint;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000155using testing::internal::ForEach;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000156using testing::internal::FormatTimeInMillisAsSeconds;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000157using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000158using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000159using testing::internal::GetElementOr;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000160using testing::internal::GetNextRandomSeed;
161using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000162using testing::internal::GetTestTypeId;
163using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000164using testing::internal::GetUnitTestImpl;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000165using testing::internal::ImplicitlyConvertible;
shiqian4b6829f2008-07-03 22:38:12 +0000166using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000167using testing::internal::Int32FromEnvOrDie;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000168using testing::internal::IsAProtocolMessage;
169using testing::internal::IsContainer;
170using testing::internal::IsContainerTest;
171using testing::internal::IsNotContainer;
172using testing::internal::NativeArray;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000173using testing::internal::ParseInt32Flag;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000174using testing::internal::RemoveConst;
175using testing::internal::RemoveReference;
zhanyong.wan905074c2009-02-09 18:05:21 +0000176using testing::internal::ShouldRunTestOnShard;
177using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000178using testing::internal::ShouldUseColor;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000179using testing::internal::Shuffle;
180using testing::internal::ShuffleRange;
zhanyong.wan9748de02010-06-08 22:51:46 +0000181using testing::internal::SkipPrefix;
shiqian4b6829f2008-07-03 22:38:12 +0000182using testing::internal::StreamableToString;
183using testing::internal::String;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000184using testing::internal::TestEventListenersAccessor;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000185using testing::internal::TestResultAccessor;
zhanyong.wan85f555a2009-09-21 19:42:03 +0000186using testing::internal::UInt32;
vladloseve006e682008-08-25 23:11:54 +0000187using testing::internal::WideStringToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000188using testing::internal::kCopy;
zhanyong.wanfff03342009-09-24 21:15:59 +0000189using testing::internal::kMaxRandomSeed;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000190using testing::internal::kReference;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000191using testing::internal::kTestTypeIdInGoogleTest;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000192using testing::internal::scoped_ptr;
shiqian4b6829f2008-07-03 22:38:12 +0000193
zhanyong.wancf8a5842010-01-28 21:50:29 +0000194#if GTEST_HAS_STREAM_REDIRECTION_
195using testing::internal::CaptureStdout;
196using testing::internal::GetCapturedStdout;
197#endif // GTEST_HAS_STREAM_REDIRECTION_
198
zhanyong.wanf6fb5322010-03-04 22:15:53 +0000199#if GTEST_IS_THREADSAFE
200using testing::internal::ThreadWithParam;
201#endif
202
zhanyong.wan678f92b2010-05-10 17:11:58 +0000203#if GTEST_HAS_PROTOBUF_
204using ::testing::internal::TestMessage;
205#endif // GTEST_HAS_PROTOBUF_
206
zhanyong.wan93d13a82010-02-25 01:09:07 +0000207class TestingVector : public std::vector<int> {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000208};
209
210::std::ostream& operator<<(::std::ostream& os,
211 const TestingVector& vector) {
212 os << "{ ";
zhanyong.wan93d13a82010-02-25 01:09:07 +0000213 for (size_t i = 0; i < vector.size(); i++) {
214 os << vector[i] << " ";
zhanyong.wanf19450f2009-09-30 23:46:28 +0000215 }
216 os << "}";
217 return os;
218}
219
shiqian4b6829f2008-07-03 22:38:12 +0000220// This line tests that we can define tests in an unnamed namespace.
221namespace {
222
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000223TEST(GetRandomSeedFromFlagTest, HandlesZero) {
224 const int seed = GetRandomSeedFromFlag(0);
225 EXPECT_LE(1, seed);
226 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
227}
228
229TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
230 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
231 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
232 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
233 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
234 GetRandomSeedFromFlag(kMaxRandomSeed));
235}
236
237TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
238 const int seed1 = GetRandomSeedFromFlag(-1);
239 EXPECT_LE(1, seed1);
240 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
241
242 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
243 EXPECT_LE(1, seed2);
244 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
245}
246
247TEST(GetNextRandomSeedTest, WorksForValidInput) {
248 EXPECT_EQ(2, GetNextRandomSeed(1));
249 EXPECT_EQ(3, GetNextRandomSeed(2));
250 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
251 GetNextRandomSeed(kMaxRandomSeed - 1));
252 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
253
254 // We deliberately don't test GetNextRandomSeed() with invalid
255 // inputs, as that requires death tests, which are expensive. This
256 // is fine as GetNextRandomSeed() is internal and has a
257 // straightforward definition.
258}
259
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000260static void ClearCurrentTestPartResults() {
261 TestResultAccessor::ClearTestPartResults(
262 GetUnitTestImpl()->current_test_result());
263}
264
shiqianfe6a9a42008-11-24 20:13:22 +0000265// Tests GetTypeId.
266
267TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
268 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
269 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
270}
271
272class SubClassOfTest : public Test {};
273class AnotherSubClassOfTest : public Test {};
274
275TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
276 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
277 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
278 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
279 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
280 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
281 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
282}
283
284// Verifies that GetTestTypeId() returns the same value, no matter it
285// is called from inside Google Test or outside of it.
286TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
287 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
288}
289
shiqianf0e809a2008-09-26 16:08:30 +0000290// Tests FormatTimeInMillisAsSeconds().
291
292TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000293 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
shiqianf0e809a2008-09-26 16:08:30 +0000294}
295
296TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000297 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
298 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
299 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
300 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
301 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
shiqianf0e809a2008-09-26 16:08:30 +0000302}
303
304TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000305 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
306 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
307 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
308 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
309 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
shiqianf0e809a2008-09-26 16:08:30 +0000310}
311
vladlosev5147b452010-03-17 18:22:59 +0000312#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +0000313
zhanyong.wan98efcc42009-04-28 00:28:09 +0000314#ifdef __BORLANDC__
315// Silences warnings: "Condition is always true", "Unreachable code"
316#pragma option push -w-ccc -w-rch
317#endif
318
shiqiane44602e2008-10-11 07:20:02 +0000319// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000320// pointer literal.
321TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000322 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
323 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000324 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
325 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
326 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000327#ifndef __BORLANDC__
328 // 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));
shiqiane44602e2008-10-11 07:20:02 +0000332 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000333#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.wan98efcc42009-04-28 00:28:09 +0000345#ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +0000346// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan98efcc42009-04-28 00:28:09 +0000347#pragma option pop
348#endif
349
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
vladloseve006e682008-08-25 23:11:54 +0000377 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000378}
379
380// Tests that Unicode code-points that have 12 to 16 bits are encoded
381// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000382TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
383 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000384 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000385 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000386
387 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
vladloseve006e682008-08-25 23:11:54 +0000388 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000389}
390
zhanyong.wan4cd62602009-02-23 23:21:55 +0000391#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000392// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000393// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000394// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000395
396// Tests that Unicode code-points that have 17 to 21 bits are encoded
397// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000398TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
399 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000400 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000401 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000402
vladloseve006e682008-08-25 23:11:54 +0000403 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
404 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
405
406 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
407 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000408}
409
410// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000411TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
412 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000413 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
vladloseve006e682008-08-25 23:11:54 +0000414 CodePointToUtf8(L'\x1234ABCD', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000415}
416
zhanyong.wan4cd62602009-02-23 23:21:55 +0000417#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000418
419// Tests WideStringToUtf8().
420
421// Tests that the NUL character L'\0' is encoded correctly.
422TEST(WideStringToUtf8Test, CanEncodeNul) {
423 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
424 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
425}
426
427// Tests that ASCII strings are encoded correctly.
428TEST(WideStringToUtf8Test, CanEncodeAscii) {
429 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
430 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
431 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
432 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
433}
434
435// Tests that Unicode code-points that have 8 to 11 bits are encoded
436// as 110xxxxx 10xxxxxx.
437TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
438 // 000 1101 0011 => 110-00011 10-010011
439 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
440 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
441
442 // 101 0111 0110 => 110-10101 10-110110
443 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
444 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
445}
446
447// Tests that Unicode code-points that have 12 to 16 bits are encoded
448// as 1110xxxx 10xxxxxx 10xxxxxx.
449TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
450 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
451 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
452 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
453
454 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
455 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
456 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
457}
458
459// Tests that the conversion stops when the function encounters \0 character.
460TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
461 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
462}
463
464// Tests that the conversion stops when the function reaches the limit
465// specified by the 'length' parameter.
466TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
467 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
468}
469
470
zhanyong.wan4cd62602009-02-23 23:21:55 +0000471#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000472// Tests that Unicode code-points that have 17 to 21 bits are encoded
473// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
474// on the systems using UTF-16 encoding.
475TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
476 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
477 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
478 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
479
480 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
481 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
482 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
483}
484
485// Tests that encoding an invalid code-point generates the expected result.
486TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
487 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
488 WideStringToUtf8(L"\xABCDFF", -1).c_str());
489}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000490#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000491// Tests that surrogate pairs are encoded correctly on the systems using
492// UTF-16 encoding in the wide strings.
493TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
494 EXPECT_STREQ("\xF0\x90\x90\x80",
495 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
496}
497
498// Tests that encoding an invalid UTF-16 surrogate pair
499// generates the expected result.
500TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
501 // Leading surrogate is at the end of the string.
502 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
503 // Leading surrogate is not followed by the trailing surrogate.
504 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
505 // Trailing surrogate appearas without a leading surrogate.
506 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
507}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000508#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000509
510// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000511#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000512TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
513 EXPECT_STREQ(
514 "\xF4\x88\x98\xB4"
515 "\xEC\x9D\x8D"
516 "\n"
517 "\xD5\xB6"
518 "\xE0\xA3\x93"
519 "\xF4\x88\x98\xB4",
520 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
521}
522#else
523TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
524 EXPECT_STREQ(
525 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
526 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
527}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000528#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000529
zhanyong.wan85f555a2009-09-21 19:42:03 +0000530// Tests the Random class.
531
532TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
533 testing::internal::Random random(42);
534 EXPECT_DEATH_IF_SUPPORTED(
535 random.Generate(0),
536 "Cannot generate a number in the range \\[0, 0\\)");
537 EXPECT_DEATH_IF_SUPPORTED(
538 random.Generate(testing::internal::Random::kMaxRange + 1),
539 "Generation of a number in \\[0, 2147483649\\) was requested, "
540 "but this can only generate numbers in \\[0, 2147483648\\)");
541}
542
543TEST(RandomTest, GeneratesNumbersWithinRange) {
544 const UInt32 kRange = 10000;
545 testing::internal::Random random(12345);
546 for (int i = 0; i < 10; i++) {
547 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
548 }
549
550 testing::internal::Random random2(testing::internal::Random::kMaxRange);
551 for (int i = 0; i < 10; i++) {
552 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
553 }
554}
555
556TEST(RandomTest, RepeatsWhenReseeded) {
557 const int kSeed = 123;
558 const int kArraySize = 10;
559 const UInt32 kRange = 10000;
560 UInt32 values[kArraySize];
561
562 testing::internal::Random random(kSeed);
563 for (int i = 0; i < kArraySize; i++) {
564 values[i] = random.Generate(kRange);
565 }
566
567 random.Reseed(kSeed);
568 for (int i = 0; i < kArraySize; i++) {
569 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
570 }
571}
572
zhanyong.wan93d13a82010-02-25 01:09:07 +0000573// Tests STL container utilities.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000574
zhanyong.wan93d13a82010-02-25 01:09:07 +0000575// Tests CountIf().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000576
zhanyong.wan93d13a82010-02-25 01:09:07 +0000577static bool IsPositive(int n) { return n > 0; }
578
579TEST(ContainerUtilityTest, CountIf) {
580 std::vector<int> v;
581 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
582
583 v.push_back(-1);
584 v.push_back(0);
585 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
586
587 v.push_back(2);
588 v.push_back(-10);
589 v.push_back(10);
590 EXPECT_EQ(2, CountIf(v, IsPositive));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000591}
592
zhanyong.wan93d13a82010-02-25 01:09:07 +0000593// Tests ForEach().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000594
zhanyong.wan93d13a82010-02-25 01:09:07 +0000595static int g_sum = 0;
596static void Accumulate(int n) { g_sum += n; }
597
598TEST(ContainerUtilityTest, ForEach) {
599 std::vector<int> v;
600 g_sum = 0;
601 ForEach(v, Accumulate);
602 EXPECT_EQ(0, g_sum); // Works for an empty container;
603
604 g_sum = 0;
605 v.push_back(1);
606 ForEach(v, Accumulate);
607 EXPECT_EQ(1, g_sum); // Works for a container with one element.
608
609 g_sum = 0;
610 v.push_back(20);
611 v.push_back(300);
612 ForEach(v, Accumulate);
613 EXPECT_EQ(321, g_sum);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000614}
shiqian4b6829f2008-07-03 22:38:12 +0000615
zhanyong.wan93d13a82010-02-25 01:09:07 +0000616// Tests GetElementOr().
617TEST(ContainerUtilityTest, GetElementOr) {
618 std::vector<char> a;
619 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000620
zhanyong.wan93d13a82010-02-25 01:09:07 +0000621 a.push_back('a');
622 a.push_back('b');
623 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
624 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
625 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
626 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000627}
628
zhanyong.wan93d13a82010-02-25 01:09:07 +0000629TEST(ContainerUtilityDeathTest, ShuffleRange) {
630 std::vector<int> a;
631 a.push_back(0);
632 a.push_back(1);
633 a.push_back(2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000634 testing::internal::Random random(1);
635
636 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000637 ShuffleRange(&random, -1, 1, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000638 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
639 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000640 ShuffleRange(&random, 4, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000641 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
642 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000643 ShuffleRange(&random, 3, 2, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000644 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
645 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000646 ShuffleRange(&random, 3, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000647 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
648}
649
650class VectorShuffleTest : public Test {
651 protected:
652 static const int kVectorSize = 20;
653
654 VectorShuffleTest() : random_(1) {
655 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000656 vector_.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000657 }
658 }
659
660 static bool VectorIsCorrupt(const TestingVector& vector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000661 if (kVectorSize != static_cast<int>(vector.size())) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000662 return true;
663 }
664
665 bool found_in_vector[kVectorSize] = { false };
zhanyong.wan93d13a82010-02-25 01:09:07 +0000666 for (size_t i = 0; i < vector.size(); i++) {
667 const int e = vector[i];
zhanyong.wanf19450f2009-09-30 23:46:28 +0000668 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
669 return true;
670 }
671 found_in_vector[e] = true;
672 }
673
674 // Vector size is correct, elements' range is correct, no
675 // duplicate elements. Therefore no corruption has occurred.
676 return false;
677 }
678
679 static bool VectorIsNotCorrupt(const TestingVector& vector) {
680 return !VectorIsCorrupt(vector);
681 }
682
683 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
684 for (int i = begin; i < end; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000685 if (i != vector[i]) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000686 return true;
687 }
688 }
689 return false;
690 }
691
692 static bool RangeIsUnshuffled(
693 const TestingVector& vector, int begin, int end) {
694 return !RangeIsShuffled(vector, begin, end);
695 }
696
697 static bool VectorIsShuffled(const TestingVector& vector) {
zhanyong.wanb03ca472010-02-25 22:15:27 +0000698 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
zhanyong.wanf19450f2009-09-30 23:46:28 +0000699 }
700
701 static bool VectorIsUnshuffled(const TestingVector& vector) {
702 return !VectorIsShuffled(vector);
703 }
704
705 testing::internal::Random random_;
706 TestingVector vector_;
707}; // class VectorShuffleTest
708
709const int VectorShuffleTest::kVectorSize;
710
711TEST_F(VectorShuffleTest, HandlesEmptyRange) {
712 // Tests an empty range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000713 ShuffleRange(&random_, 0, 0, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000714 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
715 ASSERT_PRED1(VectorIsUnshuffled, vector_);
716
717 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000718 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000719 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
720 ASSERT_PRED1(VectorIsUnshuffled, vector_);
721
722 // ...at the end...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000723 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000724 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
725 ASSERT_PRED1(VectorIsUnshuffled, vector_);
726
727 // ...and past the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000728 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000729 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
730 ASSERT_PRED1(VectorIsUnshuffled, vector_);
731}
732
733TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
734 // Tests a size one range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000735 ShuffleRange(&random_, 0, 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000736 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
737 ASSERT_PRED1(VectorIsUnshuffled, vector_);
738
739 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000740 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000741 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
742 ASSERT_PRED1(VectorIsUnshuffled, vector_);
743
744 // ...and at the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000745 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000746 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
747 ASSERT_PRED1(VectorIsUnshuffled, vector_);
748}
749
750// Because we use our own random number generator and a fixed seed,
751// we can guarantee that the following "random" tests will succeed.
752
753TEST_F(VectorShuffleTest, ShufflesEntireVector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000754 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000755 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
756 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
757
758 // Tests the first and last elements in particular to ensure that
759 // there are no off-by-one problems in our shuffle algorithm.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000760 EXPECT_NE(0, vector_[0]);
761 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000762}
763
764TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
765 const int kRangeSize = kVectorSize/2;
766
zhanyong.wan93d13a82010-02-25 01:09:07 +0000767 ShuffleRange(&random_, 0, kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000768
769 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
770 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
771 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
772}
773
774TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
775 const int kRangeSize = kVectorSize / 2;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000776 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000777
778 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
779 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
780 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
781}
782
783TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
784 int kRangeSize = kVectorSize/3;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000785 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000786
787 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
788 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
789 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
790 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
791}
792
793TEST_F(VectorShuffleTest, ShufflesRepeatably) {
794 TestingVector vector2;
795 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000796 vector2.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000797 }
798
799 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000800 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000801 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000802 Shuffle(&random_, &vector2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000803
804 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
805 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
806
807 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000808 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
zhanyong.wanf19450f2009-09-30 23:46:28 +0000809 }
810}
811
zhanyong.wanf39160b2009-09-04 18:30:25 +0000812// Tests the size of the AssertHelper class.
shiqian4b6829f2008-07-03 22:38:12 +0000813
zhanyong.wanf39160b2009-09-04 18:30:25 +0000814TEST(AssertHelperTest, AssertHelperIsSmall) {
zhanyong.wan89be5762009-09-01 18:53:56 +0000815 // To avoid breaking clients that use lots of assertions in one
zhanyong.wanf39160b2009-09-04 18:30:25 +0000816 // function, we cannot grow the size of AssertHelper.
817 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
zhanyong.wan89be5762009-09-01 18:53:56 +0000818}
819
zhanyong.wanf39160b2009-09-04 18:30:25 +0000820// Tests the String class.
821
shiqian4b6829f2008-07-03 22:38:12 +0000822// Tests String's constructors.
823TEST(StringTest, Constructors) {
824 // Default ctor.
825 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +0000826 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
827 // pointers with NULL isn't supported on all platforms.
zhanyong.wan89be5762009-09-01 18:53:56 +0000828 EXPECT_EQ(0U, s1.length());
shiqiandd4a17b2008-07-31 18:34:08 +0000829 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +0000830
831 // Implicitly constructs from a C-string.
832 String s2 = "Hi";
zhanyong.wan89be5762009-09-01 18:53:56 +0000833 EXPECT_EQ(2U, s2.length());
shiqian4b6829f2008-07-03 22:38:12 +0000834 EXPECT_STREQ("Hi", s2.c_str());
835
836 // Constructs from a C-string and a length.
837 String s3("hello", 3);
zhanyong.wan89be5762009-09-01 18:53:56 +0000838 EXPECT_EQ(3U, s3.length());
shiqian4b6829f2008-07-03 22:38:12 +0000839 EXPECT_STREQ("hel", s3.c_str());
840
zhanyong.wan89be5762009-09-01 18:53:56 +0000841 // The empty String should be created when String is constructed with
842 // a NULL pointer and length 0.
843 EXPECT_EQ(0U, String(NULL, 0).length());
844 EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
845
846 // Constructs a String that contains '\0'.
847 String s4("a\0bcd", 4);
848 EXPECT_EQ(4U, s4.length());
849 EXPECT_EQ('a', s4.c_str()[0]);
850 EXPECT_EQ('\0', s4.c_str()[1]);
851 EXPECT_EQ('b', s4.c_str()[2]);
852 EXPECT_EQ('c', s4.c_str()[3]);
853
854 // Copy ctor where the source is NULL.
855 const String null_str;
856 String s5 = null_str;
857 EXPECT_TRUE(s5.c_str() == NULL);
858
859 // Copy ctor where the source isn't NULL.
860 String s6 = s3;
861 EXPECT_EQ(3U, s6.length());
862 EXPECT_STREQ("hel", s6.c_str());
863
864 // Copy ctor where the source contains '\0'.
865 String s7 = s4;
866 EXPECT_EQ(4U, s7.length());
867 EXPECT_EQ('a', s7.c_str()[0]);
868 EXPECT_EQ('\0', s7.c_str()[1]);
869 EXPECT_EQ('b', s7.c_str()[2]);
870 EXPECT_EQ('c', s7.c_str()[3]);
shiqian4b6829f2008-07-03 22:38:12 +0000871}
872
vladlosevf179f4e2008-11-26 20:48:45 +0000873TEST(StringTest, ConvertsFromStdString) {
874 // An empty std::string.
875 const std::string src1("");
876 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000877 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000878 EXPECT_STREQ("", dest1.c_str());
879
880 // A normal std::string.
881 const std::string src2("Hi");
882 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000883 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000884 EXPECT_STREQ("Hi", dest2.c_str());
885
886 // An std::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000887 const char src3[] = "a\0b";
vladlosevf179f4e2008-11-26 20:48:45 +0000888 const String dest3 = std::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000889 EXPECT_EQ(sizeof(src3), dest3.length());
890 EXPECT_EQ('a', dest3.c_str()[0]);
891 EXPECT_EQ('\0', dest3.c_str()[1]);
892 EXPECT_EQ('b', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000893}
894
895TEST(StringTest, ConvertsToStdString) {
896 // An empty String.
897 const String src1("");
898 const std::string dest1 = src1;
899 EXPECT_EQ("", dest1);
900
901 // A normal String.
902 const String src2("Hi");
903 const std::string dest2 = src2;
904 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000905
906 // A String containing a '\0'.
907 const String src3("x\0y", 3);
908 const std::string dest3 = src3;
909 EXPECT_EQ(std::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000910}
911
vladlosevf179f4e2008-11-26 20:48:45 +0000912#if GTEST_HAS_GLOBAL_STRING
913
914TEST(StringTest, ConvertsFromGlobalString) {
915 // An empty ::string.
916 const ::string src1("");
917 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000918 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000919 EXPECT_STREQ("", dest1.c_str());
920
921 // A normal ::string.
922 const ::string src2("Hi");
923 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000924 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000925 EXPECT_STREQ("Hi", dest2.c_str());
926
927 // An ::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000928 const char src3[] = "x\0y";
vladlosevf179f4e2008-11-26 20:48:45 +0000929 const String dest3 = ::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000930 EXPECT_EQ(sizeof(src3), dest3.length());
931 EXPECT_EQ('x', dest3.c_str()[0]);
932 EXPECT_EQ('\0', dest3.c_str()[1]);
933 EXPECT_EQ('y', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000934}
935
936TEST(StringTest, ConvertsToGlobalString) {
937 // An empty String.
938 const String src1("");
939 const ::string dest1 = src1;
940 EXPECT_EQ("", dest1);
941
942 // A normal String.
943 const String src2("Hi");
944 const ::string dest2 = src2;
945 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000946
947 const String src3("x\0y", 3);
948 const ::string dest3 = src3;
949 EXPECT_EQ(::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000950}
951
952#endif // GTEST_HAS_GLOBAL_STRING
953
shiqian4b6829f2008-07-03 22:38:12 +0000954// Tests String::ShowCStringQuoted().
955TEST(StringTest, ShowCStringQuoted) {
956 EXPECT_STREQ("(null)",
957 String::ShowCStringQuoted(NULL).c_str());
958 EXPECT_STREQ("\"\"",
959 String::ShowCStringQuoted("").c_str());
960 EXPECT_STREQ("\"foo\"",
961 String::ShowCStringQuoted("foo").c_str());
962}
963
zhanyong.wan89be5762009-09-01 18:53:56 +0000964// Tests String::empty().
965TEST(StringTest, Empty) {
966 EXPECT_TRUE(String("").empty());
967 EXPECT_FALSE(String().empty());
968 EXPECT_FALSE(String(NULL).empty());
969 EXPECT_FALSE(String("a").empty());
970 EXPECT_FALSE(String("\0", 1).empty());
971}
972
973// Tests String::Compare().
974TEST(StringTest, Compare) {
975 // NULL vs NULL.
976 EXPECT_EQ(0, String().Compare(String()));
977
978 // NULL vs non-NULL.
979 EXPECT_EQ(-1, String().Compare(String("")));
980
981 // Non-NULL vs NULL.
982 EXPECT_EQ(1, String("").Compare(String()));
983
984 // The following covers non-NULL vs non-NULL.
985
986 // "" vs "".
987 EXPECT_EQ(0, String("").Compare(String("")));
988
989 // "" vs non-"".
990 EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
991 EXPECT_EQ(-1, String("").Compare(" "));
992
993 // Non-"" vs "".
994 EXPECT_EQ(1, String("a").Compare(String("")));
995
996 // The following covers non-"" vs non-"".
997
998 // Same length and equal.
999 EXPECT_EQ(0, String("a").Compare(String("a")));
1000
1001 // Same length and different.
1002 EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
1003 EXPECT_EQ(1, String("b").Compare(String("a")));
1004
1005 // Different lengths.
1006 EXPECT_EQ(-1, String("a").Compare(String("ab")));
1007 EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
1008 EXPECT_EQ(1, String("abc").Compare(String("aacd")));
1009}
1010
shiqian4b6829f2008-07-03 22:38:12 +00001011// Tests String::operator==().
1012TEST(StringTest, Equals) {
1013 const String null(NULL);
1014 EXPECT_TRUE(null == NULL); // NOLINT
1015 EXPECT_FALSE(null == ""); // NOLINT
1016 EXPECT_FALSE(null == "bar"); // NOLINT
1017
1018 const String empty("");
1019 EXPECT_FALSE(empty == NULL); // NOLINT
1020 EXPECT_TRUE(empty == ""); // NOLINT
1021 EXPECT_FALSE(empty == "bar"); // NOLINT
1022
1023 const String foo("foo");
1024 EXPECT_FALSE(foo == NULL); // NOLINT
1025 EXPECT_FALSE(foo == ""); // NOLINT
1026 EXPECT_FALSE(foo == "bar"); // NOLINT
1027 EXPECT_TRUE(foo == "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001028
1029 const String bar("x\0y", 3);
1030 EXPECT_FALSE(bar == "x");
shiqian4b6829f2008-07-03 22:38:12 +00001031}
1032
1033// Tests String::operator!=().
1034TEST(StringTest, NotEquals) {
1035 const String null(NULL);
1036 EXPECT_FALSE(null != NULL); // NOLINT
1037 EXPECT_TRUE(null != ""); // NOLINT
1038 EXPECT_TRUE(null != "bar"); // NOLINT
1039
1040 const String empty("");
1041 EXPECT_TRUE(empty != NULL); // NOLINT
1042 EXPECT_FALSE(empty != ""); // NOLINT
1043 EXPECT_TRUE(empty != "bar"); // NOLINT
1044
1045 const String foo("foo");
1046 EXPECT_TRUE(foo != NULL); // NOLINT
1047 EXPECT_TRUE(foo != ""); // NOLINT
1048 EXPECT_TRUE(foo != "bar"); // NOLINT
1049 EXPECT_FALSE(foo != "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001050
1051 const String bar("x\0y", 3);
1052 EXPECT_TRUE(bar != "x");
1053}
1054
1055// Tests String::length().
1056TEST(StringTest, Length) {
1057 EXPECT_EQ(0U, String().length());
1058 EXPECT_EQ(0U, String("").length());
1059 EXPECT_EQ(2U, String("ab").length());
1060 EXPECT_EQ(3U, String("a\0b", 3).length());
shiqian4b6829f2008-07-03 22:38:12 +00001061}
1062
1063// Tests String::EndsWith().
1064TEST(StringTest, EndsWith) {
1065 EXPECT_TRUE(String("foobar").EndsWith("bar"));
1066 EXPECT_TRUE(String("foobar").EndsWith(""));
1067 EXPECT_TRUE(String("").EndsWith(""));
1068
1069 EXPECT_FALSE(String("foobar").EndsWith("foo"));
1070 EXPECT_FALSE(String("").EndsWith("foo"));
1071}
1072
1073// Tests String::EndsWithCaseInsensitive().
1074TEST(StringTest, EndsWithCaseInsensitive) {
1075 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
1076 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
1077 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
1078 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
1079
1080 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
1081 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
1082 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
1083}
1084
zhanyong.wan98efcc42009-04-28 00:28:09 +00001085// C++Builder's preprocessor is buggy; it fails to expand macros that
1086// appear in macro parameters after wide char literals. Provide an alias
1087// for NULL as a workaround.
1088static const wchar_t* const kNull = NULL;
1089
shiqiane8ff1482008-09-08 17:55:52 +00001090// Tests String::CaseInsensitiveWideCStringEquals
1091TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1092 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001093 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1094 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1095 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1096 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +00001097 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1098 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1099 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1100}
1101
shiqian4b6829f2008-07-03 22:38:12 +00001102// Tests that NULL can be assigned to a String.
1103TEST(StringTest, CanBeAssignedNULL) {
1104 const String src(NULL);
1105 String dest;
1106
1107 dest = src;
1108 EXPECT_STREQ(NULL, dest.c_str());
1109}
1110
1111// Tests that the empty string "" can be assigned to a String.
1112TEST(StringTest, CanBeAssignedEmpty) {
1113 const String src("");
1114 String dest;
1115
1116 dest = src;
1117 EXPECT_STREQ("", dest.c_str());
1118}
1119
1120// Tests that a non-empty string can be assigned to a String.
1121TEST(StringTest, CanBeAssignedNonEmpty) {
1122 const String src("hello");
1123 String dest;
shiqian4b6829f2008-07-03 22:38:12 +00001124 dest = src;
zhanyong.wan89be5762009-09-01 18:53:56 +00001125 EXPECT_EQ(5U, dest.length());
shiqian4b6829f2008-07-03 22:38:12 +00001126 EXPECT_STREQ("hello", dest.c_str());
zhanyong.wan89be5762009-09-01 18:53:56 +00001127
1128 const String src2("x\0y", 3);
1129 String dest2;
1130 dest2 = src2;
1131 EXPECT_EQ(3U, dest2.length());
1132 EXPECT_EQ('x', dest2.c_str()[0]);
1133 EXPECT_EQ('\0', dest2.c_str()[1]);
1134 EXPECT_EQ('y', dest2.c_str()[2]);
shiqian4b6829f2008-07-03 22:38:12 +00001135}
1136
1137// Tests that a String can be assigned to itself.
1138TEST(StringTest, CanBeAssignedSelf) {
1139 String dest("hello");
1140
1141 dest = dest;
1142 EXPECT_STREQ("hello", dest.c_str());
1143}
1144
vladlosev673a0cb2010-02-03 02:27:02 +00001145// Sun Studio < 12 incorrectly rejects this code due to an overloading
1146// ambiguity.
1147#if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
zhanyong.wan89be5762009-09-01 18:53:56 +00001148// Tests streaming a String.
1149TEST(StringTest, Streams) {
1150 EXPECT_EQ(StreamableToString(String()), "(null)");
1151 EXPECT_EQ(StreamableToString(String("")), "");
1152 EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
1153}
vladlosev673a0cb2010-02-03 02:27:02 +00001154#endif
zhanyong.wan89be5762009-09-01 18:53:56 +00001155
zhanyong.wanf39160b2009-09-04 18:30:25 +00001156// Tests that String::Format() works.
1157TEST(StringTest, FormatWorks) {
1158 // Normal case: the format spec is valid, the arguments match the
1159 // spec, and the result is < 4095 characters.
1160 EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
1161
1162 // Edge case: the result is 4095 characters.
1163 char buffer[4096];
1164 const size_t kSize = sizeof(buffer);
1165 memset(buffer, 'a', kSize - 1);
1166 buffer[kSize - 1] = '\0';
1167 EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
1168
1169 // The result needs to be 4096 characters, exceeding Format()'s limit.
1170 EXPECT_STREQ("<formatting error or buffer exceeded>",
1171 String::Format("x%s", buffer).c_str());
1172
1173#if GTEST_OS_LINUX
1174 // On Linux, invalid format spec should lead to an error message.
1175 // In other environment (e.g. MSVC on Windows), String::Format() may
1176 // simply ignore a bad format spec, so this assertion is run on
1177 // Linux only.
1178 EXPECT_STREQ("<formatting error or buffer exceeded>",
1179 String::Format("%").c_str());
1180#endif
1181}
1182
zhanyong.wan4cd62602009-02-23 23:21:55 +00001183#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00001184
1185// Tests String::ShowWideCString().
1186TEST(StringTest, ShowWideCString) {
1187 EXPECT_STREQ("(null)",
1188 String::ShowWideCString(NULL).c_str());
1189 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1190 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1191}
1192
1193// Tests String::ShowWideCStringQuoted().
1194TEST(StringTest, ShowWideCStringQuoted) {
1195 EXPECT_STREQ("(null)",
1196 String::ShowWideCStringQuoted(NULL).c_str());
1197 EXPECT_STREQ("L\"\"",
1198 String::ShowWideCStringQuoted(L"").c_str());
1199 EXPECT_STREQ("L\"foo\"",
1200 String::ShowWideCStringQuoted(L"foo").c_str());
1201}
1202
zhanyong.wanfff03342009-09-24 21:15:59 +00001203#if GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001204TEST(StringTest, AnsiAndUtf16Null) {
1205 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1206 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1207}
1208
1209TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1210 const char* ansi = String::Utf16ToAnsi(L"str");
1211 EXPECT_STREQ("str", ansi);
1212 delete [] ansi;
1213 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001214 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001215 delete [] utf16;
1216}
1217
1218TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1219 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1220 EXPECT_STREQ(".:\\ \"*?", ansi);
1221 delete [] ansi;
1222 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001223 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001224 delete [] utf16;
1225}
zhanyong.wanfff03342009-09-24 21:15:59 +00001226#endif // GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001227
shiqian4b6829f2008-07-03 22:38:12 +00001228#endif // GTEST_OS_WINDOWS
1229
1230// Tests TestProperty construction.
1231TEST(TestPropertyTest, StringValue) {
1232 TestProperty property("key", "1");
1233 EXPECT_STREQ("key", property.key());
1234 EXPECT_STREQ("1", property.value());
1235}
1236
1237// Tests TestProperty replacing a value.
1238TEST(TestPropertyTest, ReplaceStringValue) {
1239 TestProperty property("key", "1");
1240 EXPECT_STREQ("1", property.value());
1241 property.SetValue("2");
1242 EXPECT_STREQ("2", property.value());
1243}
1244
zhanyong.wan98efcc42009-04-28 00:28:09 +00001245// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1246// functions (i.e. their definitions cannot be inlined at the call
1247// sites), or C++Builder won't compile the code.
1248static void AddFatalFailure() {
1249 FAIL() << "Expected fatal failure.";
1250}
1251
1252static void AddNonfatalFailure() {
1253 ADD_FAILURE() << "Expected non-fatal failure.";
1254}
1255
shiqiane44602e2008-10-11 07:20:02 +00001256class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001257 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001258 enum FailureMode {
1259 FATAL_FAILURE,
1260 NONFATAL_FAILURE
1261 };
1262 static void AddFailure(FailureMode failure) {
1263 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001264 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001265 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001266 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001267 }
1268 }
shiqian4b6829f2008-07-03 22:38:12 +00001269};
1270
shiqian4b6829f2008-07-03 22:38:12 +00001271// Tests that ScopedFakeTestPartResultReporter intercepts test
1272// failures.
shiqiane44602e2008-10-11 07:20:02 +00001273TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001274 TestPartResultArray results;
1275 {
shiqiane44602e2008-10-11 07:20:02 +00001276 ScopedFakeTestPartResultReporter reporter(
1277 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1278 &results);
1279 AddFailure(NONFATAL_FAILURE);
1280 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001281 }
1282
1283 EXPECT_EQ(2, results.size());
1284 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1285 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1286}
1287
shiqiane44602e2008-10-11 07:20:02 +00001288TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1289 TestPartResultArray results;
1290 {
1291 // Tests, that the deprecated constructor still works.
1292 ScopedFakeTestPartResultReporter reporter(&results);
1293 AddFailure(NONFATAL_FAILURE);
1294 }
1295 EXPECT_EQ(1, results.size());
1296}
1297
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001298#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001299
1300class ScopedFakeTestPartResultReporterWithThreadsTest
1301 : public ScopedFakeTestPartResultReporterTest {
1302 protected:
1303 static void AddFailureInOtherThread(FailureMode failure) {
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001304 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1305 thread.Join();
shiqiane44602e2008-10-11 07:20:02 +00001306 }
1307};
1308
1309TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1310 InterceptsTestFailuresInAllThreads) {
1311 TestPartResultArray results;
1312 {
1313 ScopedFakeTestPartResultReporter reporter(
1314 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1315 AddFailure(NONFATAL_FAILURE);
1316 AddFailure(FATAL_FAILURE);
1317 AddFailureInOtherThread(NONFATAL_FAILURE);
1318 AddFailureInOtherThread(FATAL_FAILURE);
1319 }
1320
1321 EXPECT_EQ(4, results.size());
1322 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1323 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1324 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1325 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1326}
1327
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001328#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001329
zhanyong.wan98efcc42009-04-28 00:28:09 +00001330// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1331// work even if the failure is generated in a called function rather than
1332// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001333
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001334typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001335
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001336TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001337 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001338}
1339
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001340TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1341 // We have another test below to verify that the macro catches fatal
1342 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001343 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001344 "Expected fatal failure.");
1345}
1346
zhanyong.wan98efcc42009-04-28 00:28:09 +00001347#ifdef __BORLANDC__
1348// Silences warnings: "Condition is always true"
1349#pragma option push -w-ccc
1350#endif
1351
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001352// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1353// function even when the statement in it contains ASSERT_*.
1354
1355int NonVoidFunction() {
1356 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1357 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1358 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001359}
1360
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001361TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1362 NonVoidFunction();
1363}
1364
1365// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1366// current function even though 'statement' generates a fatal failure.
1367
1368void DoesNotAbortHelper(bool* aborted) {
1369 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1370 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1371
1372 *aborted = false;
1373}
1374
zhanyong.wan98efcc42009-04-28 00:28:09 +00001375#ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +00001376// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001377#pragma option pop
1378#endif
1379
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001380TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1381 bool aborted = true;
1382 DoesNotAbortHelper(&aborted);
1383 EXPECT_FALSE(aborted);
1384}
1385
1386// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1387// statement that contains a macro which expands to code containing an
1388// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001389
1390static int global_var = 0;
1391#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1392
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001393TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
vladlosevd6b49412010-04-07 05:32:34 +00001394#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
zhanyong.wan98efcc42009-04-28 00:28:09 +00001395 // ICE's in C++Builder 2007.
shiqiane44602e2008-10-11 07:20:02 +00001396 EXPECT_FATAL_FAILURE({
1397 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001398 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001399 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001400#endif
shiqiane44602e2008-10-11 07:20:02 +00001401
1402 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1403 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001404 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001405 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001406}
shiqiane44602e2008-10-11 07:20:02 +00001407
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001408// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1409
1410typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1411
1412TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001413 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001414 "Expected non-fatal failure.");
1415}
1416
1417TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1418 // We have another test below to verify that the macro catches
1419 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001420 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001421 "Expected non-fatal failure.");
1422}
1423
1424// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1425// statement that contains a macro which expands to code containing an
1426// unprotected comma.
1427TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001428 EXPECT_NONFATAL_FAILURE({
1429 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001430 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001431 }, "");
1432
1433 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1434 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001435 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001436 }, "");
1437}
1438
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001439#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001440
1441typedef ScopedFakeTestPartResultReporterWithThreadsTest
1442 ExpectFailureWithThreadsTest;
1443
1444TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1445 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1446 "Expected fatal failure.");
1447}
1448
1449TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1450 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1451 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1452}
1453
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001454#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001455
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001456// Tests the TestProperty class.
1457
1458TEST(TestPropertyTest, ConstructorWorks) {
1459 const TestProperty property("key", "value");
1460 EXPECT_STREQ("key", property.key());
1461 EXPECT_STREQ("value", property.value());
1462}
1463
1464TEST(TestPropertyTest, SetValue) {
1465 TestProperty property("key", "value_1");
1466 EXPECT_STREQ("key", property.key());
1467 property.SetValue("value_2");
1468 EXPECT_STREQ("key", property.key());
1469 EXPECT_STREQ("value_2", property.value());
1470}
1471
shiqian4b6829f2008-07-03 22:38:12 +00001472// Tests the TestResult class
1473
1474// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001475class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001476 protected:
zhanyong.wan93d13a82010-02-25 01:09:07 +00001477 typedef std::vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001478
1479 // We make use of 2 TestPartResult objects,
1480 TestPartResult * pr1, * pr2;
1481
1482 // ... and 3 TestResult objects.
1483 TestResult * r0, * r1, * r2;
1484
1485 virtual void SetUp() {
1486 // pr1 is for success.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001487 pr1 = new TestPartResult(TestPartResult::kSuccess,
1488 "foo/bar.cc",
1489 10,
1490 "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001491
1492 // pr2 is for fatal failure.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001493 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1494 "foo/bar.cc",
shiqian760af5c2008-08-06 21:43:15 +00001495 -1, // This line number means "unknown"
1496 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001497
1498 // Creates the TestResult objects.
1499 r0 = new TestResult();
1500 r1 = new TestResult();
1501 r2 = new TestResult();
1502
1503 // In order to test TestResult, we need to modify its internal
zhanyong.wan93d13a82010-02-25 01:09:07 +00001504 // state, in particular the TestPartResult vector it holds.
1505 // test_part_results() returns a const reference to this vector.
shiqian4b6829f2008-07-03 22:38:12 +00001506 // We cast it to a non-const object s.t. it can be modified (yes,
1507 // this is a hack).
zhanyong.wan93d13a82010-02-25 01:09:07 +00001508 TPRVector* results1 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001509 &TestResultAccessor::test_part_results(*r1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001510 TPRVector* results2 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001511 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001512
1513 // r0 is an empty TestResult.
1514
1515 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001516 results1->push_back(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001517
1518 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001519 results2->push_back(*pr1);
1520 results2->push_back(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001521 }
1522
1523 virtual void TearDown() {
1524 delete pr1;
1525 delete pr2;
1526
1527 delete r0;
1528 delete r1;
1529 delete r2;
1530 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001531
1532 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001533 static void CompareTestPartResult(const TestPartResult& expected,
1534 const TestPartResult& actual) {
1535 EXPECT_EQ(expected.type(), actual.type());
1536 EXPECT_STREQ(expected.file_name(), actual.file_name());
1537 EXPECT_EQ(expected.line_number(), actual.line_number());
1538 EXPECT_STREQ(expected.summary(), actual.summary());
1539 EXPECT_STREQ(expected.message(), actual.message());
1540 EXPECT_EQ(expected.passed(), actual.passed());
1541 EXPECT_EQ(expected.failed(), actual.failed());
1542 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1543 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001544 }
shiqian4b6829f2008-07-03 22:38:12 +00001545};
1546
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001547// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001548TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001549 ASSERT_EQ(0, r0->total_part_count());
1550 ASSERT_EQ(1, r1->total_part_count());
1551 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001552}
1553
zhanyong.wan9644db82009-06-24 23:02:50 +00001554// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001555TEST_F(TestResultTest, Passed) {
1556 ASSERT_TRUE(r0->Passed());
1557 ASSERT_TRUE(r1->Passed());
1558 ASSERT_FALSE(r2->Passed());
1559}
1560
zhanyong.wan9644db82009-06-24 23:02:50 +00001561// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001562TEST_F(TestResultTest, Failed) {
1563 ASSERT_FALSE(r0->Failed());
1564 ASSERT_FALSE(r1->Failed());
1565 ASSERT_TRUE(r2->Failed());
1566}
1567
zhanyong.wan9644db82009-06-24 23:02:50 +00001568// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001569
1570typedef TestResultTest TestResultDeathTest;
1571
1572TEST_F(TestResultDeathTest, GetTestPartResult) {
1573 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1574 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001575 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1576 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001577}
1578
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001579// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001580TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1581 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001582 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001583}
1584
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001585// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001586TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1587 TestResult test_result;
1588 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001589 TestResultAccessor::RecordProperty(&test_result, property);
1590 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001591 const TestProperty& actual_property = test_result.GetTestProperty(0);
1592 EXPECT_STREQ("key_1", actual_property.key());
1593 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001594}
1595
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001596// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001597TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1598 TestResult test_result;
1599 TestProperty property_1("key_1", "1");
1600 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001601 TestResultAccessor::RecordProperty(&test_result, property_1);
1602 TestResultAccessor::RecordProperty(&test_result, property_2);
1603 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001604 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1605 EXPECT_STREQ("key_1", actual_property_1.key());
1606 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001607
zhanyong.wan449f84d2009-07-01 22:55:05 +00001608 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1609 EXPECT_STREQ("key_2", actual_property_2.key());
1610 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001611}
1612
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001613// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001614TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1615 TestResult test_result;
1616 TestProperty property_1_1("key_1", "1");
1617 TestProperty property_2_1("key_2", "2");
1618 TestProperty property_1_2("key_1", "12");
1619 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001620 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1621 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1622 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1623 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001624
zhanyong.wan9644db82009-06-24 23:02:50 +00001625 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001626 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1627 EXPECT_STREQ("key_1", actual_property_1.key());
1628 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001629
zhanyong.wan449f84d2009-07-01 22:55:05 +00001630 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1631 EXPECT_STREQ("key_2", actual_property_2.key());
1632 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001633}
1634
1635// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001636TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001637 TestResult test_result;
1638 TestProperty property_1("key_1", "1");
1639 TestProperty property_2("key_2", "2");
1640 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001641 TestResultAccessor::RecordProperty(&test_result, property_1);
1642 TestResultAccessor::RecordProperty(&test_result, property_2);
1643 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001644
zhanyong.wan449f84d2009-07-01 22:55:05 +00001645 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1646 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1647 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001648
zhanyong.wan449f84d2009-07-01 22:55:05 +00001649 EXPECT_STREQ("key_1", fetched_property_1.key());
1650 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001651
zhanyong.wan449f84d2009-07-01 22:55:05 +00001652 EXPECT_STREQ("key_2", fetched_property_2.key());
1653 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001654
zhanyong.wan449f84d2009-07-01 22:55:05 +00001655 EXPECT_STREQ("key_3", fetched_property_3.key());
1656 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001657
zhanyong.wan93d13a82010-02-25 01:09:07 +00001658 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1659 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001660}
1661
shiqian4b6829f2008-07-03 22:38:12 +00001662// When a property using a reserved key is supplied to this function, it tests
1663// that a non-fatal failure is added, a fatal failure is not added, and that the
1664// property is not recorded.
1665void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1666 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001667 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001668 EXPECT_NONFATAL_FAILURE(
1669 TestResultAccessor::RecordProperty(&test_result, property),
1670 "Reserved key");
1671 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001672}
1673
1674// Attempting to recording a property with the Reserved literal "name"
1675// should add a non-fatal failure and the property should not be recorded.
1676TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1677 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1678}
1679
1680// Attempting to recording a property with the Reserved literal "status"
1681// should add a non-fatal failure and the property should not be recorded.
1682TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1683 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1684}
1685
1686// Attempting to recording a property with the Reserved literal "time"
1687// should add a non-fatal failure and the property should not be recorded.
1688TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1689 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1690}
1691
1692// Attempting to recording a property with the Reserved literal "classname"
1693// should add a non-fatal failure and the property should not be recorded.
1694TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1695 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1696}
1697
1698// Tests that GTestFlagSaver works on Windows and Mac.
1699
shiqian760af5c2008-08-06 21:43:15 +00001700class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001701 protected:
1702 // Saves the Google Test flags such that we can restore them later, and
1703 // then sets them to their default values. This will be called
1704 // before the first test in this test case is run.
1705 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001706 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001707
shiqianca6949f2009-01-10 01:16:33 +00001708 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001709 GTEST_FLAG(break_on_failure) = false;
1710 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001711 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001712 GTEST_FLAG(color) = "auto";
1713 GTEST_FLAG(filter) = "";
1714 GTEST_FLAG(list_tests) = false;
1715 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001716 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001717 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001718 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001719 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00001720 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001721 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001722 }
1723
1724 // Restores the Google Test flags that the tests have modified. This will
1725 // be called after the last test in this test case is run.
1726 static void TearDownTestCase() {
1727 delete saver_;
1728 saver_ = NULL;
1729 }
1730
1731 // Verifies that the Google Test flags have their default values, and then
1732 // modifies each of them.
1733 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001734 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001735 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1736 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1737 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001738 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001739 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1740 EXPECT_FALSE(GTEST_FLAG(list_tests));
1741 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001742 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001743 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001744 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001745 EXPECT_FALSE(GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00001746 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001747 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001748
shiqianca6949f2009-01-10 01:16:33 +00001749 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001750 GTEST_FLAG(break_on_failure) = true;
1751 GTEST_FLAG(catch_exceptions) = true;
1752 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001753 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001754 GTEST_FLAG(filter) = "abc";
1755 GTEST_FLAG(list_tests) = true;
1756 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001757 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001758 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001759 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001760 GTEST_FLAG(shuffle) = true;
vladlosevba015a92009-11-17 22:43:15 +00001761 GTEST_FLAG(stack_trace_depth) = 1;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001762 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001763 }
1764 private:
1765 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001766 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001767};
1768
shiqian760af5c2008-08-06 21:43:15 +00001769GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001770
1771// Google Test doesn't guarantee the order of tests. The following two
1772// tests are designed to work regardless of their order.
1773
1774// Modifies the Google Test flags in the test body.
1775TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1776 VerifyAndModifyFlags();
1777}
1778
1779// Verifies that the Google Test flags in the body of the previous test were
1780// restored to their original values.
1781TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1782 VerifyAndModifyFlags();
1783}
1784
1785// Sets an environment variable with the given name to the given
1786// value. If the value argument is "", unsets the environment
1787// variable. The caller must ensure that both arguments are not NULL.
1788static void SetEnv(const char* name, const char* value) {
zhanyong.wanfff03342009-09-24 21:15:59 +00001789#if GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001790 // Environment variables are not supported on Windows CE.
1791 return;
vladlosev673a0cb2010-02-03 02:27:02 +00001792#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
zhanyong.wan98efcc42009-04-28 00:28:09 +00001793 // C++Builder's putenv only stores a pointer to its parameter; we have to
1794 // ensure that the string remains valid as long as it might be needed.
1795 // We use an std::map to do so.
1796 static std::map<String, String*> added_env;
1797
1798 // Because putenv stores a pointer to the string buffer, we can't delete the
1799 // previous string (if present) until after it's replaced.
1800 String *prev_env = NULL;
1801 if (added_env.find(name) != added_env.end()) {
1802 prev_env = added_env[name];
1803 }
1804 added_env[name] = new String((Message() << name << "=" << value).GetString());
vladlosev673a0cb2010-02-03 02:27:02 +00001805
1806 // The standard signature of putenv accepts a 'char*' argument. Other
1807 // implementations, like C++Builder's, accept a 'const char*'.
1808 // We cast away the 'const' since that would work for both variants.
1809 putenv(const_cast<char*>(added_env[name]->c_str()));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001810 delete prev_env;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001811#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001812 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001813#else
1814 if (*value == '\0') {
1815 unsetenv(name);
1816 } else {
1817 setenv(name, value, 1);
1818 }
zhanyong.wanfff03342009-09-24 21:15:59 +00001819#endif // GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001820}
1821
zhanyong.wanfff03342009-09-24 21:15:59 +00001822#if !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001823// Environment variables are not supported on Windows CE.
1824
shiqian760af5c2008-08-06 21:43:15 +00001825using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001826
1827// Tests Int32FromGTestEnv().
1828
1829// Tests that Int32FromGTestEnv() returns the default value when the
1830// environment variable is not set.
1831TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001832 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001833 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1834}
1835
1836// Tests that Int32FromGTestEnv() returns the default value when the
1837// environment variable overflows as an Int32.
1838TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1839 printf("(expecting 2 warnings)\n");
1840
zhanyong.wan4cd62602009-02-23 23:21:55 +00001841 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001842 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1843
zhanyong.wan4cd62602009-02-23 23:21:55 +00001844 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001845 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1846}
1847
1848// Tests that Int32FromGTestEnv() returns the default value when the
1849// environment variable does not represent a valid decimal integer.
1850TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1851 printf("(expecting 2 warnings)\n");
1852
zhanyong.wan4cd62602009-02-23 23:21:55 +00001853 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001854 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1855
zhanyong.wan4cd62602009-02-23 23:21:55 +00001856 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001857 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1858}
1859
1860// Tests that Int32FromGTestEnv() parses and returns the value of the
1861// environment variable when it represents a valid decimal integer in
1862// the range of an Int32.
1863TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001864 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001865 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1866
zhanyong.wan4cd62602009-02-23 23:21:55 +00001867 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001868 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1869}
zhanyong.wanfff03342009-09-24 21:15:59 +00001870#endif // !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001871
1872// Tests ParseInt32Flag().
1873
1874// Tests that ParseInt32Flag() returns false and doesn't change the
1875// output value when the flag has wrong format
1876TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1877 Int32 value = 123;
1878 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1879 EXPECT_EQ(123, value);
1880
1881 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1882 EXPECT_EQ(123, value);
1883}
1884
1885// Tests that ParseInt32Flag() returns false and doesn't change the
1886// output value when the flag overflows as an Int32.
1887TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1888 printf("(expecting 2 warnings)\n");
1889
1890 Int32 value = 123;
1891 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1892 EXPECT_EQ(123, value);
1893
1894 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1895 EXPECT_EQ(123, value);
1896}
1897
1898// Tests that ParseInt32Flag() returns false and doesn't change the
1899// output value when the flag does not represent a valid decimal
1900// integer.
1901TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1902 printf("(expecting 2 warnings)\n");
1903
1904 Int32 value = 123;
1905 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1906 EXPECT_EQ(123, value);
1907
1908 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1909 EXPECT_EQ(123, value);
1910}
1911
1912// Tests that ParseInt32Flag() parses the value of the flag and
1913// returns true when the flag represents a valid decimal integer in
1914// the range of an Int32.
1915TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1916 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001917 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001918 EXPECT_EQ(456, value);
1919
zhanyong.wan98efcc42009-04-28 00:28:09 +00001920 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1921 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001922 EXPECT_EQ(-789, value);
1923}
1924
zhanyong.wan905074c2009-02-09 18:05:21 +00001925// Tests that Int32FromEnvOrDie() parses the value of the var or
1926// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001927// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00001928#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001929TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001930 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1931 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1932 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1933 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1934 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001935}
zhanyong.wanfff03342009-09-24 21:15:59 +00001936#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001937
1938// Tests that Int32FromEnvOrDie() aborts with an error message
1939// if the variable is not an Int32.
1940TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001941 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan535de532009-08-07 06:47:47 +00001942 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001943 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1944 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001945}
1946
1947// Tests that Int32FromEnvOrDie() aborts with an error message
1948// if the variable cannot be represnted by an Int32.
1949TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001950 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan535de532009-08-07 06:47:47 +00001951 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001952 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1953 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001954}
1955
zhanyong.wan905074c2009-02-09 18:05:21 +00001956// Tests that ShouldRunTestOnShard() selects all tests
1957// where there is 1 shard.
1958TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1959 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1960 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1961 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1962 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1963 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1964}
1965
1966class ShouldShardTest : public testing::Test {
1967 protected:
1968 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001969 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1970 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00001971 }
1972
1973 virtual void TearDown() {
1974 SetEnv(index_var_, "");
1975 SetEnv(total_var_, "");
1976 }
1977
1978 const char* index_var_;
1979 const char* total_var_;
1980};
1981
1982// Tests that sharding is disabled if neither of the environment variables
1983// are set.
1984TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1985 SetEnv(index_var_, "");
1986 SetEnv(total_var_, "");
1987
1988 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1989 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1990}
1991
1992// Tests that sharding is not enabled if total_shards == 1.
1993TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1994 SetEnv(index_var_, "0");
1995 SetEnv(total_var_, "1");
1996 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1997 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1998}
1999
2000// Tests that sharding is enabled if total_shards > 1 and
2001// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00002002// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00002003#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002004TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
2005 SetEnv(index_var_, "4");
2006 SetEnv(total_var_, "22");
2007 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2008 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2009
2010 SetEnv(index_var_, "8");
2011 SetEnv(total_var_, "9");
2012 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2013 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2014
2015 SetEnv(index_var_, "0");
2016 SetEnv(total_var_, "9");
2017 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2018 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2019}
zhanyong.wanfff03342009-09-24 21:15:59 +00002020#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002021
2022// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00002023
2024typedef ShouldShardTest ShouldShardDeathTest;
2025
2026TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00002027 SetEnv(index_var_, "4");
2028 SetEnv(total_var_, "4");
zhanyong.wan535de532009-08-07 06:47:47 +00002029 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002030
2031 SetEnv(index_var_, "4");
2032 SetEnv(total_var_, "-2");
zhanyong.wan535de532009-08-07 06:47:47 +00002033 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002034
2035 SetEnv(index_var_, "5");
2036 SetEnv(total_var_, "");
zhanyong.wan535de532009-08-07 06:47:47 +00002037 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002038
2039 SetEnv(index_var_, "");
2040 SetEnv(total_var_, "5");
zhanyong.wan535de532009-08-07 06:47:47 +00002041 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002042}
2043
zhanyong.wan905074c2009-02-09 18:05:21 +00002044// Tests that ShouldRunTestOnShard is a partition when 5
2045// shards are used.
2046TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
2047 // Choose an arbitrary number of tests and shards.
2048 const int num_tests = 17;
2049 const int num_shards = 5;
2050
2051 // Check partitioning: each test should be on exactly 1 shard.
2052 for (int test_id = 0; test_id < num_tests; test_id++) {
2053 int prev_selected_shard_index = -1;
2054 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2055 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
2056 if (prev_selected_shard_index < 0) {
2057 prev_selected_shard_index = shard_index;
2058 } else {
2059 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
2060 << shard_index << " are both selected to run test " << test_id;
2061 }
2062 }
2063 }
2064 }
2065
2066 // Check balance: This is not required by the sharding protocol, but is a
2067 // desirable property for performance.
2068 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2069 int num_tests_on_shard = 0;
2070 for (int test_id = 0; test_id < num_tests; test_id++) {
2071 num_tests_on_shard +=
2072 ShouldRunTestOnShard(num_shards, shard_index, test_id);
2073 }
2074 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
2075 }
2076}
2077
shiqian4b6829f2008-07-03 22:38:12 +00002078// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00002079// Test class, there are no separate tests for the following classes
2080// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00002081//
2082// TestCase, UnitTest, UnitTestResultPrinter.
2083//
2084// Similarly, there are no separate tests for the following macros:
2085//
2086// TEST, TEST_F, RUN_ALL_TESTS
2087
shiqianc3b4de32008-09-12 04:01:37 +00002088TEST(UnitTestTest, CanGetOriginalWorkingDir) {
2089 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
2090 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2091}
2092
shiqian4b6829f2008-07-03 22:38:12 +00002093// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2094// of various arities. They do not attempt to be exhaustive. Rather,
2095// view them as smoke tests that can be easily reviewed and verified.
2096// A more complete set of tests for predicate assertions can be found
2097// in gtest_pred_impl_unittest.cc.
2098
2099// First, some predicates and predicate-formatters needed by the tests.
2100
2101// Returns true iff the argument is an even number.
2102bool IsEven(int n) {
2103 return (n % 2) == 0;
2104}
2105
2106// A functor that returns true iff the argument is an even number.
2107struct IsEvenFunctor {
2108 bool operator()(int n) { return IsEven(n); }
2109};
2110
2111// A predicate-formatter function that asserts the argument is an even
2112// number.
shiqian760af5c2008-08-06 21:43:15 +00002113AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002114 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00002115 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002116 }
2117
shiqian760af5c2008-08-06 21:43:15 +00002118 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002119 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002120 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002121}
2122
vladlosevfbd53a52009-10-20 21:03:10 +00002123// A predicate function that returns AssertionResult for use in
2124// EXPECT/ASSERT_TRUE/FALSE.
2125AssertionResult ResultIsEven(int n) {
2126 if (IsEven(n))
2127 return AssertionSuccess() << n << " is even";
2128 else
2129 return AssertionFailure() << n << " is odd";
2130}
2131
2132// A predicate function that returns AssertionResult but gives no
2133// explanation why it succeeds. Needed for testing that
2134// EXPECT/ASSERT_FALSE handles such functions correctly.
2135AssertionResult ResultIsEvenNoExplanation(int n) {
2136 if (IsEven(n))
2137 return AssertionSuccess();
2138 else
2139 return AssertionFailure() << n << " is odd";
2140}
2141
shiqian4b6829f2008-07-03 22:38:12 +00002142// A predicate-formatter functor that asserts the argument is an even
2143// number.
2144struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00002145 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002146 return AssertIsEven(expr, n);
2147 }
2148};
2149
2150// Returns true iff the sum of the arguments is an even number.
2151bool SumIsEven2(int n1, int n2) {
2152 return IsEven(n1 + n2);
2153}
2154
2155// A functor that returns true iff the sum of the arguments is an even
2156// number.
2157struct SumIsEven3Functor {
2158 bool operator()(int n1, int n2, int n3) {
2159 return IsEven(n1 + n2 + n3);
2160 }
2161};
2162
2163// A predicate-formatter function that asserts the sum of the
2164// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00002165AssertionResult AssertSumIsEven4(
2166 const char* e1, const char* e2, const char* e3, const char* e4,
2167 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00002168 const int sum = n1 + n2 + n3 + n4;
2169 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002170 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002171 }
2172
shiqian760af5c2008-08-06 21:43:15 +00002173 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002174 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2175 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2176 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002177 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002178}
2179
2180// A predicate-formatter functor that asserts the sum of the arguments
2181// is an even number.
2182struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00002183 AssertionResult operator()(
2184 const char* e1, const char* e2, const char* e3, const char* e4,
2185 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00002186 const int sum = n1 + n2 + n3 + n4 + n5;
2187 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002188 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002189 }
2190
shiqian760af5c2008-08-06 21:43:15 +00002191 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002192 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2193 << " ("
2194 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2195 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002196 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002197 }
2198};
2199
2200
2201// Tests unary predicate assertions.
2202
2203// Tests unary predicate assertions that don't use a custom formatter.
2204TEST(Pred1Test, WithoutFormat) {
2205 // Success cases.
2206 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2207 ASSERT_PRED1(IsEven, 4);
2208
2209 // Failure cases.
2210 EXPECT_NONFATAL_FAILURE({ // NOLINT
2211 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2212 }, "This failure is expected.");
2213 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2214 "evaluates to false");
2215}
2216
2217// Tests unary predicate assertions that use a custom formatter.
2218TEST(Pred1Test, WithFormat) {
2219 // Success cases.
2220 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2221 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2222 << "This failure is UNEXPECTED!";
2223
2224 // Failure cases.
2225 const int n = 5;
2226 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2227 "n evaluates to 5, which is not even.");
2228 EXPECT_FATAL_FAILURE({ // NOLINT
2229 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2230 }, "This failure is expected.");
2231}
2232
2233// Tests that unary predicate assertions evaluates their arguments
2234// exactly once.
2235TEST(Pred1Test, SingleEvaluationOnFailure) {
2236 // A success case.
2237 static int n = 0;
2238 EXPECT_PRED1(IsEven, n++);
2239 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2240
2241 // A failure case.
2242 EXPECT_FATAL_FAILURE({ // NOLINT
2243 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2244 << "This failure is expected.";
2245 }, "This failure is expected.");
2246 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2247}
2248
2249
2250// Tests predicate assertions whose arity is >= 2.
2251
2252// Tests predicate assertions that don't use a custom formatter.
2253TEST(PredTest, WithoutFormat) {
2254 // Success cases.
2255 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2256 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2257
2258 // Failure cases.
2259 const int n1 = 1;
2260 const int n2 = 2;
2261 EXPECT_NONFATAL_FAILURE({ // NOLINT
2262 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2263 }, "This failure is expected.");
2264 EXPECT_FATAL_FAILURE({ // NOLINT
2265 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2266 }, "evaluates to false");
2267}
2268
2269// Tests predicate assertions that use a custom formatter.
2270TEST(PredTest, WithFormat) {
2271 // Success cases.
2272 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2273 "This failure is UNEXPECTED!";
2274 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2275
2276 // Failure cases.
2277 const int n1 = 1;
2278 const int n2 = 2;
2279 const int n3 = 4;
2280 const int n4 = 6;
2281 EXPECT_NONFATAL_FAILURE({ // NOLINT
2282 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2283 }, "evaluates to 13, which is not even.");
2284 EXPECT_FATAL_FAILURE({ // NOLINT
2285 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2286 << "This failure is expected.";
2287 }, "This failure is expected.");
2288}
2289
2290// Tests that predicate assertions evaluates their arguments
2291// exactly once.
2292TEST(PredTest, SingleEvaluationOnFailure) {
2293 // A success case.
2294 int n1 = 0;
2295 int n2 = 0;
2296 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2297 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2298 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2299
2300 // Another success case.
2301 n1 = n2 = 0;
2302 int n3 = 0;
2303 int n4 = 0;
2304 int n5 = 0;
2305 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2306 n1++, n2++, n3++, n4++, n5++)
2307 << "This failure is UNEXPECTED!";
2308 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2309 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2310 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2311 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2312 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2313
2314 // A failure case.
2315 n1 = n2 = n3 = 0;
2316 EXPECT_NONFATAL_FAILURE({ // NOLINT
2317 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2318 << "This failure is expected.";
2319 }, "This failure is expected.");
2320 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2321 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2322 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2323
2324 // Another failure case.
2325 n1 = n2 = n3 = n4 = 0;
2326 EXPECT_NONFATAL_FAILURE({ // NOLINT
2327 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2328 }, "evaluates to 1, which is not even.");
2329 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2330 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2331 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2332 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2333}
2334
2335
2336// Some helper functions for testing using overloaded/template
2337// functions with ASSERT_PREDn and EXPECT_PREDn.
2338
shiqian4b6829f2008-07-03 22:38:12 +00002339bool IsPositive(double x) {
2340 return x > 0;
2341}
2342
2343template <typename T>
2344bool IsNegative(T x) {
2345 return x < 0;
2346}
2347
2348template <typename T1, typename T2>
2349bool GreaterThan(T1 x1, T2 x2) {
2350 return x1 > x2;
2351}
2352
2353// Tests that overloaded functions can be used in *_PRED* as long as
2354// their types are explicitly specified.
2355TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002356 // C++Builder requires C-style casts rather than static_cast.
2357 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2358 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002359}
2360
2361// Tests that template functions can be used in *_PRED* as long as
2362// their types are explicitly specified.
2363TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2364 EXPECT_PRED1(IsNegative<int>, -5);
2365 // Makes sure that we can handle templates with more than one
2366 // parameter.
2367 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2368}
2369
2370
2371// Some helper functions for testing using overloaded/template
2372// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2373
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002374AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002375 return n > 0 ? AssertionSuccess() :
2376 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002377}
2378
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002379AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002380 return x > 0 ? AssertionSuccess() :
2381 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002382}
2383
2384template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002385AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002386 return x < 0 ? AssertionSuccess() :
2387 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002388}
2389
2390template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002391AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002392 const T1& x1, const T2& x2) {
2393 return x1 == x2 ? AssertionSuccess() :
2394 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002395}
2396
2397// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002398// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002399TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2400 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2401 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2402}
2403
2404// Tests that template functions can be used in *_PRED_FORMAT* without
2405// explicitly specifying their types.
2406TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2407 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2408 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2409}
2410
2411
2412// Tests string assertions.
2413
2414// Tests ASSERT_STREQ with non-NULL arguments.
2415TEST(StringAssertionTest, ASSERT_STREQ) {
2416 const char * const p1 = "good";
2417 ASSERT_STREQ(p1, p1);
2418
2419 // Let p2 have the same content as p1, but be at a different address.
2420 const char p2[] = "good";
2421 ASSERT_STREQ(p1, p2);
2422
2423 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2424 "Expected: \"bad\"");
2425}
2426
2427// Tests ASSERT_STREQ with NULL arguments.
2428TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2429 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2430 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2431 "non-null");
2432}
2433
2434// Tests ASSERT_STREQ with NULL arguments.
2435TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2436 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2437 "non-null");
2438}
2439
2440// Tests ASSERT_STRNE.
2441TEST(StringAssertionTest, ASSERT_STRNE) {
2442 ASSERT_STRNE("hi", "Hi");
2443 ASSERT_STRNE("Hi", NULL);
2444 ASSERT_STRNE(NULL, "Hi");
2445 ASSERT_STRNE("", NULL);
2446 ASSERT_STRNE(NULL, "");
2447 ASSERT_STRNE("", "Hi");
2448 ASSERT_STRNE("Hi", "");
2449 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2450 "\"Hi\" vs \"Hi\"");
2451}
2452
2453// Tests ASSERT_STRCASEEQ.
2454TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2455 ASSERT_STRCASEEQ("hi", "Hi");
2456 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2457
2458 ASSERT_STRCASEEQ("", "");
2459 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2460 "(ignoring case)");
2461}
2462
2463// Tests ASSERT_STRCASENE.
2464TEST(StringAssertionTest, ASSERT_STRCASENE) {
2465 ASSERT_STRCASENE("hi1", "Hi2");
2466 ASSERT_STRCASENE("Hi", NULL);
2467 ASSERT_STRCASENE(NULL, "Hi");
2468 ASSERT_STRCASENE("", NULL);
2469 ASSERT_STRCASENE(NULL, "");
2470 ASSERT_STRCASENE("", "Hi");
2471 ASSERT_STRCASENE("Hi", "");
2472 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2473 "(ignoring case)");
2474}
2475
2476// Tests *_STREQ on wide strings.
2477TEST(StringAssertionTest, STREQ_Wide) {
2478 // NULL strings.
2479 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2480
2481 // Empty strings.
2482 ASSERT_STREQ(L"", L"");
2483
2484 // Non-null vs NULL.
2485 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2486 "non-null");
2487
2488 // Equal strings.
2489 EXPECT_STREQ(L"Hi", L"Hi");
2490
2491 // Unequal strings.
2492 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2493 "Abc");
2494
2495 // Strings containing wide characters.
2496 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2497 "abc");
2498}
2499
2500// Tests *_STRNE on wide strings.
2501TEST(StringAssertionTest, STRNE_Wide) {
2502 // NULL strings.
2503 EXPECT_NONFATAL_FAILURE({ // NOLINT
2504 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2505 }, "");
2506
2507 // Empty strings.
2508 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2509 "L\"\"");
2510
2511 // Non-null vs NULL.
2512 ASSERT_STRNE(L"non-null", NULL);
2513
2514 // Equal strings.
2515 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2516 "L\"Hi\"");
2517
2518 // Unequal strings.
2519 EXPECT_STRNE(L"abc", L"Abc");
2520
2521 // Strings containing wide characters.
2522 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2523 "abc");
2524}
2525
2526// Tests for ::testing::IsSubstring().
2527
2528// Tests that IsSubstring() returns the correct result when the input
2529// argument type is const char*.
2530TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002531 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2532 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2533 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2534
2535 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2536 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2537}
2538
2539// Tests that IsSubstring() returns the correct result when the input
2540// argument type is const wchar_t*.
2541TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002542 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2543 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002544 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2545
2546 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2547 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2548}
2549
2550// Tests that IsSubstring() generates the correct message when the input
2551// argument type is const char*.
2552TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2553 EXPECT_STREQ("Value of: needle_expr\n"
2554 " Actual: \"needle\"\n"
2555 "Expected: a substring of haystack_expr\n"
2556 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002557 IsSubstring("needle_expr", "haystack_expr",
2558 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002559}
2560
shiqian4b6829f2008-07-03 22:38:12 +00002561// Tests that IsSubstring returns the correct result when the input
2562// argument type is ::std::string.
2563TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002564 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2565 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002566}
2567
shiqian4b6829f2008-07-03 22:38:12 +00002568#if GTEST_HAS_STD_WSTRING
2569// Tests that IsSubstring returns the correct result when the input
2570// argument type is ::std::wstring.
2571TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002572 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2573 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2574}
2575
2576// Tests that IsSubstring() generates the correct message when the input
2577// argument type is ::std::wstring.
2578TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2579 EXPECT_STREQ("Value of: needle_expr\n"
2580 " Actual: L\"needle\"\n"
2581 "Expected: a substring of haystack_expr\n"
2582 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002583 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002584 "needle_expr", "haystack_expr",
2585 ::std::wstring(L"needle"), L"haystack").failure_message());
2586}
2587
2588#endif // GTEST_HAS_STD_WSTRING
2589
2590// Tests for ::testing::IsNotSubstring().
2591
2592// Tests that IsNotSubstring() returns the correct result when the input
2593// argument type is const char*.
2594TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002595 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2596 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2597}
2598
2599// Tests that IsNotSubstring() returns the correct result when the input
2600// argument type is const wchar_t*.
2601TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002602 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2603 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2604}
2605
2606// Tests that IsNotSubstring() generates the correct message when the input
2607// argument type is const wchar_t*.
2608TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2609 EXPECT_STREQ("Value of: needle_expr\n"
2610 " Actual: L\"needle\"\n"
2611 "Expected: not a substring of haystack_expr\n"
2612 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002613 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002614 "needle_expr", "haystack_expr",
2615 L"needle", L"two needles").failure_message());
2616}
2617
shiqian4b6829f2008-07-03 22:38:12 +00002618// Tests that IsNotSubstring returns the correct result when the input
2619// argument type is ::std::string.
2620TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002621 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2622 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2623}
2624
2625// Tests that IsNotSubstring() generates the correct message when the input
2626// argument type is ::std::string.
2627TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2628 EXPECT_STREQ("Value of: needle_expr\n"
2629 " Actual: \"needle\"\n"
2630 "Expected: not a substring of haystack_expr\n"
2631 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002632 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002633 "needle_expr", "haystack_expr",
2634 ::std::string("needle"), "two needles").failure_message());
2635}
2636
shiqian4b6829f2008-07-03 22:38:12 +00002637#if GTEST_HAS_STD_WSTRING
2638
2639// Tests that IsNotSubstring returns the correct result when the input
2640// argument type is ::std::wstring.
2641TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002642 EXPECT_FALSE(
2643 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2644 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2645}
2646
2647#endif // GTEST_HAS_STD_WSTRING
2648
2649// Tests floating-point assertions.
2650
2651template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002652class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002653 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002654
2655 // Pre-calculated numbers to be used by the tests.
2656 struct TestValues {
2657 RawType close_to_positive_zero;
2658 RawType close_to_negative_zero;
2659 RawType further_from_negative_zero;
2660
2661 RawType close_to_one;
2662 RawType further_from_one;
2663
2664 RawType infinity;
2665 RawType close_to_infinity;
2666 RawType further_from_infinity;
2667
2668 RawType nan1;
2669 RawType nan2;
2670 };
2671
shiqian4b6829f2008-07-03 22:38:12 +00002672 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2673 typedef typename Floating::Bits Bits;
2674
2675 virtual void SetUp() {
2676 const size_t max_ulps = Floating::kMaxUlps;
2677
2678 // The bits that represent 0.0.
2679 const Bits zero_bits = Floating(0).bits();
2680
2681 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002682 values_.close_to_positive_zero = Floating::ReinterpretBits(
2683 zero_bits + max_ulps/2);
2684 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002685 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002686 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002687 zero_bits + max_ulps + 1 - max_ulps/2);
2688
2689 // The bits that represent 1.0.
2690 const Bits one_bits = Floating(1).bits();
2691
2692 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002693 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2694 values_.further_from_one = Floating::ReinterpretBits(
2695 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002696
2697 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002698 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002699
2700 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002701 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002702
2703 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002704 values_.close_to_infinity = Floating::ReinterpretBits(
2705 infinity_bits - max_ulps);
2706 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002707 infinity_bits - max_ulps - 1);
2708
zhanyong.wan98efcc42009-04-28 00:28:09 +00002709 // Makes some NAN's. Sets the most significant bit of the fraction so that
2710 // our NaN's are quiet; trying to process a signaling NaN would raise an
2711 // exception if our environment enables floating point exceptions.
2712 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2713 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2714 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2715 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002716 }
2717
2718 void TestSize() {
2719 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2720 }
2721
zhanyong.wan98efcc42009-04-28 00:28:09 +00002722 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002723};
2724
2725template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002726typename FloatingPointTest<RawType>::TestValues
2727 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002728
2729// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2730typedef FloatingPointTest<float> FloatTest;
2731
2732// Tests that the size of Float::Bits matches the size of float.
2733TEST_F(FloatTest, Size) {
2734 TestSize();
2735}
2736
2737// Tests comparing with +0 and -0.
2738TEST_F(FloatTest, Zeros) {
2739 EXPECT_FLOAT_EQ(0.0, -0.0);
2740 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2741 "1.0");
2742 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2743 "1.5");
2744}
2745
2746// Tests comparing numbers close to 0.
2747//
2748// This ensures that *_FLOAT_EQ handles the sign correctly and no
2749// overflow occurs when comparing numbers whose absolute value is very
2750// small.
2751TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002752 // In C++Builder, names within local classes (such as used by
2753 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2754 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002755 // We use the assignment syntax since some compilers, like Sun Studio,
2756 // don't allow initializing references using construction syntax
2757 // (parentheses).
2758 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002759
2760 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2761 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2762 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002763
2764 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002765 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2766 v.further_from_negative_zero);
2767 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002768}
2769
2770// Tests comparing numbers close to each other.
2771TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002772 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2773 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2774 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002775}
2776
2777// Tests comparing numbers far apart.
2778TEST_F(FloatTest, LargeDiff) {
2779 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2780 "3.0");
2781}
2782
2783// Tests comparing with infinity.
2784//
2785// This ensures that no overflow occurs when comparing numbers whose
2786// absolute value is very large.
2787TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002788 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2789 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002790#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002791 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002792 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2793 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002794
zhanyong.wan98efcc42009-04-28 00:28:09 +00002795 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002796 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002797 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2798 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002799#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002800}
2801
2802// Tests that comparing with NAN always returns false.
2803TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002804#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002805// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002806
zhanyong.wan98efcc42009-04-28 00:28:09 +00002807 // In C++Builder, names within local classes (such as used by
2808 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2809 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002810 // We use the assignment syntax since some compilers, like Sun Studio,
2811 // don't allow initializing references using construction syntax
2812 // (parentheses).
2813 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002814
2815 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2816 "v.nan1");
2817 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2818 "v.nan2");
2819 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2820 "v.nan1");
2821
2822 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2823 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002824#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002825}
2826
2827// Tests that *_FLOAT_EQ are reflexive.
2828TEST_F(FloatTest, Reflexive) {
2829 EXPECT_FLOAT_EQ(0.0, 0.0);
2830 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002831 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002832}
2833
2834// Tests that *_FLOAT_EQ are commutative.
2835TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002836 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2837 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002838
zhanyong.wan98efcc42009-04-28 00:28:09 +00002839 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2840 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002841 "1.0");
2842}
2843
2844// Tests EXPECT_NEAR.
2845TEST_F(FloatTest, EXPECT_NEAR) {
2846 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2847 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002848 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2849 "The difference between 1.0f and 1.5f is 0.5, "
2850 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002851 // To work around a bug in gcc 2.95.0, there is intentionally no
2852 // space after the first comma in the previous line.
2853}
2854
2855// Tests ASSERT_NEAR.
2856TEST_F(FloatTest, ASSERT_NEAR) {
2857 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2858 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002859 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2860 "The difference between 1.0f and 1.5f is 0.5, "
2861 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002862 // To work around a bug in gcc 2.95.0, there is intentionally no
2863 // space after the first comma in the previous line.
2864}
2865
2866// Tests the cases where FloatLE() should succeed.
2867TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002868 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2869 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002870
2871 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002872 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002873}
2874
2875// Tests the cases where FloatLE() should fail.
2876TEST_F(FloatTest, FloatLEFails) {
2877 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002878 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002879 "(2.0f) <= (1.0f)");
2880
2881 // or by a small yet non-negligible margin,
2882 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002883 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2884 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002885
zhanyong.wan98efcc42009-04-28 00:28:09 +00002886#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002887 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002888 // C++Builder gives bad results for ordered comparisons involving NaNs
2889 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002890 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002891 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2892 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002893 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002894 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2895 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002896 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002897 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2898 }, "(values_.nan1) <= (values_.nan1)");
2899#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002900}
2901
2902// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2903typedef FloatingPointTest<double> DoubleTest;
2904
2905// Tests that the size of Double::Bits matches the size of double.
2906TEST_F(DoubleTest, Size) {
2907 TestSize();
2908}
2909
2910// Tests comparing with +0 and -0.
2911TEST_F(DoubleTest, Zeros) {
2912 EXPECT_DOUBLE_EQ(0.0, -0.0);
2913 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2914 "1.0");
2915 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2916 "1.0");
2917}
2918
2919// Tests comparing numbers close to 0.
2920//
2921// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2922// overflow occurs when comparing numbers whose absolute value is very
2923// small.
2924TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002925 // In C++Builder, names within local classes (such as used by
2926 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2927 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002928 // We use the assignment syntax since some compilers, like Sun Studio,
2929 // don't allow initializing references using construction syntax
2930 // (parentheses).
2931 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002932
2933 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2934 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2935 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002936
2937 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002938 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2939 v.further_from_negative_zero);
2940 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002941}
2942
2943// Tests comparing numbers close to each other.
2944TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002945 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2946 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2947 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002948}
2949
2950// Tests comparing numbers far apart.
2951TEST_F(DoubleTest, LargeDiff) {
2952 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2953 "3.0");
2954}
2955
2956// Tests comparing with infinity.
2957//
2958// This ensures that no overflow occurs when comparing numbers whose
2959// absolute value is very large.
2960TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002961 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2962 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002963#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002964 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002965 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2966 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002967
2968 // This is interesting as the representations of infinity_ and nan1_
2969 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002970 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2971 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002972#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002973}
2974
2975// Tests that comparing with NAN always returns false.
2976TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002977#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00002978 // In C++Builder, names within local classes (such as used by
2979 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2980 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002981 // We use the assignment syntax since some compilers, like Sun Studio,
2982 // don't allow initializing references using construction syntax
2983 // (parentheses).
2984 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002985
shiqiane44602e2008-10-11 07:20:02 +00002986 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002987 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2988 "v.nan1");
2989 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2990 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2991 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2992 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002993#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002994}
2995
2996// Tests that *_DOUBLE_EQ are reflexive.
2997TEST_F(DoubleTest, Reflexive) {
2998 EXPECT_DOUBLE_EQ(0.0, 0.0);
2999 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003000#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003001 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003002 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003003#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003004}
3005
3006// Tests that *_DOUBLE_EQ are commutative.
3007TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003008 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3009 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00003010
zhanyong.wan98efcc42009-04-28 00:28:09 +00003011 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3012 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3013 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00003014}
3015
3016// Tests EXPECT_NEAR.
3017TEST_F(DoubleTest, EXPECT_NEAR) {
3018 EXPECT_NEAR(-1.0, -1.1, 0.2);
3019 EXPECT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003020 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3021 "The difference between 1.0 and 1.5 is 0.5, "
3022 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003023 // To work around a bug in gcc 2.95.0, there is intentionally no
3024 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003025}
3026
3027// Tests ASSERT_NEAR.
3028TEST_F(DoubleTest, ASSERT_NEAR) {
3029 ASSERT_NEAR(-1.0, -1.1, 0.2);
3030 ASSERT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003031 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3032 "The difference between 1.0 and 1.5 is 0.5, "
3033 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003034 // To work around a bug in gcc 2.95.0, there is intentionally no
3035 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003036}
3037
3038// Tests the cases where DoubleLE() should succeed.
3039TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00003040 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3041 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00003042
3043 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003044 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00003045}
3046
3047// Tests the cases where DoubleLE() should fail.
3048TEST_F(DoubleTest, DoubleLEFails) {
3049 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003050 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003051 "(2.0) <= (1.0)");
3052
3053 // or by a small yet non-negligible margin,
3054 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003055 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3056 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00003057
zhanyong.wan98efcc42009-04-28 00:28:09 +00003058#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003059 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003060 // C++Builder gives bad results for ordered comparisons involving NaNs
3061 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003062 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003063 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3064 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003065 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003066 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3067 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003068 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003069 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3070 }, "(values_.nan1) <= (values_.nan1)");
3071#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003072}
3073
3074
3075// Verifies that a test or test case whose name starts with DISABLED_ is
3076// not run.
3077
3078// A test whose name starts with DISABLED_.
3079// Should not run.
3080TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3081 FAIL() << "Unexpected failure: Disabled test should not be run.";
3082}
3083
3084// A test whose name does not start with DISABLED_.
3085// Should run.
3086TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3087 EXPECT_EQ(1, 1);
3088}
3089
3090// A test case whose name starts with DISABLED_.
3091// Should not run.
3092TEST(DISABLED_TestCase, TestShouldNotRun) {
3093 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3094}
3095
3096// A test case and test whose names start with DISABLED_.
3097// Should not run.
3098TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3099 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3100}
3101
3102// Check that when all tests in a test case are disabled, SetupTestCase() and
3103// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00003104class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00003105 protected:
3106 static void SetUpTestCase() {
3107 FAIL() << "Unexpected failure: All tests disabled in test case. "
3108 "SetupTestCase() should not be called.";
3109 }
3110
3111 static void TearDownTestCase() {
3112 FAIL() << "Unexpected failure: All tests disabled in test case. "
3113 "TearDownTestCase() should not be called.";
3114 }
3115};
3116
3117TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3118 FAIL() << "Unexpected failure: Disabled test should not be run.";
3119}
3120
3121TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3122 FAIL() << "Unexpected failure: Disabled test should not be run.";
3123}
3124
shiqiane8ff1482008-09-08 17:55:52 +00003125// Tests that disabled typed tests aren't run.
3126
zhanyong.wan4cd62602009-02-23 23:21:55 +00003127#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00003128
3129template <typename T>
3130class TypedTest : public Test {
3131};
3132
3133typedef testing::Types<int, double> NumericTypes;
3134TYPED_TEST_CASE(TypedTest, NumericTypes);
3135
3136TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3137 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3138}
3139
3140template <typename T>
3141class DISABLED_TypedTest : public Test {
3142};
3143
3144TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3145
3146TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3147 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3148}
3149
3150#endif // GTEST_HAS_TYPED_TEST
3151
3152// Tests that disabled type-parameterized tests aren't run.
3153
zhanyong.wan4cd62602009-02-23 23:21:55 +00003154#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00003155
3156template <typename T>
3157class TypedTestP : public Test {
3158};
3159
3160TYPED_TEST_CASE_P(TypedTestP);
3161
3162TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3163 FAIL() << "Unexpected failure: "
3164 << "Disabled type-parameterized test should not run.";
3165}
3166
3167REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3168
3169INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3170
3171template <typename T>
3172class DISABLED_TypedTestP : public Test {
3173};
3174
3175TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3176
3177TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3178 FAIL() << "Unexpected failure: "
3179 << "Disabled type-parameterized test should not run.";
3180}
3181
3182REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3183
3184INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3185
3186#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00003187
3188// Tests that assertion macros evaluate their arguments exactly once.
3189
shiqian760af5c2008-08-06 21:43:15 +00003190class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00003191 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003192 // This helper function is needed by the FailedASSERT_STREQ test
3193 // below. It's public to work around C++Builder's bug with scoping local
3194 // classes.
3195 static void CompareAndIncrementCharPtrs() {
3196 ASSERT_STREQ(p1_++, p2_++);
3197 }
3198
3199 // This helper function is needed by the FailedASSERT_NE test below. It's
3200 // public to work around C++Builder's bug with scoping local classes.
3201 static void CompareAndIncrementInts() {
3202 ASSERT_NE(a_++, b_++);
3203 }
3204
shiqian4b6829f2008-07-03 22:38:12 +00003205 protected:
3206 SingleEvaluationTest() {
3207 p1_ = s1_;
3208 p2_ = s2_;
3209 a_ = 0;
3210 b_ = 0;
3211 }
3212
shiqian4b6829f2008-07-03 22:38:12 +00003213 static const char* const s1_;
3214 static const char* const s2_;
3215 static const char* p1_;
3216 static const char* p2_;
3217
3218 static int a_;
3219 static int b_;
3220};
3221
3222const char* const SingleEvaluationTest::s1_ = "01234";
3223const char* const SingleEvaluationTest::s2_ = "abcde";
3224const char* SingleEvaluationTest::p1_;
3225const char* SingleEvaluationTest::p2_;
3226int SingleEvaluationTest::a_;
3227int SingleEvaluationTest::b_;
3228
3229// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3230// exactly once.
3231TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003232 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003233 "p2_++");
3234 EXPECT_EQ(s1_ + 1, p1_);
3235 EXPECT_EQ(s2_ + 1, p2_);
3236}
3237
3238// Tests that string assertion arguments are evaluated exactly once.
3239TEST_F(SingleEvaluationTest, ASSERT_STR) {
3240 // successful EXPECT_STRNE
3241 EXPECT_STRNE(p1_++, p2_++);
3242 EXPECT_EQ(s1_ + 1, p1_);
3243 EXPECT_EQ(s2_ + 1, p2_);
3244
3245 // failed EXPECT_STRCASEEQ
3246 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3247 "ignoring case");
3248 EXPECT_EQ(s1_ + 2, p1_);
3249 EXPECT_EQ(s2_ + 2, p2_);
3250}
3251
3252// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3253// once.
3254TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003255 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3256 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003257 EXPECT_EQ(1, a_);
3258 EXPECT_EQ(1, b_);
3259}
3260
3261// Tests that assertion arguments are evaluated exactly once.
3262TEST_F(SingleEvaluationTest, OtherCases) {
3263 // successful EXPECT_TRUE
3264 EXPECT_TRUE(0 == a_++); // NOLINT
3265 EXPECT_EQ(1, a_);
3266
3267 // failed EXPECT_TRUE
3268 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3269 EXPECT_EQ(2, a_);
3270
3271 // successful EXPECT_GT
3272 EXPECT_GT(a_++, b_++);
3273 EXPECT_EQ(3, a_);
3274 EXPECT_EQ(1, b_);
3275
3276 // failed EXPECT_LT
3277 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3278 EXPECT_EQ(4, a_);
3279 EXPECT_EQ(2, b_);
3280
3281 // successful ASSERT_TRUE
3282 ASSERT_TRUE(0 < a_++); // NOLINT
3283 EXPECT_EQ(5, a_);
3284
3285 // successful ASSERT_GT
3286 ASSERT_GT(a_++, b_++);
3287 EXPECT_EQ(6, a_);
3288 EXPECT_EQ(3, b_);
3289}
3290
shiqian9204c8e2008-09-12 20:57:22 +00003291#if GTEST_HAS_EXCEPTIONS
3292
3293void ThrowAnInteger() {
3294 throw 1;
3295}
3296
3297// Tests that assertion arguments are evaluated exactly once.
3298TEST_F(SingleEvaluationTest, ExceptionTests) {
3299 // successful EXPECT_THROW
3300 EXPECT_THROW({ // NOLINT
3301 a_++;
3302 ThrowAnInteger();
3303 }, int);
3304 EXPECT_EQ(1, a_);
3305
3306 // failed EXPECT_THROW, throws different
3307 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3308 a_++;
3309 ThrowAnInteger();
3310 }, bool), "throws a different type");
3311 EXPECT_EQ(2, a_);
3312
3313 // failed EXPECT_THROW, throws nothing
3314 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3315 EXPECT_EQ(3, a_);
3316
3317 // successful EXPECT_NO_THROW
3318 EXPECT_NO_THROW(a_++);
3319 EXPECT_EQ(4, a_);
3320
3321 // failed EXPECT_NO_THROW
3322 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3323 a_++;
3324 ThrowAnInteger();
3325 }), "it throws");
3326 EXPECT_EQ(5, a_);
3327
3328 // successful EXPECT_ANY_THROW
3329 EXPECT_ANY_THROW({ // NOLINT
3330 a_++;
3331 ThrowAnInteger();
3332 });
3333 EXPECT_EQ(6, a_);
3334
3335 // failed EXPECT_ANY_THROW
3336 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3337 EXPECT_EQ(7, a_);
3338}
3339
3340#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003341
shiqiane44602e2008-10-11 07:20:02 +00003342// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3343class NoFatalFailureTest : public Test {
3344 protected:
3345 void Succeeds() {}
3346 void FailsNonFatal() {
3347 ADD_FAILURE() << "some non-fatal failure";
3348 }
3349 void Fails() {
3350 FAIL() << "some fatal failure";
3351 }
3352
3353 void DoAssertNoFatalFailureOnFails() {
3354 ASSERT_NO_FATAL_FAILURE(Fails());
3355 ADD_FAILURE() << "shold not reach here.";
3356 }
3357
3358 void DoExpectNoFatalFailureOnFails() {
3359 EXPECT_NO_FATAL_FAILURE(Fails());
3360 ADD_FAILURE() << "other failure";
3361 }
3362};
3363
3364TEST_F(NoFatalFailureTest, NoFailure) {
3365 EXPECT_NO_FATAL_FAILURE(Succeeds());
3366 ASSERT_NO_FATAL_FAILURE(Succeeds());
3367}
3368
3369TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3370 EXPECT_NONFATAL_FAILURE(
3371 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3372 "some non-fatal failure");
3373 EXPECT_NONFATAL_FAILURE(
3374 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3375 "some non-fatal failure");
3376}
3377
3378TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3379 TestPartResultArray gtest_failures;
3380 {
3381 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3382 DoAssertNoFatalFailureOnFails();
3383 }
3384 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003385 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003386 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003387 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003388 gtest_failures.GetTestPartResult(1).type());
3389 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3390 gtest_failures.GetTestPartResult(0).message());
3391 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3392 gtest_failures.GetTestPartResult(1).message());
3393}
3394
3395TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3396 TestPartResultArray gtest_failures;
3397 {
3398 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3399 DoExpectNoFatalFailureOnFails();
3400 }
3401 ASSERT_EQ(3, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003402 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003403 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003404 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003405 gtest_failures.GetTestPartResult(1).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003406 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003407 gtest_failures.GetTestPartResult(2).type());
3408 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3409 gtest_failures.GetTestPartResult(0).message());
3410 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3411 gtest_failures.GetTestPartResult(1).message());
3412 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3413 gtest_failures.GetTestPartResult(2).message());
3414}
3415
3416TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3417 TestPartResultArray gtest_failures;
3418 {
3419 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3420 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3421 }
3422 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003423 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003424 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003425 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003426 gtest_failures.GetTestPartResult(1).type());
3427 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3428 gtest_failures.GetTestPartResult(0).message());
3429 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3430 gtest_failures.GetTestPartResult(1).message());
3431}
3432
shiqian4b6829f2008-07-03 22:38:12 +00003433// Tests non-string assertions.
3434
3435// Tests EqFailure(), used for implementing *EQ* assertions.
3436TEST(AssertionTest, EqFailure) {
3437 const String foo_val("5"), bar_val("6");
3438 const String msg1(
3439 EqFailure("foo", "bar", foo_val, bar_val, false)
3440 .failure_message());
3441 EXPECT_STREQ(
3442 "Value of: bar\n"
3443 " Actual: 6\n"
3444 "Expected: foo\n"
3445 "Which is: 5",
3446 msg1.c_str());
3447
3448 const String msg2(
3449 EqFailure("foo", "6", foo_val, bar_val, false)
3450 .failure_message());
3451 EXPECT_STREQ(
3452 "Value of: 6\n"
3453 "Expected: foo\n"
3454 "Which is: 5",
3455 msg2.c_str());
3456
3457 const String msg3(
3458 EqFailure("5", "bar", foo_val, bar_val, false)
3459 .failure_message());
3460 EXPECT_STREQ(
3461 "Value of: bar\n"
3462 " Actual: 6\n"
3463 "Expected: 5",
3464 msg3.c_str());
3465
3466 const String msg4(
3467 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3468 EXPECT_STREQ(
3469 "Value of: 6\n"
3470 "Expected: 5",
3471 msg4.c_str());
3472
3473 const String msg5(
3474 EqFailure("foo", "bar",
3475 String("\"x\""), String("\"y\""),
3476 true).failure_message());
3477 EXPECT_STREQ(
3478 "Value of: bar\n"
3479 " Actual: \"y\"\n"
3480 "Expected: foo (ignoring case)\n"
3481 "Which is: \"x\"",
3482 msg5.c_str());
3483}
3484
3485// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3486TEST(AssertionTest, AppendUserMessage) {
3487 const String foo("foo");
3488
shiqian760af5c2008-08-06 21:43:15 +00003489 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003490 EXPECT_STREQ("foo",
3491 AppendUserMessage(foo, msg).c_str());
3492
3493 msg << "bar";
3494 EXPECT_STREQ("foo\nbar",
3495 AppendUserMessage(foo, msg).c_str());
3496}
3497
zhanyong.wan98efcc42009-04-28 00:28:09 +00003498#ifdef __BORLANDC__
3499// Silences warnings: "Condition is always true", "Unreachable code"
3500#pragma option push -w-ccc -w-rch
3501#endif
3502
shiqian4b6829f2008-07-03 22:38:12 +00003503// Tests ASSERT_TRUE.
3504TEST(AssertionTest, ASSERT_TRUE) {
3505 ASSERT_TRUE(2 > 1); // NOLINT
3506 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3507 "2 < 1");
3508}
3509
vladlosevfbd53a52009-10-20 21:03:10 +00003510// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3511TEST(AssertionTest, AssertTrueWithAssertionResult) {
3512 ASSERT_TRUE(ResultIsEven(2));
vladlosevd6b49412010-04-07 05:32:34 +00003513#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
3514 // ICE's in C++Builder 2007.
vladlosevfbd53a52009-10-20 21:03:10 +00003515 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3516 "Value of: ResultIsEven(3)\n"
3517 " Actual: false (3 is odd)\n"
3518 "Expected: true");
vladlosevd6b49412010-04-07 05:32:34 +00003519#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003520 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3521 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3522 "Value of: ResultIsEvenNoExplanation(3)\n"
3523 " Actual: false (3 is odd)\n"
3524 "Expected: true");
3525}
3526
shiqian4b6829f2008-07-03 22:38:12 +00003527// Tests ASSERT_FALSE.
3528TEST(AssertionTest, ASSERT_FALSE) {
3529 ASSERT_FALSE(2 < 1); // NOLINT
3530 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3531 "Value of: 2 > 1\n"
3532 " Actual: true\n"
3533 "Expected: false");
3534}
3535
vladlosevfbd53a52009-10-20 21:03:10 +00003536// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3537TEST(AssertionTest, AssertFalseWithAssertionResult) {
3538 ASSERT_FALSE(ResultIsEven(3));
vladlosevd6b49412010-04-07 05:32:34 +00003539#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
3540 // ICE's in C++Builder 2007.
vladlosevfbd53a52009-10-20 21:03:10 +00003541 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3542 "Value of: ResultIsEven(2)\n"
3543 " Actual: true (2 is even)\n"
3544 "Expected: false");
vladlosevd6b49412010-04-07 05:32:34 +00003545#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003546 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3547 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3548 "Value of: ResultIsEvenNoExplanation(2)\n"
3549 " Actual: true\n"
3550 "Expected: false");
3551}
3552
zhanyong.wan98efcc42009-04-28 00:28:09 +00003553#ifdef __BORLANDC__
3554// Restores warnings after previous "#pragma option push" supressed them
3555#pragma option pop
3556#endif
3557
shiqian4b6829f2008-07-03 22:38:12 +00003558// Tests using ASSERT_EQ on double values. The purpose is to make
3559// sure that the specialization we did for integer and anonymous enums
3560// isn't used for double arguments.
3561TEST(ExpectTest, ASSERT_EQ_Double) {
3562 // A success.
3563 ASSERT_EQ(5.6, 5.6);
3564
3565 // A failure.
3566 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3567 "5.1");
3568}
3569
3570// Tests ASSERT_EQ.
3571TEST(AssertionTest, ASSERT_EQ) {
3572 ASSERT_EQ(5, 2 + 3);
3573 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3574 "Value of: 2*3\n"
3575 " Actual: 6\n"
3576 "Expected: 5");
3577}
3578
3579// Tests ASSERT_EQ(NULL, pointer).
vladlosev5147b452010-03-17 18:22:59 +00003580#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003581TEST(AssertionTest, ASSERT_EQ_NULL) {
3582 // A success.
3583 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003584 // Some older GCC versions may issue a spurious waring in this or the next
3585 // assertion statement. This warning should not be suppressed with
3586 // static_cast since the test verifies the ability to use bare NULL as the
3587 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003588 ASSERT_EQ(NULL, p);
3589
3590 // A failure.
3591 static int n = 0;
3592 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3593 "Value of: &n\n");
3594}
vladlosev5147b452010-03-17 18:22:59 +00003595#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003596
3597// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3598// treated as a null pointer by the compiler, we need to make sure
3599// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3600// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3601TEST(ExpectTest, ASSERT_EQ_0) {
3602 int n = 0;
3603
3604 // A success.
3605 ASSERT_EQ(0, n);
3606
3607 // A failure.
3608 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3609 "Expected: 0");
3610}
3611
3612// Tests ASSERT_NE.
3613TEST(AssertionTest, ASSERT_NE) {
3614 ASSERT_NE(6, 7);
3615 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3616 "Expected: ('a') != ('a'), "
3617 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3618}
3619
3620// Tests ASSERT_LE.
3621TEST(AssertionTest, ASSERT_LE) {
3622 ASSERT_LE(2, 3);
3623 ASSERT_LE(2, 2);
3624 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3625 "Expected: (2) <= (0), actual: 2 vs 0");
3626}
3627
3628// Tests ASSERT_LT.
3629TEST(AssertionTest, ASSERT_LT) {
3630 ASSERT_LT(2, 3);
3631 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3632 "Expected: (2) < (2), actual: 2 vs 2");
3633}
3634
3635// Tests ASSERT_GE.
3636TEST(AssertionTest, ASSERT_GE) {
3637 ASSERT_GE(2, 1);
3638 ASSERT_GE(2, 2);
3639 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3640 "Expected: (2) >= (3), actual: 2 vs 3");
3641}
3642
3643// Tests ASSERT_GT.
3644TEST(AssertionTest, ASSERT_GT) {
3645 ASSERT_GT(2, 1);
3646 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3647 "Expected: (2) > (2), actual: 2 vs 2");
3648}
3649
shiqian9204c8e2008-09-12 20:57:22 +00003650#if GTEST_HAS_EXCEPTIONS
3651
zhanyong.wanac60cef2009-02-08 04:53:35 +00003652void ThrowNothing() {}
3653
shiqian9204c8e2008-09-12 20:57:22 +00003654// Tests ASSERT_THROW.
3655TEST(AssertionTest, ASSERT_THROW) {
3656 ASSERT_THROW(ThrowAnInteger(), int);
vladlosevd6b49412010-04-07 05:32:34 +00003657
3658#ifndef __BORLANDC__
3659 // ICE's in C++Builder 2007 and 2009.
zhanyong.wanac60cef2009-02-08 04:53:35 +00003660 EXPECT_FATAL_FAILURE(
3661 ASSERT_THROW(ThrowAnInteger(), bool),
3662 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3663 " Actual: it throws a different type.");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003664#endif
vladlosevd6b49412010-04-07 05:32:34 +00003665
zhanyong.wanac60cef2009-02-08 04:53:35 +00003666 EXPECT_FATAL_FAILURE(
3667 ASSERT_THROW(ThrowNothing(), bool),
3668 "Expected: ThrowNothing() throws an exception of type bool.\n"
3669 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003670}
3671
3672// Tests ASSERT_NO_THROW.
3673TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003674 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003675 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003676 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003677 "\n Actual: it throws.");
3678}
3679
3680// Tests ASSERT_ANY_THROW.
3681TEST(AssertionTest, ASSERT_ANY_THROW) {
3682 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003683 EXPECT_FATAL_FAILURE(
3684 ASSERT_ANY_THROW(ThrowNothing()),
3685 "Expected: ThrowNothing() throws an exception.\n"
3686 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003687}
3688
3689#endif // GTEST_HAS_EXCEPTIONS
3690
shiqian4b6829f2008-07-03 22:38:12 +00003691// Makes sure we deal with the precedence of <<. This test should
3692// compile.
3693TEST(AssertionTest, AssertPrecedence) {
3694 ASSERT_EQ(1 < 2, true);
3695 ASSERT_EQ(true && false, false);
3696}
3697
3698// A subroutine used by the following test.
3699void TestEq1(int x) {
3700 ASSERT_EQ(1, x);
3701}
3702
3703// Tests calling a test subroutine that's not part of a fixture.
3704TEST(AssertionTest, NonFixtureSubroutine) {
3705 EXPECT_FATAL_FAILURE(TestEq1(2),
3706 "Value of: x");
3707}
3708
3709// An uncopyable class.
3710class Uncopyable {
3711 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00003712 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqian4b6829f2008-07-03 22:38:12 +00003713
3714 int value() const { return value_; }
3715 bool operator==(const Uncopyable& rhs) const {
3716 return value() == rhs.value();
3717 }
3718 private:
3719 // This constructor deliberately has no implementation, as we don't
3720 // want this class to be copyable.
3721 Uncopyable(const Uncopyable&); // NOLINT
3722
3723 int value_;
3724};
3725
3726::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3727 return os << value.value();
3728}
3729
3730
3731bool IsPositiveUncopyable(const Uncopyable& x) {
3732 return x.value() > 0;
3733}
3734
3735// A subroutine used by the following test.
3736void TestAssertNonPositive() {
3737 Uncopyable y(-1);
3738 ASSERT_PRED1(IsPositiveUncopyable, y);
3739}
3740// A subroutine used by the following test.
3741void TestAssertEqualsUncopyable() {
3742 Uncopyable x(5);
3743 Uncopyable y(-1);
3744 ASSERT_EQ(x, y);
3745}
3746
3747// Tests that uncopyable objects can be used in assertions.
3748TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3749 Uncopyable x(5);
3750 ASSERT_PRED1(IsPositiveUncopyable, x);
3751 ASSERT_EQ(x, x);
3752 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3753 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3754 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3755 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3756}
3757
3758// Tests that uncopyable objects can be used in expects.
3759TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3760 Uncopyable x(5);
3761 EXPECT_PRED1(IsPositiveUncopyable, x);
3762 Uncopyable y(-1);
3763 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3764 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3765 EXPECT_EQ(x, x);
3766 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3767 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3768}
3769
zhanyong.wan739d3042010-08-09 18:19:15 +00003770enum NamedEnum {
3771 kE1 = 0,
3772 kE2 = 1,
3773};
3774
3775TEST(AssertionTest, NamedEnum) {
3776 EXPECT_EQ(kE1, kE1);
3777 EXPECT_LT(kE1, kE2);
3778 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3779 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
3780}
shiqian4b6829f2008-07-03 22:38:12 +00003781
3782// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003783// anonymous enums in assertions. Therefore the following test is not
3784// done on Mac.
vladlosev673a0cb2010-02-03 02:27:02 +00003785// Sun Studio also rejects this code.
3786#if !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian4b6829f2008-07-03 22:38:12 +00003787
3788// Tests using assertions with anonymous enums.
3789enum {
zhanyong.wan739d3042010-08-09 18:19:15 +00003790 kCaseA = -1,
zhanyong.wan4cd62602009-02-23 23:21:55 +00003791#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003792 // We want to test the case where the size of the anonymous enum is
3793 // larger than sizeof(int), to make sure our implementation of the
3794 // assertions doesn't truncate the enums. However, MSVC
3795 // (incorrectly) doesn't allow an enum value to exceed the range of
3796 // an int, so this has to be conditionally compiled.
3797 //
zhanyong.wan739d3042010-08-09 18:19:15 +00003798 // On Linux, kCaseB and kCaseA have the same value when truncated to
shiqian4b6829f2008-07-03 22:38:12 +00003799 // int size. We want to test whether this will confuse the
3800 // assertions.
zhanyong.wan739d3042010-08-09 18:19:15 +00003801 kCaseB = testing::internal::kMaxBiggestInt,
shiqian4b6829f2008-07-03 22:38:12 +00003802#else
zhanyong.wan739d3042010-08-09 18:19:15 +00003803 kCaseB = INT_MAX,
shiqian4b6829f2008-07-03 22:38:12 +00003804#endif // GTEST_OS_LINUX
zhanyong.wan739d3042010-08-09 18:19:15 +00003805 kCaseC = 42,
shiqian4b6829f2008-07-03 22:38:12 +00003806};
3807
3808TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003809#if GTEST_OS_LINUX
zhanyong.wan739d3042010-08-09 18:19:15 +00003810 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
shiqian4b6829f2008-07-03 22:38:12 +00003811#endif // GTEST_OS_LINUX
3812
zhanyong.wan739d3042010-08-09 18:19:15 +00003813 EXPECT_EQ(kCaseA, kCaseA);
3814 EXPECT_NE(kCaseA, kCaseB);
3815 EXPECT_LT(kCaseA, kCaseB);
3816 EXPECT_LE(kCaseA, kCaseB);
3817 EXPECT_GT(kCaseB, kCaseA);
3818 EXPECT_GE(kCaseA, kCaseA);
3819 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3820 "(kCaseA) >= (kCaseB)");
3821 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3822 "-1 vs 42");
shiqian4b6829f2008-07-03 22:38:12 +00003823
zhanyong.wan739d3042010-08-09 18:19:15 +00003824 ASSERT_EQ(kCaseA, kCaseA);
3825 ASSERT_NE(kCaseA, kCaseB);
3826 ASSERT_LT(kCaseA, kCaseB);
3827 ASSERT_LE(kCaseA, kCaseB);
3828 ASSERT_GT(kCaseB, kCaseA);
3829 ASSERT_GE(kCaseA, kCaseA);
3830 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3831 "Value of: kCaseB");
3832 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3833 "Actual: 42");
3834 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3835 "Which is: -1");
shiqian4b6829f2008-07-03 22:38:12 +00003836}
3837
vladlosev673a0cb2010-02-03 02:27:02 +00003838#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian4b6829f2008-07-03 22:38:12 +00003839
zhanyong.wan4cd62602009-02-23 23:21:55 +00003840#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003841
3842static HRESULT UnexpectedHRESULTFailure() {
3843 return E_UNEXPECTED;
3844}
3845
3846static HRESULT OkHRESULTSuccess() {
3847 return S_OK;
3848}
3849
3850static HRESULT FalseHRESULTSuccess() {
3851 return S_FALSE;
3852}
3853
3854// HRESULT assertion tests test both zero and non-zero
3855// success codes as well as failure message for each.
3856//
3857// Windows CE doesn't support message texts.
3858TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3859 EXPECT_HRESULT_SUCCEEDED(S_OK);
3860 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3861
shiqian4b6829f2008-07-03 22:38:12 +00003862 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003863 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3864 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003865}
3866
3867TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3868 ASSERT_HRESULT_SUCCEEDED(S_OK);
3869 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3870
shiqian4b6829f2008-07-03 22:38:12 +00003871 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003872 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3873 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003874}
3875
3876TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3877 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3878
shiqian4b6829f2008-07-03 22:38:12 +00003879 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003880 "Expected: (OkHRESULTSuccess()) fails.\n"
3881 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00003882 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003883 "Expected: (FalseHRESULTSuccess()) fails.\n"
3884 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003885}
3886
3887TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3888 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3889
zhanyong.wan98efcc42009-04-28 00:28:09 +00003890#ifndef __BORLANDC__
3891 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003892 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003893 "Expected: (OkHRESULTSuccess()) fails.\n"
3894 " Actual: 0x00000000");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003895#endif
shiqian4b6829f2008-07-03 22:38:12 +00003896 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003897 "Expected: (FalseHRESULTSuccess()) fails.\n"
3898 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003899}
3900
3901// Tests that streaming to the HRESULT macros works.
3902TEST(HRESULTAssertionTest, Streaming) {
3903 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3904 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3905 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3906 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3907
3908 EXPECT_NONFATAL_FAILURE(
3909 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3910 "expected failure");
3911
zhanyong.wan98efcc42009-04-28 00:28:09 +00003912#ifndef __BORLANDC__
3913 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003914 EXPECT_FATAL_FAILURE(
3915 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3916 "expected failure");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003917#endif
shiqian4b6829f2008-07-03 22:38:12 +00003918
3919 EXPECT_NONFATAL_FAILURE(
3920 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3921 "expected failure");
3922
3923 EXPECT_FATAL_FAILURE(
3924 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3925 "expected failure");
3926}
3927
zhanyong.wan4cd62602009-02-23 23:21:55 +00003928#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003929
zhanyong.wan98efcc42009-04-28 00:28:09 +00003930#ifdef __BORLANDC__
3931// Silences warnings: "Condition is always true", "Unreachable code"
3932#pragma option push -w-ccc -w-rch
3933#endif
3934
shiqian4b6829f2008-07-03 22:38:12 +00003935// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003936TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003937 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00003938 ASSERT_TRUE(false) << "This should never be executed; "
3939 "It's a compilation test only.";
3940
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003941 if (AlwaysTrue())
shiqian4b6829f2008-07-03 22:38:12 +00003942 EXPECT_FALSE(false);
3943 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003944 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003945
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003946 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00003947 ASSERT_LT(1, 3);
3948
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003949 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003950 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003951 else
3952 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00003953}
shiqian9204c8e2008-09-12 20:57:22 +00003954
3955#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00003956// Tests that the compiler will not complain about unreachable code in the
3957// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3958TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3959 int n = 0;
3960
3961 EXPECT_THROW(throw 1, int);
3962 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3963 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3964 EXPECT_NO_THROW(n++);
3965 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3966 EXPECT_ANY_THROW(throw 1);
3967 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3968}
3969
shiqiane44602e2008-10-11 07:20:02 +00003970TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003971 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00003972 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00003973
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003974 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00003975 EXPECT_THROW(ThrowAnInteger(), int);
3976 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003977 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003978
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003979 if (AlwaysFalse())
shiqian9204c8e2008-09-12 20:57:22 +00003980 EXPECT_NO_THROW(ThrowAnInteger());
3981
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003982 if (AlwaysTrue())
zhanyong.wanac60cef2009-02-08 04:53:35 +00003983 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003984 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003985 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003986
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003987 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00003988 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003989
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003990 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00003991 EXPECT_ANY_THROW(ThrowAnInteger());
3992 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003993 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003994}
shiqian9204c8e2008-09-12 20:57:22 +00003995#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00003996
3997TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003998 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00003999 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4000 << "It's a compilation test only.";
4001 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004002 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004003
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004004 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004005 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4006 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004007 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004008
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004009 if (AlwaysTrue())
shiqiane44602e2008-10-11 07:20:02 +00004010 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4011 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004012 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004013
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004014 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004015 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004016 else
4017 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00004018}
4019
4020// Tests that the assertion macros work well with switch statements.
4021TEST(AssertionSyntaxTest, WorksWithSwitch) {
4022 switch (0) {
4023 case 1:
4024 break;
4025 default:
4026 ASSERT_TRUE(true);
4027 }
4028
4029 switch (0)
4030 case 0:
4031 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4032
4033 // Binary assertions are implemented using a different code path
4034 // than the Boolean assertions. Hence we test them separately.
4035 switch (0) {
4036 case 1:
4037 default:
4038 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4039 }
4040
4041 switch (0)
4042 case 0:
4043 EXPECT_NE(1, 2);
4044}
4045
shiqian9204c8e2008-09-12 20:57:22 +00004046#if GTEST_HAS_EXCEPTIONS
4047
4048void ThrowAString() {
4049 throw "String";
4050}
4051
4052// Test that the exception assertion macros compile and work with const
4053// type qualifier.
4054TEST(AssertionSyntaxTest, WorksWithConst) {
4055 ASSERT_THROW(ThrowAString(), const char*);
4056
4057 EXPECT_THROW(ThrowAString(), const char*);
4058}
4059
4060#endif // GTEST_HAS_EXCEPTIONS
4061
shiqian4b6829f2008-07-03 22:38:12 +00004062} // namespace
4063
shiqian4b6829f2008-07-03 22:38:12 +00004064namespace testing {
4065
4066// Tests that Google Test tracks SUCCEED*.
4067TEST(SuccessfulAssertionTest, SUCCEED) {
4068 SUCCEED();
4069 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004070 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004071}
4072
4073// Tests that Google Test doesn't track successful EXPECT_*.
4074TEST(SuccessfulAssertionTest, EXPECT) {
4075 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004076 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004077}
4078
4079// Tests that Google Test doesn't track successful EXPECT_STR*.
4080TEST(SuccessfulAssertionTest, EXPECT_STR) {
4081 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004082 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004083}
4084
4085// Tests that Google Test doesn't track successful ASSERT_*.
4086TEST(SuccessfulAssertionTest, ASSERT) {
4087 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004088 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004089}
4090
4091// Tests that Google Test doesn't track successful ASSERT_STR*.
4092TEST(SuccessfulAssertionTest, ASSERT_STR) {
4093 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004094 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004095}
4096
4097} // namespace testing
4098
4099namespace {
4100
4101// Tests EXPECT_TRUE.
4102TEST(ExpectTest, EXPECT_TRUE) {
4103 EXPECT_TRUE(2 > 1); // NOLINT
4104 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4105 "Value of: 2 < 1\n"
4106 " Actual: false\n"
4107 "Expected: true");
4108 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4109 "2 > 3");
4110}
4111
vladlosevfbd53a52009-10-20 21:03:10 +00004112// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4113TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4114 EXPECT_TRUE(ResultIsEven(2));
4115 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4116 "Value of: ResultIsEven(3)\n"
4117 " Actual: false (3 is odd)\n"
4118 "Expected: true");
4119 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4120 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4121 "Value of: ResultIsEvenNoExplanation(3)\n"
4122 " Actual: false (3 is odd)\n"
4123 "Expected: true");
4124}
4125
shiqian4b6829f2008-07-03 22:38:12 +00004126// Tests EXPECT_FALSE.
4127TEST(ExpectTest, EXPECT_FALSE) {
4128 EXPECT_FALSE(2 < 1); // NOLINT
4129 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4130 "Value of: 2 > 1\n"
4131 " Actual: true\n"
4132 "Expected: false");
4133 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4134 "2 < 3");
4135}
4136
vladlosevfbd53a52009-10-20 21:03:10 +00004137// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4138TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4139 EXPECT_FALSE(ResultIsEven(3));
4140 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4141 "Value of: ResultIsEven(2)\n"
4142 " Actual: true (2 is even)\n"
4143 "Expected: false");
4144 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4145 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4146 "Value of: ResultIsEvenNoExplanation(2)\n"
4147 " Actual: true\n"
4148 "Expected: false");
4149}
4150
zhanyong.wan98efcc42009-04-28 00:28:09 +00004151#ifdef __BORLANDC__
4152// Restores warnings after previous "#pragma option push" supressed them
4153#pragma option pop
4154#endif
4155
shiqian4b6829f2008-07-03 22:38:12 +00004156// Tests EXPECT_EQ.
4157TEST(ExpectTest, EXPECT_EQ) {
4158 EXPECT_EQ(5, 2 + 3);
4159 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4160 "Value of: 2*3\n"
4161 " Actual: 6\n"
4162 "Expected: 5");
4163 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4164 "2 - 3");
4165}
4166
4167// Tests using EXPECT_EQ on double values. The purpose is to make
4168// sure that the specialization we did for integer and anonymous enums
4169// isn't used for double arguments.
4170TEST(ExpectTest, EXPECT_EQ_Double) {
4171 // A success.
4172 EXPECT_EQ(5.6, 5.6);
4173
4174 // A failure.
4175 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4176 "5.1");
4177}
4178
vladlosev5147b452010-03-17 18:22:59 +00004179#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004180// Tests EXPECT_EQ(NULL, pointer).
4181TEST(ExpectTest, EXPECT_EQ_NULL) {
4182 // A success.
4183 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00004184 // Some older GCC versions may issue a spurious waring in this or the next
4185 // assertion statement. This warning should not be suppressed with
4186 // static_cast since the test verifies the ability to use bare NULL as the
4187 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00004188 EXPECT_EQ(NULL, p);
4189
4190 // A failure.
4191 int n = 0;
4192 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4193 "Value of: &n\n");
4194}
vladlosev5147b452010-03-17 18:22:59 +00004195#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004196
4197// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4198// treated as a null pointer by the compiler, we need to make sure
4199// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4200// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4201TEST(ExpectTest, EXPECT_EQ_0) {
4202 int n = 0;
4203
4204 // A success.
4205 EXPECT_EQ(0, n);
4206
4207 // A failure.
4208 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4209 "Expected: 0");
4210}
4211
4212// Tests EXPECT_NE.
4213TEST(ExpectTest, EXPECT_NE) {
4214 EXPECT_NE(6, 7);
4215
4216 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4217 "Expected: ('a') != ('a'), "
4218 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4219 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4220 "2");
4221 char* const p0 = NULL;
4222 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4223 "p0");
4224 // Only way to get the Nokia compiler to compile the cast
4225 // is to have a separate void* variable first. Putting
4226 // the two casts on the same line doesn't work, neither does
4227 // a direct C-style to char*.
4228 void* pv1 = (void*)0x1234; // NOLINT
4229 char* const p1 = reinterpret_cast<char*>(pv1);
4230 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4231 "p1");
4232}
4233
4234// Tests EXPECT_LE.
4235TEST(ExpectTest, EXPECT_LE) {
4236 EXPECT_LE(2, 3);
4237 EXPECT_LE(2, 2);
4238 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4239 "Expected: (2) <= (0), actual: 2 vs 0");
4240 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4241 "(1.1) <= (0.9)");
4242}
4243
4244// Tests EXPECT_LT.
4245TEST(ExpectTest, EXPECT_LT) {
4246 EXPECT_LT(2, 3);
4247 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4248 "Expected: (2) < (2), actual: 2 vs 2");
4249 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4250 "(2) < (1)");
4251}
4252
4253// Tests EXPECT_GE.
4254TEST(ExpectTest, EXPECT_GE) {
4255 EXPECT_GE(2, 1);
4256 EXPECT_GE(2, 2);
4257 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4258 "Expected: (2) >= (3), actual: 2 vs 3");
4259 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4260 "(0.9) >= (1.1)");
4261}
4262
4263// Tests EXPECT_GT.
4264TEST(ExpectTest, EXPECT_GT) {
4265 EXPECT_GT(2, 1);
4266 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4267 "Expected: (2) > (2), actual: 2 vs 2");
4268 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4269 "(2) > (3)");
4270}
4271
shiqian9204c8e2008-09-12 20:57:22 +00004272#if GTEST_HAS_EXCEPTIONS
4273
4274// Tests EXPECT_THROW.
4275TEST(ExpectTest, EXPECT_THROW) {
4276 EXPECT_THROW(ThrowAnInteger(), int);
4277 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004278 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00004279 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00004280 EXPECT_NONFATAL_FAILURE(
4281 EXPECT_THROW(ThrowNothing(), bool),
4282 "Expected: ThrowNothing() throws an exception of type bool.\n"
4283 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00004284}
4285
4286// Tests EXPECT_NO_THROW.
4287TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00004288 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004289 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004290 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00004291 "exception.\n Actual: it throws.");
4292}
4293
4294// Tests EXPECT_ANY_THROW.
4295TEST(ExpectTest, EXPECT_ANY_THROW) {
4296 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004297 EXPECT_NONFATAL_FAILURE(
4298 EXPECT_ANY_THROW(ThrowNothing()),
4299 "Expected: ThrowNothing() throws an exception.\n"
4300 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004301}
4302
4303#endif // GTEST_HAS_EXCEPTIONS
4304
shiqian4b6829f2008-07-03 22:38:12 +00004305// Make sure we deal with the precedence of <<.
4306TEST(ExpectTest, ExpectPrecedence) {
4307 EXPECT_EQ(1 < 2, true);
4308 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4309 "Value of: true && false");
4310}
4311
4312
4313// Tests the StreamableToString() function.
4314
4315// Tests using StreamableToString() on a scalar.
4316TEST(StreamableToStringTest, Scalar) {
4317 EXPECT_STREQ("5", StreamableToString(5).c_str());
4318}
4319
4320// Tests using StreamableToString() on a non-char pointer.
4321TEST(StreamableToStringTest, Pointer) {
4322 int n = 0;
4323 int* p = &n;
4324 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4325}
4326
4327// Tests using StreamableToString() on a NULL non-char pointer.
4328TEST(StreamableToStringTest, NullPointer) {
4329 int* p = NULL;
4330 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4331}
4332
4333// Tests using StreamableToString() on a C string.
4334TEST(StreamableToStringTest, CString) {
4335 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4336}
4337
4338// Tests using StreamableToString() on a NULL C string.
4339TEST(StreamableToStringTest, NullCString) {
4340 char* p = NULL;
4341 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4342}
4343
4344// Tests using streamable values as assertion messages.
4345
shiqian4b6829f2008-07-03 22:38:12 +00004346// Tests using std::string as an assertion message.
4347TEST(StreamableTest, string) {
4348 static const std::string str(
4349 "This failure message is a std::string, and is expected.");
4350 EXPECT_FATAL_FAILURE(FAIL() << str,
4351 str.c_str());
4352}
4353
4354// Tests that we can output strings containing embedded NULs.
4355// Limited to Linux because we can only do this with std::string's.
4356TEST(StreamableTest, stringWithEmbeddedNUL) {
4357 static const char char_array_with_nul[] =
4358 "Here's a NUL\0 and some more string";
4359 static const std::string string_with_nul(char_array_with_nul,
4360 sizeof(char_array_with_nul)
4361 - 1); // drops the trailing NUL
4362 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4363 "Here's a NUL\\0 and some more string");
4364}
4365
shiqian4b6829f2008-07-03 22:38:12 +00004366// Tests that we can output a NUL char.
4367TEST(StreamableTest, NULChar) {
4368 EXPECT_FATAL_FAILURE({ // NOLINT
4369 FAIL() << "A NUL" << '\0' << " and some more string";
4370 }, "A NUL\\0 and some more string");
4371}
4372
4373// Tests using int as an assertion message.
4374TEST(StreamableTest, int) {
4375 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4376 "900913");
4377}
4378
4379// Tests using NULL char pointer as an assertion message.
4380//
4381// In MSVC, streaming a NULL char * causes access violation. Google Test
4382// implemented a workaround (substituting "(null)" for NULL). This
4383// tests whether the workaround works.
4384TEST(StreamableTest, NullCharPtr) {
4385 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4386 "(null)");
4387}
4388
4389// Tests that basic IO manipulators (endl, ends, and flush) can be
4390// streamed to testing::Message.
4391TEST(StreamableTest, BasicIoManip) {
4392 EXPECT_FATAL_FAILURE({ // NOLINT
4393 FAIL() << "Line 1." << std::endl
4394 << "A NUL char " << std::ends << std::flush << " in line 2.";
4395 }, "Line 1.\nA NUL char \\0 in line 2.");
4396}
4397
shiqian4b6829f2008-07-03 22:38:12 +00004398// Tests the macros that haven't been covered so far.
4399
4400void AddFailureHelper(bool* aborted) {
4401 *aborted = true;
4402 ADD_FAILURE() << "Failure";
4403 *aborted = false;
4404}
4405
4406// Tests ADD_FAILURE.
4407TEST(MacroTest, ADD_FAILURE) {
4408 bool aborted = true;
4409 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4410 "Failure");
4411 EXPECT_FALSE(aborted);
4412}
4413
zhanyong.wand5ad2ca2010-07-26 21:59:50 +00004414// Tests ADD_FAILURE_AT.
4415TEST(MacroTest, ADD_FAILURE_AT) {
4416 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4417 // the failure message contains the user-streamed part.
4418 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4419
4420 // Verifies that the user-streamed part is optional.
4421 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4422
4423 // Unfortunately, we cannot verify that the failure message contains
4424 // the right file path and line number the same way, as
4425 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4426 // line number. Instead, we do that in gtest_output_test_.cc.
4427}
4428
shiqian4b6829f2008-07-03 22:38:12 +00004429// Tests FAIL.
4430TEST(MacroTest, FAIL) {
4431 EXPECT_FATAL_FAILURE(FAIL(),
4432 "Failed");
4433 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4434 "Intentional failure.");
4435}
4436
4437// Tests SUCCEED
4438TEST(MacroTest, SUCCEED) {
4439 SUCCEED();
4440 SUCCEED() << "Explicit success.";
4441}
4442
4443
4444// Tests for EXPECT_EQ() and ASSERT_EQ().
4445//
4446// These tests fail *intentionally*, s.t. the failure messages can be
4447// generated and tested.
4448//
4449// We have different tests for different argument types.
4450
4451// Tests using bool values in {EXPECT|ASSERT}_EQ.
4452TEST(EqAssertionTest, Bool) {
4453 EXPECT_EQ(true, true);
4454 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4455 "Value of: true");
4456}
4457
4458// Tests using int values in {EXPECT|ASSERT}_EQ.
4459TEST(EqAssertionTest, Int) {
4460 ASSERT_EQ(32, 32);
4461 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4462 "33");
4463}
4464
4465// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4466TEST(EqAssertionTest, Time_T) {
4467 EXPECT_EQ(static_cast<time_t>(0),
4468 static_cast<time_t>(0));
4469 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4470 static_cast<time_t>(1234)),
4471 "1234");
4472}
4473
4474// Tests using char values in {EXPECT|ASSERT}_EQ.
4475TEST(EqAssertionTest, Char) {
4476 ASSERT_EQ('z', 'z');
4477 const char ch = 'b';
4478 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4479 "ch");
4480 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4481 "ch");
4482}
4483
4484// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4485TEST(EqAssertionTest, WideChar) {
4486 EXPECT_EQ(L'b', L'b');
4487
4488 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4489 "Value of: L'x'\n"
4490 " Actual: L'x' (120, 0x78)\n"
4491 "Expected: L'\0'\n"
4492 "Which is: L'\0' (0, 0x0)");
4493
4494 static wchar_t wchar;
4495 wchar = L'b';
4496 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4497 "wchar");
4498 wchar = L'\x8119';
4499 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4500 "Value of: wchar");
4501}
4502
shiqian4b6829f2008-07-03 22:38:12 +00004503// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4504TEST(EqAssertionTest, StdString) {
4505 // Compares a const char* to an std::string that has identical
4506 // content.
4507 ASSERT_EQ("Test", ::std::string("Test"));
4508
4509 // Compares two identical std::strings.
4510 static const ::std::string str1("A * in the middle");
4511 static const ::std::string str2(str1);
4512 EXPECT_EQ(str1, str2);
4513
4514 // Compares a const char* to an std::string that has different
4515 // content
4516 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4517 "::std::string(\"test\")");
4518
4519 // Compares an std::string to a char* that has different content.
4520 char* const p1 = const_cast<char*>("foo");
4521 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4522 "p1");
4523
4524 // Compares two std::strings that have different contents, one of
4525 // which having a NUL character in the middle. This should fail.
4526 static ::std::string str3(str1);
4527 str3.at(2) = '\0';
4528 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4529 "Value of: str3\n"
4530 " Actual: \"A \\0 in the middle\"");
4531}
4532
shiqian4b6829f2008-07-03 22:38:12 +00004533#if GTEST_HAS_STD_WSTRING
4534
4535// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4536TEST(EqAssertionTest, StdWideString) {
4537 // Compares an std::wstring to a const wchar_t* that has identical
4538 // content.
4539 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4540
4541 // Compares two identical std::wstrings.
4542 const ::std::wstring wstr1(L"A * in the middle");
4543 const ::std::wstring wstr2(wstr1);
4544 ASSERT_EQ(wstr1, wstr2);
4545
4546 // Compares an std::wstring to a const wchar_t* that has different
4547 // content.
4548 EXPECT_NONFATAL_FAILURE({ // NOLINT
4549 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4550 }, "L\"Test\\x8120\"");
4551
4552 // Compares two std::wstrings that have different contents, one of
4553 // which having a NUL character in the middle.
4554 ::std::wstring wstr3(wstr1);
4555 wstr3.at(2) = L'\0';
4556 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4557 "wstr3");
4558
4559 // Compares a wchar_t* to an std::wstring that has different
4560 // content.
4561 EXPECT_FATAL_FAILURE({ // NOLINT
4562 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4563 }, "");
4564}
4565
4566#endif // GTEST_HAS_STD_WSTRING
4567
4568#if GTEST_HAS_GLOBAL_STRING
4569// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4570TEST(EqAssertionTest, GlobalString) {
4571 // Compares a const char* to a ::string that has identical content.
4572 EXPECT_EQ("Test", ::string("Test"));
4573
4574 // Compares two identical ::strings.
4575 const ::string str1("A * in the middle");
4576 const ::string str2(str1);
4577 ASSERT_EQ(str1, str2);
4578
4579 // Compares a ::string to a const char* that has different content.
4580 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4581 "test");
4582
4583 // Compares two ::strings that have different contents, one of which
4584 // having a NUL character in the middle.
4585 ::string str3(str1);
4586 str3.at(2) = '\0';
4587 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4588 "str3");
4589
4590 // Compares a ::string to a char* that has different content.
4591 EXPECT_FATAL_FAILURE({ // NOLINT
4592 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4593 }, "");
4594}
4595
4596#endif // GTEST_HAS_GLOBAL_STRING
4597
4598#if GTEST_HAS_GLOBAL_WSTRING
4599
4600// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4601TEST(EqAssertionTest, GlobalWideString) {
4602 // Compares a const wchar_t* to a ::wstring that has identical content.
4603 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4604
4605 // Compares two identical ::wstrings.
4606 static const ::wstring wstr1(L"A * in the middle");
4607 static const ::wstring wstr2(wstr1);
4608 EXPECT_EQ(wstr1, wstr2);
4609
4610 // Compares a const wchar_t* to a ::wstring that has different
4611 // content.
4612 EXPECT_NONFATAL_FAILURE({ // NOLINT
4613 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4614 }, "Test\\x8119");
4615
4616 // Compares a wchar_t* to a ::wstring that has different content.
4617 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4618 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4619 "bar");
4620
4621 // Compares two ::wstrings that have different contents, one of which
4622 // having a NUL character in the middle.
4623 static ::wstring wstr3;
4624 wstr3 = wstr1;
4625 wstr3.at(2) = L'\0';
4626 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4627 "wstr3");
4628}
4629
4630#endif // GTEST_HAS_GLOBAL_WSTRING
4631
4632// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4633TEST(EqAssertionTest, CharPointer) {
4634 char* const p0 = NULL;
4635 // Only way to get the Nokia compiler to compile the cast
4636 // is to have a separate void* variable first. Putting
4637 // the two casts on the same line doesn't work, neither does
4638 // a direct C-style to char*.
4639 void* pv1 = (void*)0x1234; // NOLINT
4640 void* pv2 = (void*)0xABC0; // NOLINT
4641 char* const p1 = reinterpret_cast<char*>(pv1);
4642 char* const p2 = reinterpret_cast<char*>(pv2);
4643 ASSERT_EQ(p1, p1);
4644
4645 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4646 "Value of: p2");
4647 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4648 "p2");
4649 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4650 reinterpret_cast<char*>(0xABC0)),
4651 "ABC0");
4652}
4653
4654// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4655TEST(EqAssertionTest, WideCharPointer) {
4656 wchar_t* const p0 = NULL;
4657 // Only way to get the Nokia compiler to compile the cast
4658 // is to have a separate void* variable first. Putting
4659 // the two casts on the same line doesn't work, neither does
4660 // a direct C-style to char*.
4661 void* pv1 = (void*)0x1234; // NOLINT
4662 void* pv2 = (void*)0xABC0; // NOLINT
4663 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4664 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4665 EXPECT_EQ(p0, p0);
4666
4667 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4668 "Value of: p2");
4669 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4670 "p2");
4671 void* pv3 = (void*)0x1234; // NOLINT
4672 void* pv4 = (void*)0xABC0; // NOLINT
4673 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4674 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4675 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4676 "p4");
4677}
4678
4679// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4680TEST(EqAssertionTest, OtherPointer) {
4681 ASSERT_EQ(static_cast<const int*>(NULL),
4682 static_cast<const int*>(NULL));
4683 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4684 reinterpret_cast<const int*>(0x1234)),
4685 "0x1234");
4686}
4687
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004688// A class that supports binary comparison operators but not streaming.
4689class UnprintableChar {
4690 public:
4691 explicit UnprintableChar(char ch) : char_(ch) {}
4692
4693 bool operator==(const UnprintableChar& rhs) const {
4694 return char_ == rhs.char_;
4695 }
4696 bool operator!=(const UnprintableChar& rhs) const {
4697 return char_ != rhs.char_;
4698 }
4699 bool operator<(const UnprintableChar& rhs) const {
4700 return char_ < rhs.char_;
4701 }
4702 bool operator<=(const UnprintableChar& rhs) const {
4703 return char_ <= rhs.char_;
4704 }
4705 bool operator>(const UnprintableChar& rhs) const {
4706 return char_ > rhs.char_;
4707 }
4708 bool operator>=(const UnprintableChar& rhs) const {
4709 return char_ >= rhs.char_;
4710 }
4711
4712 private:
4713 char char_;
4714};
4715
4716// Tests that ASSERT_EQ() and friends don't require the arguments to
4717// be printable.
4718TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4719 const UnprintableChar x('x'), y('y');
4720 ASSERT_EQ(x, x);
4721 EXPECT_NE(x, y);
4722 ASSERT_LT(x, y);
4723 EXPECT_LE(x, y);
4724 ASSERT_GT(y, x);
4725 EXPECT_GE(x, x);
4726
4727 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4728 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4729 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4730 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4731 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4732
4733 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4734 // variables, so we have to write UnprintableChar('x') instead of x.
4735 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4736 "1-byte object <78>");
4737 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4738 "1-byte object <78>");
4739 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4740 "1-byte object <79>");
4741 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4742 "1-byte object <78>");
4743 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4744 "1-byte object <79>");
4745}
4746
shiqian4b6829f2008-07-03 22:38:12 +00004747// Tests the FRIEND_TEST macro.
4748
4749// This class has a private member we want to test. We will test it
4750// both in a TEST and in a TEST_F.
4751class Foo {
4752 public:
4753 Foo() {}
4754
4755 private:
4756 int Bar() const { return 1; }
4757
4758 // Declares the friend tests that can access the private member
4759 // Bar().
4760 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4761 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4762};
4763
4764// Tests that the FRIEND_TEST declaration allows a TEST to access a
4765// class's private members. This should compile.
4766TEST(FRIEND_TEST_Test, TEST) {
4767 ASSERT_EQ(1, Foo().Bar());
4768}
4769
4770// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004771class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004772 protected:
4773 Foo foo;
4774};
4775
4776// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4777// class's private members. This should compile.
4778TEST_F(FRIEND_TEST_Test2, TEST_F) {
4779 ASSERT_EQ(1, foo.Bar());
4780}
4781
4782// Tests the life cycle of Test objects.
4783
4784// The test fixture for testing the life cycle of Test objects.
4785//
4786// This class counts the number of live test objects that uses this
4787// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004788class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004789 protected:
4790 // Constructor. Increments the number of test objects that uses
4791 // this fixture.
4792 TestLifeCycleTest() { count_++; }
4793
4794 // Destructor. Decrements the number of test objects that uses this
4795 // fixture.
4796 ~TestLifeCycleTest() { count_--; }
4797
4798 // Returns the number of live test objects that uses this fixture.
4799 int count() const { return count_; }
4800
4801 private:
4802 static int count_;
4803};
4804
4805int TestLifeCycleTest::count_ = 0;
4806
4807// Tests the life cycle of test objects.
4808TEST_F(TestLifeCycleTest, Test1) {
4809 // There should be only one test object in this test case that's
4810 // currently alive.
4811 ASSERT_EQ(1, count());
4812}
4813
4814// Tests the life cycle of test objects.
4815TEST_F(TestLifeCycleTest, Test2) {
4816 // After Test1 is done and Test2 is started, there should still be
4817 // only one live test object, as the object for Test1 should've been
4818 // deleted.
4819 ASSERT_EQ(1, count());
4820}
4821
4822} // namespace
4823
vladlosevfbd53a52009-10-20 21:03:10 +00004824// Tests that the copy constructor works when it is NOT optimized away by
4825// the compiler.
4826TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
4827 // Checks that the copy constructor doesn't try to dereference NULL pointers
4828 // in the source object.
4829 AssertionResult r1 = AssertionSuccess();
4830 AssertionResult r2 = r1;
4831 // The following line is added to prevent the compiler from optimizing
4832 // away the constructor call.
4833 r1 << "abc";
4834
4835 AssertionResult r3 = r1;
4836 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
4837 EXPECT_STREQ("abc", r1.message());
4838}
4839
4840// Tests that AssertionSuccess and AssertionFailure construct
4841// AssertionResult objects as expected.
4842TEST(AssertionResultTest, ConstructionWorks) {
4843 AssertionResult r1 = AssertionSuccess();
4844 EXPECT_TRUE(r1);
4845 EXPECT_STREQ("", r1.message());
4846
4847 AssertionResult r2 = AssertionSuccess() << "abc";
4848 EXPECT_TRUE(r2);
4849 EXPECT_STREQ("abc", r2.message());
4850
4851 AssertionResult r3 = AssertionFailure();
4852 EXPECT_FALSE(r3);
4853 EXPECT_STREQ("", r3.message());
4854
4855 AssertionResult r4 = AssertionFailure() << "def";
4856 EXPECT_FALSE(r4);
4857 EXPECT_STREQ("def", r4.message());
4858
4859 AssertionResult r5 = AssertionFailure(Message() << "ghi");
4860 EXPECT_FALSE(r5);
4861 EXPECT_STREQ("ghi", r5.message());
4862}
4863
4864// Tests that the negation fips the predicate result but keeps the message.
4865TEST(AssertionResultTest, NegationWorks) {
4866 AssertionResult r1 = AssertionSuccess() << "abc";
4867 EXPECT_FALSE(!r1);
4868 EXPECT_STREQ("abc", (!r1).message());
4869
4870 AssertionResult r2 = AssertionFailure() << "def";
4871 EXPECT_TRUE(!r2);
4872 EXPECT_STREQ("def", (!r2).message());
4873}
4874
4875TEST(AssertionResultTest, StreamingWorks) {
4876 AssertionResult r = AssertionSuccess();
4877 r << "abc" << 'd' << 0 << true;
4878 EXPECT_STREQ("abcd0true", r.message());
4879}
4880
shiqian4b6829f2008-07-03 22:38:12 +00004881// Tests streaming a user type whose definition and operator << are
4882// both in the global namespace.
4883class Base {
4884 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004885 explicit Base(int an_x) : x_(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004886 int x() const { return x_; }
4887 private:
4888 int x_;
4889};
4890std::ostream& operator<<(std::ostream& os,
4891 const Base& val) {
4892 return os << val.x();
4893}
4894std::ostream& operator<<(std::ostream& os,
4895 const Base* pointer) {
4896 return os << "(" << pointer->x() << ")";
4897}
4898
4899TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004900 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004901 Base a(1);
4902
4903 msg << a << &a; // Uses ::operator<<.
4904 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4905}
4906
4907// Tests streaming a user type whose definition and operator<< are
4908// both in an unnamed namespace.
4909namespace {
4910class MyTypeInUnnamedNameSpace : public Base {
4911 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004912 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004913};
4914std::ostream& operator<<(std::ostream& os,
4915 const MyTypeInUnnamedNameSpace& val) {
4916 return os << val.x();
4917}
4918std::ostream& operator<<(std::ostream& os,
4919 const MyTypeInUnnamedNameSpace* pointer) {
4920 return os << "(" << pointer->x() << ")";
4921}
4922} // namespace
4923
4924TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004925 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004926 MyTypeInUnnamedNameSpace a(1);
4927
4928 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4929 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4930}
4931
4932// Tests streaming a user type whose definition and operator<< are
4933// both in a user namespace.
4934namespace namespace1 {
4935class MyTypeInNameSpace1 : public Base {
4936 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004937 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004938};
4939std::ostream& operator<<(std::ostream& os,
4940 const MyTypeInNameSpace1& val) {
4941 return os << val.x();
4942}
4943std::ostream& operator<<(std::ostream& os,
4944 const MyTypeInNameSpace1* pointer) {
4945 return os << "(" << pointer->x() << ")";
4946}
4947} // namespace namespace1
4948
4949TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004950 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004951 namespace1::MyTypeInNameSpace1 a(1);
4952
4953 msg << a << &a; // Uses namespace1::operator<<.
4954 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4955}
4956
4957// Tests streaming a user type whose definition is in a user namespace
4958// but whose operator<< is in the global namespace.
4959namespace namespace2 {
4960class MyTypeInNameSpace2 : public ::Base {
4961 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00004962 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00004963};
4964} // namespace namespace2
4965std::ostream& operator<<(std::ostream& os,
4966 const namespace2::MyTypeInNameSpace2& val) {
4967 return os << val.x();
4968}
4969std::ostream& operator<<(std::ostream& os,
4970 const namespace2::MyTypeInNameSpace2* pointer) {
4971 return os << "(" << pointer->x() << ")";
4972}
4973
4974TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00004975 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004976 namespace2::MyTypeInNameSpace2 a(1);
4977
4978 msg << a << &a; // Uses ::operator<<.
4979 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4980}
4981
4982// Tests streaming NULL pointers to testing::Message.
4983TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00004984 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004985 char* const p1 = NULL;
4986 unsigned char* const p2 = NULL;
4987 int* p3 = NULL;
4988 double* p4 = NULL;
4989 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00004990 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004991
4992 msg << p1 << p2 << p3 << p4 << p5 << p6;
4993 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4994 msg.GetString().c_str());
4995}
4996
4997// Tests streaming wide strings to testing::Message.
4998TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00004999 // Streams a NULL of type const wchar_t*.
5000 const wchar_t* const_wstr = NULL;
5001 EXPECT_STREQ("(null)",
5002 (Message() << const_wstr).GetString().c_str());
5003
5004 // Streams a NULL of type wchar_t*.
5005 wchar_t* wstr = NULL;
5006 EXPECT_STREQ("(null)",
5007 (Message() << wstr).GetString().c_str());
5008
5009 // Streams a non-NULL of type const wchar_t*.
5010 const_wstr = L"abc\x8119";
5011 EXPECT_STREQ("abc\xe8\x84\x99",
5012 (Message() << const_wstr).GetString().c_str());
5013
5014 // Streams a non-NULL of type wchar_t*.
5015 wstr = const_cast<wchar_t*>(const_wstr);
5016 EXPECT_STREQ("abc\xe8\x84\x99",
5017 (Message() << wstr).GetString().c_str());
5018}
5019
5020
5021// This line tests that we can define tests in the testing namespace.
5022namespace testing {
5023
5024// Tests the TestInfo class.
5025
shiqian760af5c2008-08-06 21:43:15 +00005026class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005027 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005028 static const TestInfo* GetTestInfo(const char* test_name) {
5029 const TestCase* const test_case = GetUnitTestImpl()->
5030 GetTestCase("TestInfoTest", "", NULL, NULL);
5031
5032 for (int i = 0; i < test_case->total_test_count(); ++i) {
5033 const TestInfo* const test_info = test_case->GetTestInfo(i);
5034 if (strcmp(test_name, test_info->name()) == 0)
5035 return test_info;
5036 }
5037 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005038 }
5039
5040 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00005041 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00005042 return test_info->result();
5043 }
5044};
5045
5046// Tests TestInfo::test_case_name() and TestInfo::name().
5047TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005048 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00005049
5050 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5051 ASSERT_STREQ("Names", test_info->name());
5052}
5053
5054// Tests TestInfo::result().
5055TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005056 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00005057
5058 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005059 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005060
5061 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005062 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005063}
5064
5065// Tests setting up and tearing down a test case.
5066
shiqian760af5c2008-08-06 21:43:15 +00005067class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005068 protected:
5069 // This will be called once before the first test in this test case
5070 // is run.
5071 static void SetUpTestCase() {
5072 printf("Setting up the test case . . .\n");
5073
5074 // Initializes some shared resource. In this simple example, we
5075 // just create a C string. More complex stuff can be done if
5076 // desired.
5077 shared_resource_ = "123";
5078
5079 // Increments the number of test cases that have been set up.
5080 counter_++;
5081
5082 // SetUpTestCase() should be called only once.
5083 EXPECT_EQ(1, counter_);
5084 }
5085
5086 // This will be called once after the last test in this test case is
5087 // run.
5088 static void TearDownTestCase() {
5089 printf("Tearing down the test case . . .\n");
5090
5091 // Decrements the number of test cases that have been set up.
5092 counter_--;
5093
5094 // TearDownTestCase() should be called only once.
5095 EXPECT_EQ(0, counter_);
5096
5097 // Cleans up the shared resource.
5098 shared_resource_ = NULL;
5099 }
5100
5101 // This will be called before each test in this test case.
5102 virtual void SetUp() {
5103 // SetUpTestCase() should be called only once, so counter_ should
5104 // always be 1.
5105 EXPECT_EQ(1, counter_);
5106 }
5107
5108 // Number of test cases that have been set up.
5109 static int counter_;
5110
5111 // Some resource to be shared by all tests in this test case.
5112 static const char* shared_resource_;
5113};
5114
5115int SetUpTestCaseTest::counter_ = 0;
5116const char* SetUpTestCaseTest::shared_resource_ = NULL;
5117
5118// A test that uses the shared resource.
5119TEST_F(SetUpTestCaseTest, Test1) {
5120 EXPECT_STRNE(NULL, shared_resource_);
5121}
5122
5123// Another test that uses the shared resource.
5124TEST_F(SetUpTestCaseTest, Test2) {
5125 EXPECT_STREQ("123", shared_resource_);
5126}
5127
5128// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5129
5130// The Flags struct stores a copy of all Google Test flags.
5131struct Flags {
5132 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00005133 Flags() : also_run_disabled_tests(false),
5134 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00005135 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00005136 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00005137 filter(""),
5138 list_tests(false),
5139 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005140 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005141 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005142 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005143 shuffle(false),
vladlosevba015a92009-11-17 22:43:15 +00005144 stack_trace_depth(kMaxStackTraceDepth),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005145 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00005146
5147 // Factory methods.
5148
shiqianca6949f2009-01-10 01:16:33 +00005149 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5150 // the given value.
5151 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5152 Flags flags;
5153 flags.also_run_disabled_tests = also_run_disabled_tests;
5154 return flags;
5155 }
5156
shiqian4b6829f2008-07-03 22:38:12 +00005157 // Creates a Flags struct where the gtest_break_on_failure flag has
5158 // the given value.
5159 static Flags BreakOnFailure(bool break_on_failure) {
5160 Flags flags;
5161 flags.break_on_failure = break_on_failure;
5162 return flags;
5163 }
5164
5165 // Creates a Flags struct where the gtest_catch_exceptions flag has
5166 // the given value.
5167 static Flags CatchExceptions(bool catch_exceptions) {
5168 Flags flags;
5169 flags.catch_exceptions = catch_exceptions;
5170 return flags;
5171 }
5172
shiqian21d43d12009-01-08 01:10:31 +00005173 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5174 // the given value.
5175 static Flags DeathTestUseFork(bool death_test_use_fork) {
5176 Flags flags;
5177 flags.death_test_use_fork = death_test_use_fork;
5178 return flags;
5179 }
5180
shiqian4b6829f2008-07-03 22:38:12 +00005181 // Creates a Flags struct where the gtest_filter flag has the given
5182 // value.
5183 static Flags Filter(const char* filter) {
5184 Flags flags;
5185 flags.filter = filter;
5186 return flags;
5187 }
5188
5189 // Creates a Flags struct where the gtest_list_tests flag has the
5190 // given value.
5191 static Flags ListTests(bool list_tests) {
5192 Flags flags;
5193 flags.list_tests = list_tests;
5194 return flags;
5195 }
5196
5197 // Creates a Flags struct where the gtest_output flag has the given
5198 // value.
5199 static Flags Output(const char* output) {
5200 Flags flags;
5201 flags.output = output;
5202 return flags;
5203 }
5204
shiqiand981cee2008-07-25 04:06:16 +00005205 // Creates a Flags struct where the gtest_print_time flag has the given
5206 // value.
5207 static Flags PrintTime(bool print_time) {
5208 Flags flags;
5209 flags.print_time = print_time;
5210 return flags;
5211 }
5212
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005213 // Creates a Flags struct where the gtest_random_seed flag has
5214 // the given value.
5215 static Flags RandomSeed(Int32 random_seed) {
5216 Flags flags;
5217 flags.random_seed = random_seed;
5218 return flags;
5219 }
5220
shiqian4b6829f2008-07-03 22:38:12 +00005221 // Creates a Flags struct where the gtest_repeat flag has the given
5222 // value.
5223 static Flags Repeat(Int32 repeat) {
5224 Flags flags;
5225 flags.repeat = repeat;
5226 return flags;
5227 }
5228
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005229 // Creates a Flags struct where the gtest_shuffle flag has
5230 // the given value.
5231 static Flags Shuffle(bool shuffle) {
5232 Flags flags;
5233 flags.shuffle = shuffle;
5234 return flags;
5235 }
5236
vladlosevba015a92009-11-17 22:43:15 +00005237 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5238 // the given value.
5239 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5240 Flags flags;
5241 flags.stack_trace_depth = stack_trace_depth;
5242 return flags;
5243 }
5244
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005245 // Creates a Flags struct where the gtest_throw_on_failure flag has
5246 // the given value.
5247 static Flags ThrowOnFailure(bool throw_on_failure) {
5248 Flags flags;
5249 flags.throw_on_failure = throw_on_failure;
5250 return flags;
5251 }
5252
shiqian4b6829f2008-07-03 22:38:12 +00005253 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00005254 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00005255 bool break_on_failure;
5256 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00005257 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00005258 const char* filter;
5259 bool list_tests;
5260 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00005261 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005262 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00005263 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005264 bool shuffle;
vladlosevba015a92009-11-17 22:43:15 +00005265 Int32 stack_trace_depth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005266 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00005267};
5268
5269// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00005270class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005271 protected:
5272 // Clears the flags before each test.
5273 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00005274 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005275 GTEST_FLAG(break_on_failure) = false;
5276 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00005277 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005278 GTEST_FLAG(filter) = "";
5279 GTEST_FLAG(list_tests) = false;
5280 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005281 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005282 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00005283 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005284 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00005285 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005286 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005287 }
5288
5289 // Asserts that two narrow or wide string arrays are equal.
5290 template <typename CharType>
5291 static void AssertStringArrayEq(size_t size1, CharType** array1,
5292 size_t size2, CharType** array2) {
5293 ASSERT_EQ(size1, size2) << " Array sizes different.";
5294
5295 for (size_t i = 0; i != size1; i++) {
5296 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5297 }
5298 }
5299
5300 // Verifies that the flag values match the expected values.
5301 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00005302 EXPECT_EQ(expected.also_run_disabled_tests,
5303 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00005304 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5305 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00005306 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00005307 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5308 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5309 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00005310 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005311 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00005312 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005313 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005314 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
vladlosevba015a92009-11-17 22:43:15 +00005315 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
shiqian4b6829f2008-07-03 22:38:12 +00005316 }
5317
5318 // Parses a command line (specified by argc1 and argv1), then
5319 // verifies that the flag values are expected and that the
5320 // recognized flags are removed from the command line.
5321 template <typename CharType>
5322 static void TestParsingFlags(int argc1, const CharType** argv1,
5323 int argc2, const CharType** argv2,
vladlosevba015a92009-11-17 22:43:15 +00005324 const Flags& expected, bool should_print_help) {
5325 const bool saved_help_flag = ::testing::internal::g_help_flag;
5326 ::testing::internal::g_help_flag = false;
5327
zhanyong.wancf8a5842010-01-28 21:50:29 +00005328#if GTEST_HAS_STREAM_REDIRECTION_
5329 CaptureStdout();
5330#endif // GTEST_HAS_STREAM_REDIRECTION_
5331
shiqian4b6829f2008-07-03 22:38:12 +00005332 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00005333 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00005334
zhanyong.wancf8a5842010-01-28 21:50:29 +00005335#if GTEST_HAS_STREAM_REDIRECTION_
5336 const String captured_stdout = GetCapturedStdout();
5337#endif // GTEST_HAS_STREAM_REDIRECTION_
5338
shiqian4b6829f2008-07-03 22:38:12 +00005339 // Verifies the flag values.
5340 CheckFlags(expected);
5341
5342 // Verifies that the recognized flags are removed from the command
5343 // line.
5344 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
vladlosevba015a92009-11-17 22:43:15 +00005345
5346 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5347 // help message for the flags it recognizes.
5348 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5349
zhanyong.wancf8a5842010-01-28 21:50:29 +00005350#if GTEST_HAS_STREAM_REDIRECTION_
5351 const char* const expected_help_fragment =
5352 "This program contains tests written using";
5353 if (should_print_help) {
5354 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5355 } else {
5356 EXPECT_PRED_FORMAT2(IsNotSubstring,
5357 expected_help_fragment, captured_stdout);
5358 }
5359#endif // GTEST_HAS_STREAM_REDIRECTION_
vladlosevba015a92009-11-17 22:43:15 +00005360
5361 ::testing::internal::g_help_flag = saved_help_flag;
shiqian4b6829f2008-07-03 22:38:12 +00005362 }
5363
5364 // This macro wraps TestParsingFlags s.t. the user doesn't need
5365 // to specify the array sizes.
vladlosevba015a92009-11-17 22:43:15 +00005366#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
shiqian4b6829f2008-07-03 22:38:12 +00005367 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
vladlosevba015a92009-11-17 22:43:15 +00005368 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5369 expected, should_print_help)
shiqian4b6829f2008-07-03 22:38:12 +00005370};
5371
5372// Tests parsing an empty command line.
5373TEST_F(InitGoogleTestTest, Empty) {
5374 const char* argv[] = {
5375 NULL
5376 };
5377
5378 const char* argv2[] = {
5379 NULL
5380 };
5381
vladlosevba015a92009-11-17 22:43:15 +00005382 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005383}
5384
5385// Tests parsing a command line that has no flag.
5386TEST_F(InitGoogleTestTest, NoFlag) {
5387 const char* argv[] = {
5388 "foo.exe",
5389 NULL
5390 };
5391
5392 const char* argv2[] = {
5393 "foo.exe",
5394 NULL
5395 };
5396
vladlosevba015a92009-11-17 22:43:15 +00005397 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005398}
5399
5400// Tests parsing a bad --gtest_filter flag.
5401TEST_F(InitGoogleTestTest, FilterBad) {
5402 const char* argv[] = {
5403 "foo.exe",
5404 "--gtest_filter",
5405 NULL
5406 };
5407
5408 const char* argv2[] = {
5409 "foo.exe",
5410 "--gtest_filter",
5411 NULL
5412 };
5413
vladlosevba015a92009-11-17 22:43:15 +00005414 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
shiqian4b6829f2008-07-03 22:38:12 +00005415}
5416
5417// Tests parsing an empty --gtest_filter flag.
5418TEST_F(InitGoogleTestTest, FilterEmpty) {
5419 const char* argv[] = {
5420 "foo.exe",
5421 "--gtest_filter=",
5422 NULL
5423 };
5424
5425 const char* argv2[] = {
5426 "foo.exe",
5427 NULL
5428 };
5429
vladlosevba015a92009-11-17 22:43:15 +00005430 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
shiqian4b6829f2008-07-03 22:38:12 +00005431}
5432
5433// Tests parsing a non-empty --gtest_filter flag.
5434TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5435 const char* argv[] = {
5436 "foo.exe",
5437 "--gtest_filter=abc",
5438 NULL
5439 };
5440
5441 const char* argv2[] = {
5442 "foo.exe",
5443 NULL
5444 };
5445
vladlosevba015a92009-11-17 22:43:15 +00005446 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005447}
5448
5449// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005450TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00005451 const char* argv[] = {
5452 "foo.exe",
5453 "--gtest_break_on_failure",
5454 NULL
5455};
5456
5457 const char* argv2[] = {
5458 "foo.exe",
5459 NULL
5460 };
5461
vladlosevba015a92009-11-17 22:43:15 +00005462 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005463}
5464
5465// Tests parsing --gtest_break_on_failure=0.
5466TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5467 const char* argv[] = {
5468 "foo.exe",
5469 "--gtest_break_on_failure=0",
5470 NULL
5471 };
5472
5473 const char* argv2[] = {
5474 "foo.exe",
5475 NULL
5476 };
5477
vladlosevba015a92009-11-17 22:43:15 +00005478 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005479}
5480
5481// Tests parsing --gtest_break_on_failure=f.
5482TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5483 const char* argv[] = {
5484 "foo.exe",
5485 "--gtest_break_on_failure=f",
5486 NULL
5487 };
5488
5489 const char* argv2[] = {
5490 "foo.exe",
5491 NULL
5492 };
5493
vladlosevba015a92009-11-17 22:43:15 +00005494 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005495}
5496
5497// Tests parsing --gtest_break_on_failure=F.
5498TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5499 const char* argv[] = {
5500 "foo.exe",
5501 "--gtest_break_on_failure=F",
5502 NULL
5503 };
5504
5505 const char* argv2[] = {
5506 "foo.exe",
5507 NULL
5508 };
5509
vladlosevba015a92009-11-17 22:43:15 +00005510 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005511}
5512
5513// Tests parsing a --gtest_break_on_failure flag that has a "true"
5514// definition.
5515TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5516 const char* argv[] = {
5517 "foo.exe",
5518 "--gtest_break_on_failure=1",
5519 NULL
5520 };
5521
5522 const char* argv2[] = {
5523 "foo.exe",
5524 NULL
5525 };
5526
vladlosevba015a92009-11-17 22:43:15 +00005527 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005528}
5529
5530// Tests parsing --gtest_catch_exceptions.
5531TEST_F(InitGoogleTestTest, CatchExceptions) {
5532 const char* argv[] = {
5533 "foo.exe",
5534 "--gtest_catch_exceptions",
5535 NULL
5536 };
5537
5538 const char* argv2[] = {
5539 "foo.exe",
5540 NULL
5541 };
5542
vladlosevba015a92009-11-17 22:43:15 +00005543 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005544}
5545
shiqian21d43d12009-01-08 01:10:31 +00005546// Tests parsing --gtest_death_test_use_fork.
5547TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5548 const char* argv[] = {
5549 "foo.exe",
5550 "--gtest_death_test_use_fork",
5551 NULL
5552 };
5553
5554 const char* argv2[] = {
5555 "foo.exe",
5556 NULL
5557 };
5558
vladlosevba015a92009-11-17 22:43:15 +00005559 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
shiqian21d43d12009-01-08 01:10:31 +00005560}
5561
shiqian4b6829f2008-07-03 22:38:12 +00005562// Tests having the same flag twice with different values. The
5563// expected behavior is that the one coming last takes precedence.
5564TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5565 const char* argv[] = {
5566 "foo.exe",
5567 "--gtest_filter=a",
5568 "--gtest_filter=b",
5569 NULL
5570 };
5571
5572 const char* argv2[] = {
5573 "foo.exe",
5574 NULL
5575 };
5576
vladlosevba015a92009-11-17 22:43:15 +00005577 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005578}
5579
5580// Tests having an unrecognized flag on the command line.
5581TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5582 const char* argv[] = {
5583 "foo.exe",
5584 "--gtest_break_on_failure",
5585 "bar", // Unrecognized by Google Test.
5586 "--gtest_filter=b",
5587 NULL
5588 };
5589
5590 const char* argv2[] = {
5591 "foo.exe",
5592 "bar",
5593 NULL
5594 };
5595
5596 Flags flags;
5597 flags.break_on_failure = true;
5598 flags.filter = "b";
vladlosevba015a92009-11-17 22:43:15 +00005599 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00005600}
5601
5602// Tests having a --gtest_list_tests flag
5603TEST_F(InitGoogleTestTest, ListTestsFlag) {
5604 const char* argv[] = {
5605 "foo.exe",
5606 "--gtest_list_tests",
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::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005616}
5617
5618// Tests having a --gtest_list_tests flag with a "true" value
5619TEST_F(InitGoogleTestTest, ListTestsTrue) {
5620 const char* argv[] = {
5621 "foo.exe",
5622 "--gtest_list_tests=1",
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::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005632}
5633
5634// Tests having a --gtest_list_tests flag with a "false" value
5635TEST_F(InitGoogleTestTest, ListTestsFalse) {
5636 const char* argv[] = {
5637 "foo.exe",
5638 "--gtest_list_tests=0",
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::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005648}
5649
5650// Tests parsing --gtest_list_tests=f.
5651TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5652 const char* argv[] = {
5653 "foo.exe",
5654 "--gtest_list_tests=f",
5655 NULL
5656 };
5657
5658 const char* argv2[] = {
5659 "foo.exe",
5660 NULL
5661 };
5662
vladlosevba015a92009-11-17 22:43:15 +00005663 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005664}
5665
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005666// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005667TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5668 const char* argv[] = {
5669 "foo.exe",
5670 "--gtest_list_tests=F",
5671 NULL
5672 };
5673
5674 const char* argv2[] = {
5675 "foo.exe",
5676 NULL
5677 };
5678
vladlosevba015a92009-11-17 22:43:15 +00005679 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005680}
5681
5682// Tests parsing --gtest_output (invalid).
5683TEST_F(InitGoogleTestTest, OutputEmpty) {
5684 const char* argv[] = {
5685 "foo.exe",
5686 "--gtest_output",
5687 NULL
5688 };
5689
5690 const char* argv2[] = {
5691 "foo.exe",
5692 "--gtest_output",
5693 NULL
5694 };
5695
vladlosevba015a92009-11-17 22:43:15 +00005696 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
shiqian4b6829f2008-07-03 22:38:12 +00005697}
5698
5699// Tests parsing --gtest_output=xml
5700TEST_F(InitGoogleTestTest, OutputXml) {
5701 const char* argv[] = {
5702 "foo.exe",
5703 "--gtest_output=xml",
5704 NULL
5705 };
5706
5707 const char* argv2[] = {
5708 "foo.exe",
5709 NULL
5710 };
5711
vladlosevba015a92009-11-17 22:43:15 +00005712 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005713}
5714
5715// Tests parsing --gtest_output=xml:file
5716TEST_F(InitGoogleTestTest, OutputXmlFile) {
5717 const char* argv[] = {
5718 "foo.exe",
5719 "--gtest_output=xml:file",
5720 NULL
5721 };
5722
5723 const char* argv2[] = {
5724 "foo.exe",
5725 NULL
5726 };
5727
vladlosevba015a92009-11-17 22:43:15 +00005728 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005729}
5730
5731// Tests parsing --gtest_output=xml:directory/path/
5732TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5733 const char* argv[] = {
5734 "foo.exe",
5735 "--gtest_output=xml:directory/path/",
5736 NULL
5737 };
5738
5739 const char* argv2[] = {
5740 "foo.exe",
5741 NULL
5742 };
5743
vladlosevba015a92009-11-17 22:43:15 +00005744 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5745 Flags::Output("xml:directory/path/"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005746}
5747
shiqiand981cee2008-07-25 04:06:16 +00005748// Tests having a --gtest_print_time flag
5749TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5750 const char* argv[] = {
5751 "foo.exe",
5752 "--gtest_print_time",
5753 NULL
5754 };
5755
5756 const char* argv2[] = {
5757 "foo.exe",
5758 NULL
5759 };
5760
vladlosevba015a92009-11-17 22:43:15 +00005761 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005762}
5763
5764// Tests having a --gtest_print_time flag with a "true" value
5765TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5766 const char* argv[] = {
5767 "foo.exe",
5768 "--gtest_print_time=1",
5769 NULL
5770 };
5771
5772 const char* argv2[] = {
5773 "foo.exe",
5774 NULL
5775 };
5776
vladlosevba015a92009-11-17 22:43:15 +00005777 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005778}
5779
5780// Tests having a --gtest_print_time flag with a "false" value
5781TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5782 const char* argv[] = {
5783 "foo.exe",
5784 "--gtest_print_time=0",
5785 NULL
5786 };
5787
5788 const char* argv2[] = {
5789 "foo.exe",
5790 NULL
5791 };
5792
vladlosevba015a92009-11-17 22:43:15 +00005793 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005794}
5795
5796// Tests parsing --gtest_print_time=f.
5797TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5798 const char* argv[] = {
5799 "foo.exe",
5800 "--gtest_print_time=f",
5801 NULL
5802 };
5803
5804 const char* argv2[] = {
5805 "foo.exe",
5806 NULL
5807 };
5808
vladlosevba015a92009-11-17 22:43:15 +00005809 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005810}
5811
5812// Tests parsing --gtest_print_time=F.
5813TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5814 const char* argv[] = {
5815 "foo.exe",
5816 "--gtest_print_time=F",
5817 NULL
5818 };
5819
5820 const char* argv2[] = {
5821 "foo.exe",
5822 NULL
5823 };
5824
vladlosevba015a92009-11-17 22:43:15 +00005825 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005826}
5827
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005828// Tests parsing --gtest_random_seed=number
5829TEST_F(InitGoogleTestTest, RandomSeed) {
5830 const char* argv[] = {
5831 "foo.exe",
5832 "--gtest_random_seed=1000",
5833 NULL
5834 };
5835
5836 const char* argv2[] = {
5837 "foo.exe",
5838 NULL
5839 };
5840
vladlosevba015a92009-11-17 22:43:15 +00005841 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005842}
5843
shiqian4b6829f2008-07-03 22:38:12 +00005844// Tests parsing --gtest_repeat=number
5845TEST_F(InitGoogleTestTest, Repeat) {
5846 const char* argv[] = {
5847 "foo.exe",
5848 "--gtest_repeat=1000",
5849 NULL
5850 };
5851
5852 const char* argv2[] = {
5853 "foo.exe",
5854 NULL
5855 };
5856
vladlosevba015a92009-11-17 22:43:15 +00005857 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
shiqian4b6829f2008-07-03 22:38:12 +00005858}
5859
shiqianca6949f2009-01-10 01:16:33 +00005860// Tests having a --gtest_also_run_disabled_tests flag
5861TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5862 const char* argv[] = {
5863 "foo.exe",
5864 "--gtest_also_run_disabled_tests",
5865 NULL
5866 };
5867
5868 const char* argv2[] = {
5869 "foo.exe",
5870 NULL
5871 };
5872
vladlosevba015a92009-11-17 22:43:15 +00005873 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5874 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00005875}
5876
5877// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5878TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5879 const char* argv[] = {
5880 "foo.exe",
5881 "--gtest_also_run_disabled_tests=1",
5882 NULL
5883 };
5884
5885 const char* argv2[] = {
5886 "foo.exe",
5887 NULL
5888 };
5889
vladlosevba015a92009-11-17 22:43:15 +00005890 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5891 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00005892}
5893
5894// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5895TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5896 const char* argv[] = {
5897 "foo.exe",
5898 "--gtest_also_run_disabled_tests=0",
5899 NULL
5900 };
5901
5902 const char* argv2[] = {
5903 "foo.exe",
5904 NULL
5905 };
5906
vladlosevba015a92009-11-17 22:43:15 +00005907 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5908 Flags::AlsoRunDisabledTests(false), false);
shiqianca6949f2009-01-10 01:16:33 +00005909}
5910
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005911// Tests parsing --gtest_shuffle.
5912TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
5913 const char* argv[] = {
5914 "foo.exe",
5915 "--gtest_shuffle",
5916 NULL
5917};
5918
5919 const char* argv2[] = {
5920 "foo.exe",
5921 NULL
5922 };
5923
vladlosevba015a92009-11-17 22:43:15 +00005924 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005925}
5926
5927// Tests parsing --gtest_shuffle=0.
5928TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
5929 const char* argv[] = {
5930 "foo.exe",
5931 "--gtest_shuffle=0",
5932 NULL
5933 };
5934
5935 const char* argv2[] = {
5936 "foo.exe",
5937 NULL
5938 };
5939
vladlosevba015a92009-11-17 22:43:15 +00005940 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005941}
5942
5943// Tests parsing a --gtest_shuffle flag that has a "true"
5944// definition.
5945TEST_F(InitGoogleTestTest, ShuffleTrue) {
5946 const char* argv[] = {
5947 "foo.exe",
5948 "--gtest_shuffle=1",
5949 NULL
5950 };
5951
5952 const char* argv2[] = {
5953 "foo.exe",
5954 NULL
5955 };
5956
vladlosevba015a92009-11-17 22:43:15 +00005957 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
5958}
5959
5960// Tests parsing --gtest_stack_trace_depth=number.
5961TEST_F(InitGoogleTestTest, StackTraceDepth) {
5962 const char* argv[] = {
5963 "foo.exe",
5964 "--gtest_stack_trace_depth=5",
5965 NULL
5966 };
5967
5968 const char* argv2[] = {
5969 "foo.exe",
5970 NULL
5971 };
5972
5973 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005974}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005975
5976// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005977TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005978 const char* argv[] = {
5979 "foo.exe",
5980 "--gtest_throw_on_failure",
5981 NULL
5982};
5983
5984 const char* argv2[] = {
5985 "foo.exe",
5986 NULL
5987 };
5988
vladlosevba015a92009-11-17 22:43:15 +00005989 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005990}
5991
5992// Tests parsing --gtest_throw_on_failure=0.
5993TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5994 const char* argv[] = {
5995 "foo.exe",
5996 "--gtest_throw_on_failure=0",
5997 NULL
5998 };
5999
6000 const char* argv2[] = {
6001 "foo.exe",
6002 NULL
6003 };
6004
vladlosevba015a92009-11-17 22:43:15 +00006005 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006006}
6007
6008// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6009// definition.
6010TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6011 const char* argv[] = {
6012 "foo.exe",
6013 "--gtest_throw_on_failure=1",
6014 NULL
6015 };
6016
6017 const char* argv2[] = {
6018 "foo.exe",
6019 NULL
6020 };
6021
vladlosevba015a92009-11-17 22:43:15 +00006022 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006023}
6024
zhanyong.wan4cd62602009-02-23 23:21:55 +00006025#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006026// Tests parsing wide strings.
6027TEST_F(InitGoogleTestTest, WideStrings) {
6028 const wchar_t* argv[] = {
6029 L"foo.exe",
6030 L"--gtest_filter=Foo*",
6031 L"--gtest_list_tests=1",
6032 L"--gtest_break_on_failure",
6033 L"--non_gtest_flag",
6034 NULL
6035 };
6036
6037 const wchar_t* argv2[] = {
6038 L"foo.exe",
6039 L"--non_gtest_flag",
6040 NULL
6041 };
6042
6043 Flags expected_flags;
6044 expected_flags.break_on_failure = true;
6045 expected_flags.filter = "Foo*";
6046 expected_flags.list_tests = true;
6047
vladlosevba015a92009-11-17 22:43:15 +00006048 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00006049}
6050#endif // GTEST_OS_WINDOWS
6051
6052// Tests current_test_info() in UnitTest.
6053class CurrentTestInfoTest : public Test {
6054 protected:
6055 // Tests that current_test_info() returns NULL before the first test in
6056 // the test case is run.
6057 static void SetUpTestCase() {
6058 // There should be no tests running at this point.
6059 const TestInfo* test_info =
6060 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006061 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006062 << "There should be no tests running at this point.";
6063 }
6064
6065 // Tests that current_test_info() returns NULL after the last test in
6066 // the test case has run.
6067 static void TearDownTestCase() {
6068 const TestInfo* test_info =
6069 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006070 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006071 << "There should be no tests running at this point.";
6072 }
6073};
6074
6075// Tests that current_test_info() returns TestInfo for currently running
6076// test by checking the expected test name against the actual one.
6077TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6078 const TestInfo* test_info =
6079 UnitTest::GetInstance()->current_test_info();
6080 ASSERT_TRUE(NULL != test_info)
6081 << "There is a test running so we should have a valid TestInfo.";
6082 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6083 << "Expected the name of the currently running test case.";
6084 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6085 << "Expected the name of the currently running test.";
6086}
6087
6088// Tests that current_test_info() returns TestInfo for currently running
6089// test by checking the expected test name against the actual one. We
6090// use this test to see that the TestInfo object actually changed from
6091// the previous invocation.
6092TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6093 const TestInfo* test_info =
6094 UnitTest::GetInstance()->current_test_info();
6095 ASSERT_TRUE(NULL != test_info)
6096 << "There is a test running so we should have a valid TestInfo.";
6097 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6098 << "Expected the name of the currently running test case.";
6099 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6100 << "Expected the name of the currently running test.";
6101}
6102
6103} // namespace testing
6104
6105// These two lines test that we can define tests in a namespace that
6106// has the name "testing" and is nested in another namespace.
6107namespace my_namespace {
6108namespace testing {
6109
6110// Makes sure that TEST knows to use ::testing::Test instead of
6111// ::my_namespace::testing::Test.
6112class Test {};
6113
6114// Makes sure that an assertion knows to use ::testing::Message instead of
6115// ::my_namespace::testing::Message.
6116class Message {};
6117
6118// Makes sure that an assertion knows to use
6119// ::testing::AssertionResult instead of
6120// ::my_namespace::testing::AssertionResult.
6121class AssertionResult {};
6122
6123// Tests that an assertion that should succeed works as expected.
6124TEST(NestedTestingNamespaceTest, Success) {
6125 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6126}
6127
6128// Tests that an assertion that should fail works as expected.
6129TEST(NestedTestingNamespaceTest, Failure) {
6130 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6131 "This failure is expected.");
6132}
6133
6134} // namespace testing
6135} // namespace my_namespace
6136
6137// Tests that one can call superclass SetUp and TearDown methods--
6138// that is, that they are not private.
6139// No tests are based on this fixture; the test "passes" if it compiles
6140// successfully.
shiqian760af5c2008-08-06 21:43:15 +00006141class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00006142 protected:
6143 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00006144 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00006145 }
6146 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00006147 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00006148 }
6149};
6150
6151// StreamingAssertionsTest tests the streaming versions of a representative
6152// sample of assertions.
6153TEST(StreamingAssertionsTest, Unconditional) {
6154 SUCCEED() << "expected success";
6155 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6156 "expected failure");
6157 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6158 "expected failure");
6159}
6160
zhanyong.wan98efcc42009-04-28 00:28:09 +00006161#ifdef __BORLANDC__
6162// Silences warnings: "Condition is always true", "Unreachable code"
6163#pragma option push -w-ccc -w-rch
6164#endif
6165
shiqian4b6829f2008-07-03 22:38:12 +00006166TEST(StreamingAssertionsTest, Truth) {
6167 EXPECT_TRUE(true) << "unexpected failure";
6168 ASSERT_TRUE(true) << "unexpected failure";
6169 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6170 "expected failure");
6171 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6172 "expected failure");
6173}
6174
6175TEST(StreamingAssertionsTest, Truth2) {
6176 EXPECT_FALSE(false) << "unexpected failure";
6177 ASSERT_FALSE(false) << "unexpected failure";
6178 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6179 "expected failure");
6180 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6181 "expected failure");
6182}
6183
zhanyong.wan98efcc42009-04-28 00:28:09 +00006184#ifdef __BORLANDC__
6185// Restores warnings after previous "#pragma option push" supressed them
6186#pragma option pop
6187#endif
6188
shiqian4b6829f2008-07-03 22:38:12 +00006189TEST(StreamingAssertionsTest, IntegerEquals) {
6190 EXPECT_EQ(1, 1) << "unexpected failure";
6191 ASSERT_EQ(1, 1) << "unexpected failure";
6192 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6193 "expected failure");
6194 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6195 "expected failure");
6196}
6197
6198TEST(StreamingAssertionsTest, IntegerLessThan) {
6199 EXPECT_LT(1, 2) << "unexpected failure";
6200 ASSERT_LT(1, 2) << "unexpected failure";
6201 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6202 "expected failure");
6203 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6204 "expected failure");
6205}
6206
6207TEST(StreamingAssertionsTest, StringsEqual) {
6208 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6209 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6210 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6211 "expected failure");
6212 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6213 "expected failure");
6214}
6215
6216TEST(StreamingAssertionsTest, StringsNotEqual) {
6217 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6218 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6219 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6220 "expected failure");
6221 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6222 "expected failure");
6223}
6224
6225TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6226 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6227 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6228 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6229 "expected failure");
6230 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6231 "expected failure");
6232}
6233
6234TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6235 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6236 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6237 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6238 "expected failure");
6239 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6240 "expected failure");
6241}
6242
6243TEST(StreamingAssertionsTest, FloatingPointEquals) {
6244 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6245 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6246 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6247 "expected failure");
6248 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6249 "expected failure");
6250}
6251
shiqian9204c8e2008-09-12 20:57:22 +00006252#if GTEST_HAS_EXCEPTIONS
6253
6254TEST(StreamingAssertionsTest, Throw) {
6255 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6256 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6257 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6258 "expected failure", "expected failure");
6259 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6260 "expected failure", "expected failure");
6261}
6262
6263TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00006264 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6265 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00006266 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6267 "expected failure", "expected failure");
6268 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6269 "expected failure", "expected failure");
6270}
6271
6272TEST(StreamingAssertionsTest, AnyThrow) {
6273 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6274 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00006275 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006276 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00006277 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006278 "expected failure", "expected failure");
6279}
6280
6281#endif // GTEST_HAS_EXCEPTIONS
6282
shiqian4b6829f2008-07-03 22:38:12 +00006283// Tests that Google Test correctly decides whether to use colors in the output.
6284
6285TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6286 GTEST_FLAG(color) = "yes";
6287
6288 SetEnv("TERM", "xterm"); // TERM supports colors.
6289 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6290 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6291
6292 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6293 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6294 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6295}
6296
6297TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6298 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6299
6300 GTEST_FLAG(color) = "True";
6301 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6302
6303 GTEST_FLAG(color) = "t";
6304 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6305
6306 GTEST_FLAG(color) = "1";
6307 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6308}
6309
6310TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6311 GTEST_FLAG(color) = "no";
6312
6313 SetEnv("TERM", "xterm"); // TERM supports colors.
6314 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6315 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6316
6317 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6318 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6319 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6320}
6321
6322TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6323 SetEnv("TERM", "xterm"); // TERM supports colors.
6324
6325 GTEST_FLAG(color) = "F";
6326 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6327
6328 GTEST_FLAG(color) = "0";
6329 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6330
6331 GTEST_FLAG(color) = "unknown";
6332 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6333}
6334
6335TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6336 GTEST_FLAG(color) = "auto";
6337
6338 SetEnv("TERM", "xterm"); // TERM supports colors.
6339 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6340 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6341}
6342
6343TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6344 GTEST_FLAG(color) = "auto";
6345
zhanyong.wan4cd62602009-02-23 23:21:55 +00006346#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006347 // On Windows, we ignore the TERM variable as it's usually not set.
6348
6349 SetEnv("TERM", "dumb");
6350 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6351
6352 SetEnv("TERM", "");
6353 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6354
6355 SetEnv("TERM", "xterm");
6356 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6357#else
6358 // On non-Windows platforms, we rely on TERM to determine if the
6359 // terminal supports colors.
6360
6361 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6362 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6363
6364 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6365 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6366
6367 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6368 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6369
6370 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6371 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6372
6373 SetEnv("TERM", "xterm"); // TERM supports colors.
6374 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6375
6376 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6377 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00006378
vladlosev9f254912010-04-22 11:44:59 +00006379 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6380 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6381
6382 SetEnv("TERM", "screen"); // TERM supports colors.
6383 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6384
zhanyong.wana8a582f2009-07-13 19:25:02 +00006385 SetEnv("TERM", "linux"); // TERM supports colors.
6386 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
vladlosev9f254912010-04-22 11:44:59 +00006387
6388 SetEnv("TERM", "cygwin"); // TERM supports colors.
6389 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00006390#endif // GTEST_OS_WINDOWS
6391}
6392
shiqian21d43d12009-01-08 01:10:31 +00006393// Verifies that StaticAssertTypeEq works in a namespace scope.
6394
6395static bool dummy1 = StaticAssertTypeEq<bool, bool>();
6396static bool dummy2 = StaticAssertTypeEq<const int, const int>();
6397
6398// Verifies that StaticAssertTypeEq works in a class.
6399
6400template <typename T>
6401class StaticAssertTypeEqTestHelper {
6402 public:
6403 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6404};
6405
6406TEST(StaticAssertTypeEqTest, WorksInClass) {
6407 StaticAssertTypeEqTestHelper<bool>();
6408}
6409
6410// Verifies that StaticAssertTypeEq works inside a function.
6411
6412typedef int IntAlias;
6413
6414TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6415 StaticAssertTypeEq<int, IntAlias>();
6416 StaticAssertTypeEq<int*, IntAlias*>();
6417}
6418
vladlosevf904a612008-11-20 01:40:35 +00006419TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6420 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6421
6422 // We don't have a stack walker in Google Test yet.
6423 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6424 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6425}
zhanyong.wan1b171102009-04-07 21:03:22 +00006426
6427TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6428 EXPECT_FALSE(HasNonfatalFailure());
6429}
6430
6431static void FailFatally() { FAIL(); }
6432
6433TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6434 FailFatally();
6435 const bool has_nonfatal_failure = HasNonfatalFailure();
6436 ClearCurrentTestPartResults();
6437 EXPECT_FALSE(has_nonfatal_failure);
6438}
6439
6440TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6441 ADD_FAILURE();
6442 const bool has_nonfatal_failure = HasNonfatalFailure();
6443 ClearCurrentTestPartResults();
6444 EXPECT_TRUE(has_nonfatal_failure);
6445}
6446
6447TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6448 FailFatally();
6449 ADD_FAILURE();
6450 const bool has_nonfatal_failure = HasNonfatalFailure();
6451 ClearCurrentTestPartResults();
6452 EXPECT_TRUE(has_nonfatal_failure);
6453}
6454
6455// A wrapper for calling HasNonfatalFailure outside of a test body.
6456static bool HasNonfatalFailureHelper() {
6457 return testing::Test::HasNonfatalFailure();
6458}
6459
6460TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6461 EXPECT_FALSE(HasNonfatalFailureHelper());
6462}
6463
6464TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6465 ADD_FAILURE();
6466 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6467 ClearCurrentTestPartResults();
6468 EXPECT_TRUE(has_nonfatal_failure);
6469}
6470
6471TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6472 EXPECT_FALSE(HasFailure());
6473}
6474
6475TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6476 FailFatally();
6477 const bool has_failure = HasFailure();
6478 ClearCurrentTestPartResults();
6479 EXPECT_TRUE(has_failure);
6480}
6481
6482TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6483 ADD_FAILURE();
6484 const bool has_failure = HasFailure();
6485 ClearCurrentTestPartResults();
6486 EXPECT_TRUE(has_failure);
6487}
6488
6489TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6490 FailFatally();
6491 ADD_FAILURE();
6492 const bool has_failure = HasFailure();
6493 ClearCurrentTestPartResults();
6494 EXPECT_TRUE(has_failure);
6495}
6496
6497// A wrapper for calling HasFailure outside of a test body.
6498static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6499
6500TEST(HasFailureTest, WorksOutsideOfTestBody) {
6501 EXPECT_FALSE(HasFailureHelper());
6502}
6503
6504TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6505 ADD_FAILURE();
6506 const bool has_failure = HasFailureHelper();
6507 ClearCurrentTestPartResults();
6508 EXPECT_TRUE(has_failure);
6509}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006510
6511class TestListener : public EmptyTestEventListener {
6512 public:
6513 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6514 TestListener(int* on_start_counter, bool* is_destroyed)
6515 : on_start_counter_(on_start_counter),
6516 is_destroyed_(is_destroyed) {}
6517
6518 virtual ~TestListener() {
6519 if (is_destroyed_)
6520 *is_destroyed_ = true;
6521 }
6522
6523 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006524 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006525 if (on_start_counter_ != NULL)
6526 (*on_start_counter_)++;
6527 }
6528
6529 private:
6530 int* on_start_counter_;
6531 bool* is_destroyed_;
6532};
6533
6534// Tests the constructor.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006535TEST(TestEventListenersTest, ConstructionWorks) {
6536 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006537
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006538 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006539 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6540 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6541}
6542
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006543// Tests that the TestEventListeners destructor deletes all the listeners it
zhanyong.wanf39160b2009-09-04 18:30:25 +00006544// owns.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006545TEST(TestEventListenersTest, DestructionWorks) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006546 bool default_result_printer_is_destroyed = false;
6547 bool default_xml_printer_is_destroyed = false;
6548 bool extra_listener_is_destroyed = false;
6549 TestListener* default_result_printer = new TestListener(
6550 NULL, &default_result_printer_is_destroyed);
6551 TestListener* default_xml_printer = new TestListener(
6552 NULL, &default_xml_printer_is_destroyed);
6553 TestListener* extra_listener = new TestListener(
6554 NULL, &extra_listener_is_destroyed);
6555
6556 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006557 TestEventListeners listeners;
6558 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6559 default_result_printer);
6560 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6561 default_xml_printer);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006562 listeners.Append(extra_listener);
6563 }
6564 EXPECT_TRUE(default_result_printer_is_destroyed);
6565 EXPECT_TRUE(default_xml_printer_is_destroyed);
6566 EXPECT_TRUE(extra_listener_is_destroyed);
6567}
6568
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006569// Tests that a listener Append'ed to a TestEventListeners list starts
zhanyong.wanf39160b2009-09-04 18:30:25 +00006570// receiving events.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006571TEST(TestEventListenersTest, Append) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006572 int on_start_counter = 0;
6573 bool is_destroyed = false;
6574 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6575 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006576 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006577 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006578 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006579 *UnitTest::GetInstance());
6580 EXPECT_EQ(1, on_start_counter);
6581 }
6582 EXPECT_TRUE(is_destroyed);
6583}
6584
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006585// Tests that listeners receive events in the order they were appended to
6586// the list, except for *End requests, which must be received in the reverse
6587// order.
zhanyong.wanf39160b2009-09-04 18:30:25 +00006588class SequenceTestingListener : public EmptyTestEventListener {
6589 public:
zhanyong.wan93d13a82010-02-25 01:09:07 +00006590 SequenceTestingListener(std::vector<String>* vector, const char* id)
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006591 : vector_(vector), id_(id) {}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006592
6593 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006594 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006595 vector_->push_back(GetEventDescription("OnTestProgramStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006596 }
6597
6598 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006599 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006600 }
6601
6602 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
6603 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006604 vector_->push_back(GetEventDescription("OnTestIterationStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006605 }
6606
6607 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6608 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006609 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
zhanyong.wanf39160b2009-09-04 18:30:25 +00006610 }
6611
6612 private:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006613 String GetEventDescription(const char* method) {
6614 Message message;
6615 message << id_ << "." << method;
6616 return message.GetString();
6617 }
6618
zhanyong.wan93d13a82010-02-25 01:09:07 +00006619 std::vector<String>* vector_;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006620 const char* const id_;
zhanyong.wand586f9f2009-09-18 16:35:15 +00006621
6622 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006623};
6624
6625TEST(EventListenerTest, AppendKeepsOrder) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006626 std::vector<String> vec;
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006627 TestEventListeners listeners;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006628 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6629 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6630 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6631
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006632 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006633 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006634 ASSERT_EQ(3U, vec.size());
6635 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6636 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6637 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006638
zhanyong.wan93d13a82010-02-25 01:09:07 +00006639 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006640 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006641 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006642 ASSERT_EQ(3U, vec.size());
6643 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6644 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6645 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006646
zhanyong.wan93d13a82010-02-25 01:09:07 +00006647 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006648 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006649 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006650 ASSERT_EQ(3U, vec.size());
6651 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6652 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6653 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006654
zhanyong.wan93d13a82010-02-25 01:09:07 +00006655 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006656 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006657 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006658 ASSERT_EQ(3U, vec.size());
6659 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6660 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6661 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
zhanyong.wanf39160b2009-09-04 18:30:25 +00006662}
6663
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006664// Tests that a listener removed from a TestEventListeners list stops receiving
zhanyong.wanf39160b2009-09-04 18:30:25 +00006665// events and is not deleted when the list is destroyed.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006666TEST(TestEventListenersTest, Release) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006667 int on_start_counter = 0;
6668 bool is_destroyed = false;
6669 // Although Append passes the ownership of this object to the list,
6670 // the following calls release it, and we need to delete it before the
6671 // test ends.
6672 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6673 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006674 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006675 listeners.Append(listener);
6676 EXPECT_EQ(listener, listeners.Release(listener));
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006677 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006678 *UnitTest::GetInstance());
6679 EXPECT_TRUE(listeners.Release(listener) == NULL);
6680 }
6681 EXPECT_EQ(0, on_start_counter);
6682 EXPECT_FALSE(is_destroyed);
6683 delete listener;
6684}
6685
6686// Tests that no events are forwarded when event forwarding is disabled.
6687TEST(EventListenerTest, SuppressEventForwarding) {
6688 int on_start_counter = 0;
6689 TestListener* listener = new TestListener(&on_start_counter, NULL);
6690
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006691 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006692 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006693 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6694 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6695 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6696 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006697 *UnitTest::GetInstance());
6698 EXPECT_EQ(0, on_start_counter);
6699}
6700
zhanyong.wanf39160b2009-09-04 18:30:25 +00006701// Tests that events generated by Google Test are not forwarded in
6702// death test subprocesses.
6703TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
zhanyong.wand541f022009-09-11 06:59:42 +00006704 EXPECT_DEATH_IF_SUPPORTED({
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006705 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006706 *GetUnitTestImpl()->listeners())) << "expected failure";},
6707 "expected failure");
6708}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006709
6710// Tests that a listener installed via SetDefaultResultPrinter() starts
6711// receiving events and is returned via default_result_printer() and that
6712// the previous default_result_printer is removed from the list and deleted.
6713TEST(EventListenerTest, default_result_printer) {
6714 int on_start_counter = 0;
6715 bool is_destroyed = false;
6716 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6717
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006718 TestEventListeners listeners;
6719 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006720
6721 EXPECT_EQ(listener, listeners.default_result_printer());
6722
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006723 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006724 *UnitTest::GetInstance());
6725
6726 EXPECT_EQ(1, on_start_counter);
6727
6728 // Replacing default_result_printer with something else should remove it
6729 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006730 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006731
6732 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6733 EXPECT_TRUE(is_destroyed);
6734
6735 // After broadcasting an event the counter is still the same, indicating
6736 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006737 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006738 *UnitTest::GetInstance());
6739 EXPECT_EQ(1, on_start_counter);
6740}
6741
6742// Tests that the default_result_printer listener stops receiving events
6743// when removed via Release and that is not owned by the list anymore.
6744TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6745 int on_start_counter = 0;
6746 bool is_destroyed = false;
6747 // Although Append passes the ownership of this object to the list,
6748 // the following calls release it, and we need to delete it before the
6749 // test ends.
6750 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6751 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006752 TestEventListeners listeners;
6753 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006754
6755 EXPECT_EQ(listener, listeners.Release(listener));
6756 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6757 EXPECT_FALSE(is_destroyed);
6758
6759 // Broadcasting events now should not affect default_result_printer.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006760 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006761 *UnitTest::GetInstance());
6762 EXPECT_EQ(0, on_start_counter);
6763 }
6764 // Destroying the list should not affect the listener now, too.
6765 EXPECT_FALSE(is_destroyed);
6766 delete listener;
6767}
6768
6769// Tests that a listener installed via SetDefaultXmlGenerator() starts
6770// receiving events and is returned via default_xml_generator() and that
6771// the previous default_xml_generator is removed from the list and deleted.
6772TEST(EventListenerTest, default_xml_generator) {
6773 int on_start_counter = 0;
6774 bool is_destroyed = false;
6775 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6776
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006777 TestEventListeners listeners;
6778 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006779
6780 EXPECT_EQ(listener, listeners.default_xml_generator());
6781
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006782 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006783 *UnitTest::GetInstance());
6784
6785 EXPECT_EQ(1, on_start_counter);
6786
6787 // Replacing default_xml_generator with something else should remove it
6788 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006789 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006790
6791 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6792 EXPECT_TRUE(is_destroyed);
6793
6794 // After broadcasting an event the counter is still the same, indicating
6795 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006796 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006797 *UnitTest::GetInstance());
6798 EXPECT_EQ(1, on_start_counter);
6799}
6800
6801// Tests that the default_xml_generator listener stops receiving events
6802// when removed via Release and that is not owned by the list anymore.
6803TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6804 int on_start_counter = 0;
6805 bool is_destroyed = false;
6806 // Although Append passes the ownership of this object to the list,
6807 // the following calls release it, and we need to delete it before the
6808 // test ends.
6809 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6810 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006811 TestEventListeners listeners;
6812 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006813
6814 EXPECT_EQ(listener, listeners.Release(listener));
6815 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6816 EXPECT_FALSE(is_destroyed);
6817
6818 // Broadcasting events now should not affect default_xml_generator.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006819 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006820 *UnitTest::GetInstance());
6821 EXPECT_EQ(0, on_start_counter);
6822 }
6823 // Destroying the list should not affect the listener now, too.
6824 EXPECT_FALSE(is_destroyed);
6825 delete listener;
6826}
zhanyong.wan1618bb42010-04-13 04:40:32 +00006827
6828// Sanity tests to ensure that the alternative, verbose spellings of
6829// some of the macros work. We don't test them thoroughly as that
6830// would be quite involved. Since their implementations are
6831// straightforward, and they are rarely used, we'll just rely on the
6832// users to tell us when they are broken.
6833GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
6834 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
6835
6836 // GTEST_FAIL is the same as FAIL.
6837 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
6838 "An expected failure");
6839}
zhanyong.wan678f92b2010-05-10 17:11:58 +00006840
6841// Tests for internal utilities necessary for implementation of the universal
6842// printing.
6843// TODO(vladl@google.com): Find a better home for them.
6844
6845class ConversionHelperBase {};
6846class ConversionHelperDerived : public ConversionHelperBase {};
6847
6848// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
6849TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
6850 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
6851 const_true);
6852 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
6853}
6854
6855// Tests that IsAProtocolMessage<T>::value is true when T is
6856// ProtocolMessage or a sub-class of it.
6857TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
6858 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
6859 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
6860#if GTEST_HAS_PROTOBUF_
6861 EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value);
6862#endif // GTEST_HAS_PROTOBUF_
6863}
6864
6865// Tests that IsAProtocolMessage<T>::value is false when T is neither
6866// ProtocolMessage nor a sub-class of it.
6867TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
6868 EXPECT_FALSE(IsAProtocolMessage<int>::value);
6869 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
6870}
6871
6872// Tests that CompileAssertTypesEqual compiles when the type arguments are
6873// equal.
6874TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
6875 CompileAssertTypesEqual<void, void>();
6876 CompileAssertTypesEqual<int*, int*>();
6877}
6878
6879// Tests that RemoveReference does not affect non-reference types.
6880TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
6881 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
6882 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
6883}
6884
6885// Tests that RemoveReference removes reference from reference types.
6886TEST(RemoveReferenceTest, RemovesReference) {
6887 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
6888 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
6889}
6890
6891// Tests GTEST_REMOVE_REFERENCE_.
6892
6893template <typename T1, typename T2>
6894void TestGTestRemoveReference() {
6895 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
6896}
6897
6898TEST(RemoveReferenceTest, MacroVersion) {
6899 TestGTestRemoveReference<int, int>();
6900 TestGTestRemoveReference<const char, const char&>();
6901}
6902
6903
6904// Tests that RemoveConst does not affect non-const types.
6905TEST(RemoveConstTest, DoesNotAffectNonConstType) {
6906 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
6907 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
6908}
6909
6910// Tests that RemoveConst removes const from const types.
6911TEST(RemoveConstTest, RemovesConst) {
6912 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
6913 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
6914 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
6915}
6916
6917// Tests GTEST_REMOVE_CONST_.
6918
6919template <typename T1, typename T2>
6920void TestGTestRemoveConst() {
6921 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
6922}
6923
6924TEST(RemoveConstTest, MacroVersion) {
6925 TestGTestRemoveConst<int, int>();
6926 TestGTestRemoveConst<double&, double&>();
6927 TestGTestRemoveConst<char, const char>();
6928}
6929
zhanyong.wanc3ad6902010-05-17 19:31:00 +00006930// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
6931
6932template <typename T1, typename T2>
6933void TestGTestRemoveReferenceAndConst() {
6934 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
6935}
6936
6937TEST(RemoveReferenceToConstTest, Works) {
6938 TestGTestRemoveReferenceAndConst<int, int>();
6939 TestGTestRemoveReferenceAndConst<double, double&>();
6940 TestGTestRemoveReferenceAndConst<char, const char>();
6941 TestGTestRemoveReferenceAndConst<char, const char&>();
6942 TestGTestRemoveReferenceAndConst<const char*, const char*>();
6943}
6944
zhanyong.wan678f92b2010-05-10 17:11:58 +00006945// Tests that AddReference does not affect reference types.
6946TEST(AddReferenceTest, DoesNotAffectReferenceType) {
6947 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
6948 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
6949}
6950
6951// Tests that AddReference adds reference to non-reference types.
6952TEST(AddReferenceTest, AddsReference) {
6953 CompileAssertTypesEqual<int&, AddReference<int>::type>();
6954 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
6955}
6956
6957// Tests GTEST_ADD_REFERENCE_.
6958
6959template <typename T1, typename T2>
6960void TestGTestAddReference() {
6961 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
6962}
6963
6964TEST(AddReferenceTest, MacroVersion) {
6965 TestGTestAddReference<int&, int>();
6966 TestGTestAddReference<const char&, const char&>();
6967}
6968
6969// Tests GTEST_REFERENCE_TO_CONST_.
6970
6971template <typename T1, typename T2>
6972void TestGTestReferenceToConst() {
6973 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
6974}
6975
6976TEST(GTestReferenceToConstTest, Works) {
6977 TestGTestReferenceToConst<const char&, char>();
6978 TestGTestReferenceToConst<const int&, const int>();
6979 TestGTestReferenceToConst<const double&, double>();
6980 TestGTestReferenceToConst<const String&, const String&>();
6981}
6982
6983// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
6984TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
6985 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
6986 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
6987 const_false);
6988}
6989
6990// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
6991// be implicitly converted to T2.
6992TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
6993 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
6994 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
6995 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
6996 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
6997 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
6998 const ConversionHelperBase&>::value));
6999 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7000 ConversionHelperBase>::value));
7001}
7002
7003// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7004// cannot be implicitly converted to T2.
7005TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7006 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7007 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7008 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7009 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7010 ConversionHelperDerived&>::value));
7011}
7012
7013// Tests IsContainerTest.
7014
7015class NonContainer {};
7016
7017TEST(IsContainerTestTest, WorksForNonContainer) {
7018 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7019 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7020 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7021}
7022
7023TEST(IsContainerTestTest, WorksForContainer) {
7024 EXPECT_EQ(sizeof(IsContainer),
7025 sizeof(IsContainerTest<std::vector<bool> >(0)));
7026 EXPECT_EQ(sizeof(IsContainer),
7027 sizeof(IsContainerTest<std::map<int, double> >(0)));
7028}
7029
7030// Tests ArrayEq().
7031
7032TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7033 EXPECT_TRUE(ArrayEq(5, 5L));
7034 EXPECT_FALSE(ArrayEq('a', 0));
7035}
7036
7037TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7038 const int a[] = { 0, 1 };
7039 long b[] = { 0, 1 };
7040 EXPECT_TRUE(ArrayEq(a, b));
7041 EXPECT_TRUE(ArrayEq(a, 2, b));
7042
7043 b[0] = 2;
7044 EXPECT_FALSE(ArrayEq(a, b));
7045 EXPECT_FALSE(ArrayEq(a, 1, b));
7046}
7047
7048TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7049 const char a[][3] = { "hi", "lo" };
7050 const char b[][3] = { "hi", "lo" };
7051 const char c[][3] = { "hi", "li" };
7052
7053 EXPECT_TRUE(ArrayEq(a, b));
7054 EXPECT_TRUE(ArrayEq(a, 2, b));
7055
7056 EXPECT_FALSE(ArrayEq(a, c));
7057 EXPECT_FALSE(ArrayEq(a, 2, c));
7058}
7059
7060// Tests ArrayAwareFind().
7061
7062TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7063 const char a[] = "hello";
7064 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7065 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7066}
7067
7068TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7069 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7070 const int b[2] = { 2, 3 };
7071 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7072
7073 const int c[2] = { 6, 7 };
7074 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7075}
7076
7077// Tests CopyArray().
7078
7079TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7080 int n = 0;
7081 CopyArray('a', &n);
7082 EXPECT_EQ('a', n);
7083}
7084
7085TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7086 const char a[3] = "hi";
7087 int b[3];
7088 CopyArray(a, &b);
7089 EXPECT_TRUE(ArrayEq(a, b));
7090
7091 int c[3];
7092 CopyArray(a, 3, c);
7093 EXPECT_TRUE(ArrayEq(a, c));
7094}
7095
7096TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7097 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7098 int b[2][3];
7099 CopyArray(a, &b);
7100 EXPECT_TRUE(ArrayEq(a, b));
7101
7102 int c[2][3];
7103 CopyArray(a, 2, c);
7104 EXPECT_TRUE(ArrayEq(a, c));
7105}
7106
7107// Tests NativeArray.
7108
7109TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7110 const int a[3] = { 0, 1, 2 };
7111 NativeArray<int> na(a, 3, kReference);
7112 EXPECT_EQ(3U, na.size());
7113 EXPECT_EQ(a, na.begin());
7114}
7115
7116TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7117 typedef int Array[2];
7118 Array* a = new Array[1];
7119 (*a)[0] = 0;
7120 (*a)[1] = 1;
7121 NativeArray<int> na(*a, 2, kCopy);
7122 EXPECT_NE(*a, na.begin());
7123 delete[] a;
7124 EXPECT_EQ(0, na.begin()[0]);
7125 EXPECT_EQ(1, na.begin()[1]);
7126
7127 // We rely on the heap checker to verify that na deletes the copy of
7128 // array.
7129}
7130
7131TEST(NativeArrayTest, TypeMembersAreCorrect) {
7132 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7133 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7134
7135 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7136 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7137}
7138
7139TEST(NativeArrayTest, MethodsWork) {
7140 const int a[3] = { 0, 1, 2 };
7141 NativeArray<int> na(a, 3, kCopy);
7142 ASSERT_EQ(3U, na.size());
7143 EXPECT_EQ(3, na.end() - na.begin());
7144
7145 NativeArray<int>::const_iterator it = na.begin();
7146 EXPECT_EQ(0, *it);
7147 ++it;
7148 EXPECT_EQ(1, *it);
7149 it++;
7150 EXPECT_EQ(2, *it);
7151 ++it;
7152 EXPECT_EQ(na.end(), it);
7153
7154 EXPECT_TRUE(na == na);
7155
7156 NativeArray<int> na2(a, 3, kReference);
7157 EXPECT_TRUE(na == na2);
7158
7159 const int b1[3] = { 0, 1, 1 };
7160 const int b2[4] = { 0, 1, 2, 3 };
7161 EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
7162 EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
7163}
7164
7165TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7166 const char a[2][3] = { "hi", "lo" };
7167 NativeArray<char[3]> na(a, 2, kReference);
7168 ASSERT_EQ(2U, na.size());
7169 EXPECT_EQ(a, na.begin());
7170}
zhanyong.wan9748de02010-06-08 22:51:46 +00007171
7172// Tests SkipPrefix().
7173
7174TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7175 const char* const str = "hello";
7176
7177 const char* p = str;
7178 EXPECT_TRUE(SkipPrefix("", &p));
7179 EXPECT_EQ(str, p);
7180
7181 p = str;
7182 EXPECT_TRUE(SkipPrefix("hell", &p));
7183 EXPECT_EQ(str + 4, p);
7184}
7185
7186TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7187 const char* const str = "world";
7188
7189 const char* p = str;
7190 EXPECT_FALSE(SkipPrefix("W", &p));
7191 EXPECT_EQ(str, p);
7192
7193 p = str;
7194 EXPECT_FALSE(SkipPrefix("world!", &p));
7195 EXPECT_EQ(str, p);
7196}