blob: 07e60f51b0a924c548d481dfe40f8f8fe916040c [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.wan0ebc16a2009-02-02 06:37:03 +000036
37// Verifies that the command line flag variables can be accessed
38// in code once <gtest/gtest.h> has been #included.
39// Do not move it after other #includes.
40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000049 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000050 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000052 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000053 || testing::GTEST_FLAG(stack_trace_depth) > 0
54 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000055 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
56}
57
shiqian4b6829f2008-07-03 22:38:12 +000058#include <gtest/gtest-spi.h>
59
60// Indicates that this translation unit is part of Google Test's
61// implementation. It must come before gtest-internal-inl.h is
62// included, or there will be a compiler error. This trick is to
63// prevent a user from accidentally including gtest-internal-inl.h in
64// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000065#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000066#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000067#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000068
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +000069#include <limits.h> // For INT_MAX.
shiqian4b6829f2008-07-03 22:38:12 +000070#include <stdlib.h>
zhanyong.wan98efcc42009-04-28 00:28:09 +000071#include <time.h>
shiqian4b6829f2008-07-03 22:38:12 +000072
shiqiane44602e2008-10-11 07:20:02 +000073#if GTEST_HAS_PTHREAD
74#include <pthread.h>
75#endif // GTEST_HAS_PTHREAD
76
zhanyong.wan98efcc42009-04-28 00:28:09 +000077#ifdef __BORLANDC__
78#include <map>
79#endif
80
shiqian4b6829f2008-07-03 22:38:12 +000081namespace testing {
82namespace internal {
shiqianf0e809a2008-09-26 16:08:30 +000083const char* FormatTimeInMillisAsSeconds(TimeInMillis ms);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000084
shiqian4b6829f2008-07-03 22:38:12 +000085bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000086
zhanyong.wanf39160b2009-09-04 18:30:25 +000087// Provides access to otherwise private parts of the EventListeners class
88// that are needed to test it.
89class EventListenersAccessor {
90 public:
91 static UnitTestEventListenerInterface* GetRepeater(
92 EventListeners* listeners) { return listeners->repeater(); }
93
94 static void SetDefaultResultPrinter(
95 EventListeners* listeners,
96 UnitTestEventListenerInterface* listener) {
97 listeners->SetDefaultResultPrinter(listener);
98 }
99 static void SetDefaultXmlGenerator(EventListeners* listeners,
100 UnitTestEventListenerInterface* listener) {
101 listeners->SetDefaultXmlGenerator(listener);
102 }
103
104 static bool EventForwardingEnabled(const EventListeners& listeners) {
105 return listeners.EventForwardingEnabled();
106 }
107
108 static void SuppressEventForwarding(EventListeners* listeners) {
109 listeners->SuppressEventForwarding();
110 }
111};
112
shiqian4b6829f2008-07-03 22:38:12 +0000113} // namespace internal
114} // namespace testing
115
shiqianf0e809a2008-09-26 16:08:30 +0000116using testing::internal::FormatTimeInMillisAsSeconds;
shiqian4b6829f2008-07-03 22:38:12 +0000117using testing::internal::ParseInt32Flag;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000118using testing::internal::EventListenersAccessor;
shiqian4b6829f2008-07-03 22:38:12 +0000119
120namespace testing {
121
shiqiane44602e2008-10-11 07:20:02 +0000122GTEST_DECLARE_string_(output);
123GTEST_DECLARE_string_(color);
shiqian4b6829f2008-07-03 22:38:12 +0000124
125namespace internal {
126bool ShouldUseColor(bool stdout_is_tty);
127} // namespace internal
128} // namespace testing
129
shiqian760af5c2008-08-06 21:43:15 +0000130using testing::AssertionFailure;
131using testing::AssertionResult;
132using testing::AssertionSuccess;
133using testing::DoubleLE;
134using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000135using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000136using testing::GTEST_FLAG(break_on_failure);
137using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000138using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000139using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000140using testing::GTEST_FLAG(filter);
141using testing::GTEST_FLAG(list_tests);
142using testing::GTEST_FLAG(output);
143using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000144using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000145using testing::GTEST_FLAG(repeat);
146using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000147using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000148using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000149using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000150using testing::IsNotSubstring;
151using testing::IsSubstring;
152using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000153using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000154using testing::StaticAssertTypeEq;
shiqian760af5c2008-08-06 21:43:15 +0000155using testing::TPRT_FATAL_FAILURE;
156using testing::TPRT_NONFATAL_FAILURE;
157using testing::TPRT_SUCCESS;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000158using testing::Test;
159using testing::TestPartResult;
160using testing::TestPartResultArray;
shiqian4b6829f2008-07-03 22:38:12 +0000161using testing::UnitTest;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000162using testing::internal::kMaxRandomSeed;
shiqianfe6a9a42008-11-24 20:13:22 +0000163using testing::internal::kTestTypeIdInGoogleTest;
shiqian4b6829f2008-07-03 22:38:12 +0000164using testing::internal::AppendUserMessage;
vladloseve006e682008-08-25 23:11:54 +0000165using testing::internal::CodePointToUtf8;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000166using testing::internal::EmptyTestEventListener;
shiqian4b6829f2008-07-03 22:38:12 +0000167using testing::internal::EqFailure;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000168using testing::internal::EventListeners;
shiqian760af5c2008-08-06 21:43:15 +0000169using testing::internal::FloatingPoint;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000170using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000171using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000172using testing::internal::GetNextRandomSeed;
173using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000174using testing::internal::GetTestTypeId;
175using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000176using testing::internal::GetUnitTestImpl;
shiqian4b6829f2008-07-03 22:38:12 +0000177using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000178using testing::internal::Int32FromEnvOrDie;
zhanyong.wan905074c2009-02-09 18:05:21 +0000179using testing::internal::ShouldRunTestOnShard;
180using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000181using testing::internal::ShouldUseColor;
182using testing::internal::StreamableToString;
183using testing::internal::String;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000184using testing::internal::TestCase;
shiqian4b6829f2008-07-03 22:38:12 +0000185using testing::internal::TestProperty;
186using testing::internal::TestResult;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000187using testing::internal::TestResultAccessor;
shiqiane44602e2008-10-11 07:20:02 +0000188using testing::internal::ThreadLocal;
zhanyong.wana8a582f2009-07-13 19:25:02 +0000189using testing::internal::Vector;
vladloseve006e682008-08-25 23:11:54 +0000190using testing::internal::WideStringToUtf8;
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
194// This line tests that we can define tests in an unnamed namespace.
195namespace {
196
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000197TEST(GetRandomSeedFromFlagTest, HandlesZero) {
198 const int seed = GetRandomSeedFromFlag(0);
199 EXPECT_LE(1, seed);
200 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
201}
202
203TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
204 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
205 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
206 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
207 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
208 GetRandomSeedFromFlag(kMaxRandomSeed));
209}
210
211TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
212 const int seed1 = GetRandomSeedFromFlag(-1);
213 EXPECT_LE(1, seed1);
214 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
215
216 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
217 EXPECT_LE(1, seed2);
218 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
219}
220
221TEST(GetNextRandomSeedTest, WorksForValidInput) {
222 EXPECT_EQ(2, GetNextRandomSeed(1));
223 EXPECT_EQ(3, GetNextRandomSeed(2));
224 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
225 GetNextRandomSeed(kMaxRandomSeed - 1));
226 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
227
228 // We deliberately don't test GetNextRandomSeed() with invalid
229 // inputs, as that requires death tests, which are expensive. This
230 // is fine as GetNextRandomSeed() is internal and has a
231 // straightforward definition.
232}
233
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000234static void ClearCurrentTestPartResults() {
235 TestResultAccessor::ClearTestPartResults(
236 GetUnitTestImpl()->current_test_result());
237}
238
shiqianfe6a9a42008-11-24 20:13:22 +0000239// Tests GetTypeId.
240
241TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
242 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
243 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
244}
245
246class SubClassOfTest : public Test {};
247class AnotherSubClassOfTest : public Test {};
248
249TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
250 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
251 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
252 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
253 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
254 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
255 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
256}
257
258// Verifies that GetTestTypeId() returns the same value, no matter it
259// is called from inside Google Test or outside of it.
260TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
261 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
262}
263
shiqianf0e809a2008-09-26 16:08:30 +0000264// Tests FormatTimeInMillisAsSeconds().
265
266TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
267 EXPECT_STREQ("0", FormatTimeInMillisAsSeconds(0));
268}
269
270TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
271 EXPECT_STREQ("0.003", FormatTimeInMillisAsSeconds(3));
272 EXPECT_STREQ("0.01", FormatTimeInMillisAsSeconds(10));
273 EXPECT_STREQ("0.2", FormatTimeInMillisAsSeconds(200));
274 EXPECT_STREQ("1.2", FormatTimeInMillisAsSeconds(1200));
275 EXPECT_STREQ("3", FormatTimeInMillisAsSeconds(3000));
276}
277
278TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
279 EXPECT_STREQ("-0.003", FormatTimeInMillisAsSeconds(-3));
280 EXPECT_STREQ("-0.01", FormatTimeInMillisAsSeconds(-10));
281 EXPECT_STREQ("-0.2", FormatTimeInMillisAsSeconds(-200));
282 EXPECT_STREQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
283 EXPECT_STREQ("-3", FormatTimeInMillisAsSeconds(-3000));
284}
285
zhanyong.wan4cd62602009-02-23 23:21:55 +0000286#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +0000287// NULL testing does not work with Symbian compilers.
288
zhanyong.wan98efcc42009-04-28 00:28:09 +0000289#ifdef __BORLANDC__
290// Silences warnings: "Condition is always true", "Unreachable code"
291#pragma option push -w-ccc -w-rch
292#endif
293
shiqiane44602e2008-10-11 07:20:02 +0000294// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000295// pointer literal.
296TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000297 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
298 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000299 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
300 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
301 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000302#ifndef __BORLANDC__
303 // Some compilers may fail to detect some null pointer literals;
304 // as long as users of the framework don't use such literals, this
305 // is harmless.
306 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
shiqiane44602e2008-10-11 07:20:02 +0000307 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000308#endif
shiqian4b6829f2008-07-03 22:38:12 +0000309}
310
shiqiane44602e2008-10-11 07:20:02 +0000311// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
shiqian4b6829f2008-07-03 22:38:12 +0000312// pointer literal.
313TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000314 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
315 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
316 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
317 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
shiqian4b6829f2008-07-03 22:38:12 +0000318}
319
zhanyong.wan98efcc42009-04-28 00:28:09 +0000320#ifdef __BORLANDC__
321// Restores warnings after previous "#pragma option push" supressed them
322#pragma option pop
323#endif
324
zhanyong.wan4cd62602009-02-23 23:21:55 +0000325#endif // !GTEST_OS_SYMBIAN
vladloseve006e682008-08-25 23:11:54 +0000326//
327// Tests CodePointToUtf8().
shiqian4b6829f2008-07-03 22:38:12 +0000328
329// Tests that the NUL character L'\0' is encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000330TEST(CodePointToUtf8Test, CanEncodeNul) {
331 char buffer[32];
332 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000333}
334
335// Tests that ASCII characters are encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000336TEST(CodePointToUtf8Test, CanEncodeAscii) {
337 char buffer[32];
338 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
339 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
340 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
341 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000342}
343
344// Tests that Unicode code-points that have 8 to 11 bits are encoded
345// as 110xxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000346TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
347 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000348 // 000 1101 0011 => 110-00011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000349 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000350
351 // 101 0111 0110 => 110-10101 10-110110
vladloseve006e682008-08-25 23:11:54 +0000352 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000353}
354
355// Tests that Unicode code-points that have 12 to 16 bits are encoded
356// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000357TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
358 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000359 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000360 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000361
362 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
vladloseve006e682008-08-25 23:11:54 +0000363 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000364}
365
zhanyong.wan4cd62602009-02-23 23:21:55 +0000366#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000367// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000368// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000369// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000370
371// Tests that Unicode code-points that have 17 to 21 bits are encoded
372// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000373TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
374 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000375 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000376 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000377
vladloseve006e682008-08-25 23:11:54 +0000378 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
379 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
380
381 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
382 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000383}
384
385// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000386TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
387 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000388 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
vladloseve006e682008-08-25 23:11:54 +0000389 CodePointToUtf8(L'\x1234ABCD', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000390}
391
zhanyong.wan4cd62602009-02-23 23:21:55 +0000392#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000393
394// Tests WideStringToUtf8().
395
396// Tests that the NUL character L'\0' is encoded correctly.
397TEST(WideStringToUtf8Test, CanEncodeNul) {
398 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
399 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
400}
401
402// Tests that ASCII strings are encoded correctly.
403TEST(WideStringToUtf8Test, CanEncodeAscii) {
404 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
405 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
406 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
407 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
408}
409
410// Tests that Unicode code-points that have 8 to 11 bits are encoded
411// as 110xxxxx 10xxxxxx.
412TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
413 // 000 1101 0011 => 110-00011 10-010011
414 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
415 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
416
417 // 101 0111 0110 => 110-10101 10-110110
418 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
419 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
420}
421
422// Tests that Unicode code-points that have 12 to 16 bits are encoded
423// as 1110xxxx 10xxxxxx 10xxxxxx.
424TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
425 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
426 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
427 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
428
429 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
430 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
431 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
432}
433
434// Tests that the conversion stops when the function encounters \0 character.
435TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
436 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
437}
438
439// Tests that the conversion stops when the function reaches the limit
440// specified by the 'length' parameter.
441TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
442 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
443}
444
445
zhanyong.wan4cd62602009-02-23 23:21:55 +0000446#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000447// Tests that Unicode code-points that have 17 to 21 bits are encoded
448// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
449// on the systems using UTF-16 encoding.
450TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
451 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
452 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
453 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
454
455 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
456 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
457 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
458}
459
460// Tests that encoding an invalid code-point generates the expected result.
461TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
462 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
463 WideStringToUtf8(L"\xABCDFF", -1).c_str());
464}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000465#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000466// Tests that surrogate pairs are encoded correctly on the systems using
467// UTF-16 encoding in the wide strings.
468TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
469 EXPECT_STREQ("\xF0\x90\x90\x80",
470 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
471}
472
473// Tests that encoding an invalid UTF-16 surrogate pair
474// generates the expected result.
475TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
476 // Leading surrogate is at the end of the string.
477 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
478 // Leading surrogate is not followed by the trailing surrogate.
479 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
480 // Trailing surrogate appearas without a leading surrogate.
481 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
482}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000483#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000484
485// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000486#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000487TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
488 EXPECT_STREQ(
489 "\xF4\x88\x98\xB4"
490 "\xEC\x9D\x8D"
491 "\n"
492 "\xD5\xB6"
493 "\xE0\xA3\x93"
494 "\xF4\x88\x98\xB4",
495 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
496}
497#else
498TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
499 EXPECT_STREQ(
500 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
501 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
502}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000503#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000504
zhanyong.wana8a582f2009-07-13 19:25:02 +0000505// Tests the Vector class template.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000506
zhanyong.wana8a582f2009-07-13 19:25:02 +0000507// Tests Vector::Clear().
508TEST(VectorTest, Clear) {
509 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000510 a.PushBack(1);
511 a.Clear();
512 EXPECT_EQ(0, a.size());
513
514 a.PushBack(2);
515 a.PushBack(3);
516 a.Clear();
517 EXPECT_EQ(0, a.size());
518}
519
zhanyong.wana8a582f2009-07-13 19:25:02 +0000520// Tests Vector::PushBack().
521TEST(VectorTest, PushBack) {
522 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000523 a.PushBack('a');
524 ASSERT_EQ(1, a.size());
525 EXPECT_EQ('a', a.GetElement(0));
526
527 a.PushBack('b');
528 ASSERT_EQ(2, a.size());
529 EXPECT_EQ('a', a.GetElement(0));
530 EXPECT_EQ('b', a.GetElement(1));
531}
shiqian4b6829f2008-07-03 22:38:12 +0000532
zhanyong.wana8a582f2009-07-13 19:25:02 +0000533// Tests Vector::PushFront().
534TEST(VectorTest, PushFront) {
535 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000536 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000537
zhanyong.wana8a582f2009-07-13 19:25:02 +0000538 // Calls PushFront() on an empty Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000539 a.PushFront(1);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000540 ASSERT_EQ(1, a.size());
541 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000542
zhanyong.wana8a582f2009-07-13 19:25:02 +0000543 // Calls PushFront() on a singleton Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000544 a.PushFront(2);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000545 ASSERT_EQ(2, a.size());
546 EXPECT_EQ(2, a.GetElement(0));
547 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000548
zhanyong.wana8a582f2009-07-13 19:25:02 +0000549 // Calls PushFront() on a Vector with more than one elements.
shiqian4b6829f2008-07-03 22:38:12 +0000550 a.PushFront(3);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000551 ASSERT_EQ(3, a.size());
552 EXPECT_EQ(3, a.GetElement(0));
553 EXPECT_EQ(2, a.GetElement(1));
554 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000555}
556
zhanyong.wana8a582f2009-07-13 19:25:02 +0000557// Tests Vector::PopFront().
558TEST(VectorTest, PopFront) {
559 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000560
zhanyong.wana8a582f2009-07-13 19:25:02 +0000561 // Popping on an empty Vector should fail.
shiqian4b6829f2008-07-03 22:38:12 +0000562 EXPECT_FALSE(a.PopFront(NULL));
563
zhanyong.wana8a582f2009-07-13 19:25:02 +0000564 // Popping again on an empty Vector should fail, and the result element
shiqian4b6829f2008-07-03 22:38:12 +0000565 // shouldn't be overwritten.
566 int element = 1;
567 EXPECT_FALSE(a.PopFront(&element));
568 EXPECT_EQ(1, element);
569
570 a.PushFront(2);
571 a.PushFront(3);
572
zhanyong.wana8a582f2009-07-13 19:25:02 +0000573 // PopFront() should pop the element in the front of the Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000574 EXPECT_TRUE(a.PopFront(&element));
575 EXPECT_EQ(3, element);
576
zhanyong.wana8a582f2009-07-13 19:25:02 +0000577 // After popping the last element, the Vector should be empty.
shiqian4b6829f2008-07-03 22:38:12 +0000578 EXPECT_TRUE(a.PopFront(NULL));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000579 EXPECT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000580}
581
zhanyong.wana8a582f2009-07-13 19:25:02 +0000582// Tests inserting at the beginning using Vector::Insert().
583TEST(VectorTest, InsertAtBeginning) {
584 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000585 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000586
zhanyong.wana8a582f2009-07-13 19:25:02 +0000587 // Inserts into an empty Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000588 a.Insert(1, 0);
589 ASSERT_EQ(1, a.size());
590 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000591
zhanyong.wana8a582f2009-07-13 19:25:02 +0000592 // Inserts at the beginning of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000593 a.Insert(2, 0);
594 ASSERT_EQ(2, a.size());
595 EXPECT_EQ(2, a.GetElement(0));
596 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000597
zhanyong.wana8a582f2009-07-13 19:25:02 +0000598 // Inserts at the beginning of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000599 a.Insert(3, 0);
600 ASSERT_EQ(3, a.size());
601 EXPECT_EQ(3, a.GetElement(0));
602 EXPECT_EQ(2, a.GetElement(1));
603 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000604}
605
606// Tests inserting at a location other than the beginning using
zhanyong.wana8a582f2009-07-13 19:25:02 +0000607// Vector::Insert().
608TEST(VectorTest, InsertNotAtBeginning) {
609 // Prepares a singleton Vector.
610 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000611 a.PushBack(1);
612
zhanyong.wana8a582f2009-07-13 19:25:02 +0000613 // Inserts at the end of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000614 a.Insert(2, a.size());
615 ASSERT_EQ(2, a.size());
616 EXPECT_EQ(1, a.GetElement(0));
617 EXPECT_EQ(2, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000618
zhanyong.wana8a582f2009-07-13 19:25:02 +0000619 // Inserts at the end of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000620 a.Insert(3, a.size());
621 ASSERT_EQ(3, a.size());
622 EXPECT_EQ(1, a.GetElement(0));
623 EXPECT_EQ(2, a.GetElement(1));
624 EXPECT_EQ(3, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000625
zhanyong.wana8a582f2009-07-13 19:25:02 +0000626 // Inserts in the middle of a Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000627 a.Insert(4, 1);
628 ASSERT_EQ(4, a.size());
629 EXPECT_EQ(1, a.GetElement(0));
630 EXPECT_EQ(4, a.GetElement(1));
631 EXPECT_EQ(2, a.GetElement(2));
632 EXPECT_EQ(3, a.GetElement(3));
633}
634
zhanyong.wana8a582f2009-07-13 19:25:02 +0000635// Tests Vector::GetElementOr().
636TEST(VectorTest, GetElementOr) {
637 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000638 EXPECT_EQ('x', a.GetElementOr(0, 'x'));
639
640 a.PushBack('a');
641 a.PushBack('b');
642 EXPECT_EQ('a', a.GetElementOr(0, 'x'));
643 EXPECT_EQ('b', a.GetElementOr(1, 'x'));
644 EXPECT_EQ('x', a.GetElementOr(-2, 'x'));
645 EXPECT_EQ('x', a.GetElementOr(2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000646}
647
zhanyong.wana8a582f2009-07-13 19:25:02 +0000648// Tests Vector::Erase().
649TEST(VectorDeathTest, Erase) {
650 Vector<int> a;
651
652 // Tests erasing from an empty vector.
zhanyong.wan535de532009-08-07 06:47:47 +0000653 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000654 a.Erase(0),
655 "Invalid Vector index 0: must be in range \\[0, -1\\]\\.");
656
657 // Tests erasing from a singleton vector.
658 a.PushBack(0);
659
660 a.Erase(0);
661 EXPECT_EQ(0, a.size());
662
663 // Tests Erase parameters beyond the bounds of the vector.
664 Vector<int> a1;
665 a1.PushBack(0);
666 a1.PushBack(1);
667 a1.PushBack(2);
668
zhanyong.wan535de532009-08-07 06:47:47 +0000669 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000670 a1.Erase(3),
671 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +0000672 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000673 a1.Erase(-1),
674 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
675
676 // Tests erasing at the end of the vector.
677 Vector<int> a2;
678 a2.PushBack(0);
679 a2.PushBack(1);
680 a2.PushBack(2);
681
682 a2.Erase(2);
683 ASSERT_EQ(2, a2.size());
684 EXPECT_EQ(0, a2.GetElement(0));
685 EXPECT_EQ(1, a2.GetElement(1));
686
687 // Tests erasing in the middle of the vector.
688 Vector<int> a3;
689 a3.PushBack(0);
690 a3.PushBack(1);
691 a3.PushBack(2);
692
693 a3.Erase(1);
694 ASSERT_EQ(2, a3.size());
695 EXPECT_EQ(0, a3.GetElement(0));
696 EXPECT_EQ(2, a3.GetElement(1));
697
698 // Tests erasing at the beginning of the vector.
699 Vector<int> a4;
700 a4.PushBack(0);
701 a4.PushBack(1);
702 a4.PushBack(2);
703
704 a4.Erase(0);
705 ASSERT_EQ(2, a4.size());
706 EXPECT_EQ(1, a4.GetElement(0));
707 EXPECT_EQ(2, a4.GetElement(1));
708}
709
zhanyong.wan9644db82009-06-24 23:02:50 +0000710// Tests the GetElement accessor.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000711TEST(ListDeathTest, GetElement) {
zhanyong.wana8a582f2009-07-13 19:25:02 +0000712 Vector<int> a;
zhanyong.wan9644db82009-06-24 23:02:50 +0000713 a.PushBack(0);
714 a.PushBack(1);
715 a.PushBack(2);
716
zhanyong.wan449f84d2009-07-01 22:55:05 +0000717 EXPECT_EQ(0, a.GetElement(0));
718 EXPECT_EQ(1, a.GetElement(1));
719 EXPECT_EQ(2, a.GetElement(2));
zhanyong.wan535de532009-08-07 06:47:47 +0000720 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +0000721 a.GetElement(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000722 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +0000723 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +0000724 a.GetElement(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000725 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +0000726}
shiqian4b6829f2008-07-03 22:38:12 +0000727
zhanyong.wanf39160b2009-09-04 18:30:25 +0000728// Tests the size of the AssertHelper class.
shiqian4b6829f2008-07-03 22:38:12 +0000729
zhanyong.wanf39160b2009-09-04 18:30:25 +0000730TEST(AssertHelperTest, AssertHelperIsSmall) {
zhanyong.wan89be5762009-09-01 18:53:56 +0000731 // To avoid breaking clients that use lots of assertions in one
zhanyong.wanf39160b2009-09-04 18:30:25 +0000732 // function, we cannot grow the size of AssertHelper.
733 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
zhanyong.wan89be5762009-09-01 18:53:56 +0000734}
735
zhanyong.wanf39160b2009-09-04 18:30:25 +0000736// Tests the String class.
737
shiqian4b6829f2008-07-03 22:38:12 +0000738// Tests String's constructors.
739TEST(StringTest, Constructors) {
740 // Default ctor.
741 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +0000742 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
743 // pointers with NULL isn't supported on all platforms.
zhanyong.wan89be5762009-09-01 18:53:56 +0000744 EXPECT_EQ(0U, s1.length());
shiqiandd4a17b2008-07-31 18:34:08 +0000745 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +0000746
747 // Implicitly constructs from a C-string.
748 String s2 = "Hi";
zhanyong.wan89be5762009-09-01 18:53:56 +0000749 EXPECT_EQ(2U, s2.length());
shiqian4b6829f2008-07-03 22:38:12 +0000750 EXPECT_STREQ("Hi", s2.c_str());
751
752 // Constructs from a C-string and a length.
753 String s3("hello", 3);
zhanyong.wan89be5762009-09-01 18:53:56 +0000754 EXPECT_EQ(3U, s3.length());
shiqian4b6829f2008-07-03 22:38:12 +0000755 EXPECT_STREQ("hel", s3.c_str());
756
zhanyong.wan89be5762009-09-01 18:53:56 +0000757 // The empty String should be created when String is constructed with
758 // a NULL pointer and length 0.
759 EXPECT_EQ(0U, String(NULL, 0).length());
760 EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
761
762 // Constructs a String that contains '\0'.
763 String s4("a\0bcd", 4);
764 EXPECT_EQ(4U, s4.length());
765 EXPECT_EQ('a', s4.c_str()[0]);
766 EXPECT_EQ('\0', s4.c_str()[1]);
767 EXPECT_EQ('b', s4.c_str()[2]);
768 EXPECT_EQ('c', s4.c_str()[3]);
769
770 // Copy ctor where the source is NULL.
771 const String null_str;
772 String s5 = null_str;
773 EXPECT_TRUE(s5.c_str() == NULL);
774
775 // Copy ctor where the source isn't NULL.
776 String s6 = s3;
777 EXPECT_EQ(3U, s6.length());
778 EXPECT_STREQ("hel", s6.c_str());
779
780 // Copy ctor where the source contains '\0'.
781 String s7 = s4;
782 EXPECT_EQ(4U, s7.length());
783 EXPECT_EQ('a', s7.c_str()[0]);
784 EXPECT_EQ('\0', s7.c_str()[1]);
785 EXPECT_EQ('b', s7.c_str()[2]);
786 EXPECT_EQ('c', s7.c_str()[3]);
shiqian4b6829f2008-07-03 22:38:12 +0000787}
788
vladlosevf179f4e2008-11-26 20:48:45 +0000789#if GTEST_HAS_STD_STRING
790
791TEST(StringTest, ConvertsFromStdString) {
792 // An empty std::string.
793 const std::string src1("");
794 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000795 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000796 EXPECT_STREQ("", dest1.c_str());
797
798 // A normal std::string.
799 const std::string src2("Hi");
800 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000801 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000802 EXPECT_STREQ("Hi", dest2.c_str());
803
804 // An std::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000805 const char src3[] = "a\0b";
vladlosevf179f4e2008-11-26 20:48:45 +0000806 const String dest3 = std::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000807 EXPECT_EQ(sizeof(src3), dest3.length());
808 EXPECT_EQ('a', dest3.c_str()[0]);
809 EXPECT_EQ('\0', dest3.c_str()[1]);
810 EXPECT_EQ('b', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000811}
812
813TEST(StringTest, ConvertsToStdString) {
814 // An empty String.
815 const String src1("");
816 const std::string dest1 = src1;
817 EXPECT_EQ("", dest1);
818
819 // A normal String.
820 const String src2("Hi");
821 const std::string dest2 = src2;
822 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000823
824 // A String containing a '\0'.
825 const String src3("x\0y", 3);
826 const std::string dest3 = src3;
827 EXPECT_EQ(std::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000828}
829
830#endif // GTEST_HAS_STD_STRING
831
832#if GTEST_HAS_GLOBAL_STRING
833
834TEST(StringTest, ConvertsFromGlobalString) {
835 // An empty ::string.
836 const ::string src1("");
837 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +0000838 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000839 EXPECT_STREQ("", dest1.c_str());
840
841 // A normal ::string.
842 const ::string src2("Hi");
843 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +0000844 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +0000845 EXPECT_STREQ("Hi", dest2.c_str());
846
847 // An ::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +0000848 const char src3[] = "x\0y";
vladlosevf179f4e2008-11-26 20:48:45 +0000849 const String dest3 = ::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +0000850 EXPECT_EQ(sizeof(src3), dest3.length());
851 EXPECT_EQ('x', dest3.c_str()[0]);
852 EXPECT_EQ('\0', dest3.c_str()[1]);
853 EXPECT_EQ('y', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +0000854}
855
856TEST(StringTest, ConvertsToGlobalString) {
857 // An empty String.
858 const String src1("");
859 const ::string dest1 = src1;
860 EXPECT_EQ("", dest1);
861
862 // A normal String.
863 const String src2("Hi");
864 const ::string dest2 = src2;
865 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +0000866
867 const String src3("x\0y", 3);
868 const ::string dest3 = src3;
869 EXPECT_EQ(::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +0000870}
871
872#endif // GTEST_HAS_GLOBAL_STRING
873
shiqian4b6829f2008-07-03 22:38:12 +0000874// Tests String::ShowCStringQuoted().
875TEST(StringTest, ShowCStringQuoted) {
876 EXPECT_STREQ("(null)",
877 String::ShowCStringQuoted(NULL).c_str());
878 EXPECT_STREQ("\"\"",
879 String::ShowCStringQuoted("").c_str());
880 EXPECT_STREQ("\"foo\"",
881 String::ShowCStringQuoted("foo").c_str());
882}
883
zhanyong.wan89be5762009-09-01 18:53:56 +0000884// Tests String::empty().
885TEST(StringTest, Empty) {
886 EXPECT_TRUE(String("").empty());
887 EXPECT_FALSE(String().empty());
888 EXPECT_FALSE(String(NULL).empty());
889 EXPECT_FALSE(String("a").empty());
890 EXPECT_FALSE(String("\0", 1).empty());
891}
892
893// Tests String::Compare().
894TEST(StringTest, Compare) {
895 // NULL vs NULL.
896 EXPECT_EQ(0, String().Compare(String()));
897
898 // NULL vs non-NULL.
899 EXPECT_EQ(-1, String().Compare(String("")));
900
901 // Non-NULL vs NULL.
902 EXPECT_EQ(1, String("").Compare(String()));
903
904 // The following covers non-NULL vs non-NULL.
905
906 // "" vs "".
907 EXPECT_EQ(0, String("").Compare(String("")));
908
909 // "" vs non-"".
910 EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
911 EXPECT_EQ(-1, String("").Compare(" "));
912
913 // Non-"" vs "".
914 EXPECT_EQ(1, String("a").Compare(String("")));
915
916 // The following covers non-"" vs non-"".
917
918 // Same length and equal.
919 EXPECT_EQ(0, String("a").Compare(String("a")));
920
921 // Same length and different.
922 EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
923 EXPECT_EQ(1, String("b").Compare(String("a")));
924
925 // Different lengths.
926 EXPECT_EQ(-1, String("a").Compare(String("ab")));
927 EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
928 EXPECT_EQ(1, String("abc").Compare(String("aacd")));
929}
930
shiqian4b6829f2008-07-03 22:38:12 +0000931// Tests String::operator==().
932TEST(StringTest, Equals) {
933 const String null(NULL);
934 EXPECT_TRUE(null == NULL); // NOLINT
935 EXPECT_FALSE(null == ""); // NOLINT
936 EXPECT_FALSE(null == "bar"); // NOLINT
937
938 const String empty("");
939 EXPECT_FALSE(empty == NULL); // NOLINT
940 EXPECT_TRUE(empty == ""); // NOLINT
941 EXPECT_FALSE(empty == "bar"); // NOLINT
942
943 const String foo("foo");
944 EXPECT_FALSE(foo == NULL); // NOLINT
945 EXPECT_FALSE(foo == ""); // NOLINT
946 EXPECT_FALSE(foo == "bar"); // NOLINT
947 EXPECT_TRUE(foo == "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +0000948
949 const String bar("x\0y", 3);
950 EXPECT_FALSE(bar == "x");
shiqian4b6829f2008-07-03 22:38:12 +0000951}
952
953// Tests String::operator!=().
954TEST(StringTest, NotEquals) {
955 const String null(NULL);
956 EXPECT_FALSE(null != NULL); // NOLINT
957 EXPECT_TRUE(null != ""); // NOLINT
958 EXPECT_TRUE(null != "bar"); // NOLINT
959
960 const String empty("");
961 EXPECT_TRUE(empty != NULL); // NOLINT
962 EXPECT_FALSE(empty != ""); // NOLINT
963 EXPECT_TRUE(empty != "bar"); // NOLINT
964
965 const String foo("foo");
966 EXPECT_TRUE(foo != NULL); // NOLINT
967 EXPECT_TRUE(foo != ""); // NOLINT
968 EXPECT_TRUE(foo != "bar"); // NOLINT
969 EXPECT_FALSE(foo != "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +0000970
971 const String bar("x\0y", 3);
972 EXPECT_TRUE(bar != "x");
973}
974
975// Tests String::length().
976TEST(StringTest, Length) {
977 EXPECT_EQ(0U, String().length());
978 EXPECT_EQ(0U, String("").length());
979 EXPECT_EQ(2U, String("ab").length());
980 EXPECT_EQ(3U, String("a\0b", 3).length());
shiqian4b6829f2008-07-03 22:38:12 +0000981}
982
983// Tests String::EndsWith().
984TEST(StringTest, EndsWith) {
985 EXPECT_TRUE(String("foobar").EndsWith("bar"));
986 EXPECT_TRUE(String("foobar").EndsWith(""));
987 EXPECT_TRUE(String("").EndsWith(""));
988
989 EXPECT_FALSE(String("foobar").EndsWith("foo"));
990 EXPECT_FALSE(String("").EndsWith("foo"));
991}
992
993// Tests String::EndsWithCaseInsensitive().
994TEST(StringTest, EndsWithCaseInsensitive) {
995 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
996 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
997 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
998 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
999
1000 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
1001 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
1002 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
1003}
1004
zhanyong.wan98efcc42009-04-28 00:28:09 +00001005// C++Builder's preprocessor is buggy; it fails to expand macros that
1006// appear in macro parameters after wide char literals. Provide an alias
1007// for NULL as a workaround.
1008static const wchar_t* const kNull = NULL;
1009
shiqiane8ff1482008-09-08 17:55:52 +00001010// Tests String::CaseInsensitiveWideCStringEquals
1011TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1012 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001013 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1014 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1015 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1016 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +00001017 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1018 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1019 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1020}
1021
shiqian4b6829f2008-07-03 22:38:12 +00001022// Tests that NULL can be assigned to a String.
1023TEST(StringTest, CanBeAssignedNULL) {
1024 const String src(NULL);
1025 String dest;
1026
1027 dest = src;
1028 EXPECT_STREQ(NULL, dest.c_str());
1029}
1030
1031// Tests that the empty string "" can be assigned to a String.
1032TEST(StringTest, CanBeAssignedEmpty) {
1033 const String src("");
1034 String dest;
1035
1036 dest = src;
1037 EXPECT_STREQ("", dest.c_str());
1038}
1039
1040// Tests that a non-empty string can be assigned to a String.
1041TEST(StringTest, CanBeAssignedNonEmpty) {
1042 const String src("hello");
1043 String dest;
shiqian4b6829f2008-07-03 22:38:12 +00001044 dest = src;
zhanyong.wan89be5762009-09-01 18:53:56 +00001045 EXPECT_EQ(5U, dest.length());
shiqian4b6829f2008-07-03 22:38:12 +00001046 EXPECT_STREQ("hello", dest.c_str());
zhanyong.wan89be5762009-09-01 18:53:56 +00001047
1048 const String src2("x\0y", 3);
1049 String dest2;
1050 dest2 = src2;
1051 EXPECT_EQ(3U, dest2.length());
1052 EXPECT_EQ('x', dest2.c_str()[0]);
1053 EXPECT_EQ('\0', dest2.c_str()[1]);
1054 EXPECT_EQ('y', dest2.c_str()[2]);
shiqian4b6829f2008-07-03 22:38:12 +00001055}
1056
1057// Tests that a String can be assigned to itself.
1058TEST(StringTest, CanBeAssignedSelf) {
1059 String dest("hello");
1060
1061 dest = dest;
1062 EXPECT_STREQ("hello", dest.c_str());
1063}
1064
zhanyong.wan89be5762009-09-01 18:53:56 +00001065// Tests streaming a String.
1066TEST(StringTest, Streams) {
1067 EXPECT_EQ(StreamableToString(String()), "(null)");
1068 EXPECT_EQ(StreamableToString(String("")), "");
1069 EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
1070}
1071
zhanyong.wanf39160b2009-09-04 18:30:25 +00001072// Tests that String::Format() works.
1073TEST(StringTest, FormatWorks) {
1074 // Normal case: the format spec is valid, the arguments match the
1075 // spec, and the result is < 4095 characters.
1076 EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
1077
1078 // Edge case: the result is 4095 characters.
1079 char buffer[4096];
1080 const size_t kSize = sizeof(buffer);
1081 memset(buffer, 'a', kSize - 1);
1082 buffer[kSize - 1] = '\0';
1083 EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
1084
1085 // The result needs to be 4096 characters, exceeding Format()'s limit.
1086 EXPECT_STREQ("<formatting error or buffer exceeded>",
1087 String::Format("x%s", buffer).c_str());
1088
1089#if GTEST_OS_LINUX
1090 // On Linux, invalid format spec should lead to an error message.
1091 // In other environment (e.g. MSVC on Windows), String::Format() may
1092 // simply ignore a bad format spec, so this assertion is run on
1093 // Linux only.
1094 EXPECT_STREQ("<formatting error or buffer exceeded>",
1095 String::Format("%").c_str());
1096#endif
1097}
1098
zhanyong.wan4cd62602009-02-23 23:21:55 +00001099#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00001100
1101// Tests String::ShowWideCString().
1102TEST(StringTest, ShowWideCString) {
1103 EXPECT_STREQ("(null)",
1104 String::ShowWideCString(NULL).c_str());
1105 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1106 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1107}
1108
1109// Tests String::ShowWideCStringQuoted().
1110TEST(StringTest, ShowWideCStringQuoted) {
1111 EXPECT_STREQ("(null)",
1112 String::ShowWideCStringQuoted(NULL).c_str());
1113 EXPECT_STREQ("L\"\"",
1114 String::ShowWideCStringQuoted(L"").c_str());
1115 EXPECT_STREQ("L\"foo\"",
1116 String::ShowWideCStringQuoted(L"foo").c_str());
1117}
1118
shiqiandd4a17b2008-07-31 18:34:08 +00001119#ifdef _WIN32_WCE
1120TEST(StringTest, AnsiAndUtf16Null) {
1121 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1122 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1123}
1124
1125TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1126 const char* ansi = String::Utf16ToAnsi(L"str");
1127 EXPECT_STREQ("str", ansi);
1128 delete [] ansi;
1129 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001130 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001131 delete [] utf16;
1132}
1133
1134TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1135 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1136 EXPECT_STREQ(".:\\ \"*?", ansi);
1137 delete [] ansi;
1138 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001139 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001140 delete [] utf16;
1141}
1142#endif // _WIN32_WCE
1143
shiqian4b6829f2008-07-03 22:38:12 +00001144#endif // GTEST_OS_WINDOWS
1145
1146// Tests TestProperty construction.
1147TEST(TestPropertyTest, StringValue) {
1148 TestProperty property("key", "1");
1149 EXPECT_STREQ("key", property.key());
1150 EXPECT_STREQ("1", property.value());
1151}
1152
1153// Tests TestProperty replacing a value.
1154TEST(TestPropertyTest, ReplaceStringValue) {
1155 TestProperty property("key", "1");
1156 EXPECT_STREQ("1", property.value());
1157 property.SetValue("2");
1158 EXPECT_STREQ("2", property.value());
1159}
1160
zhanyong.wan98efcc42009-04-28 00:28:09 +00001161// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1162// functions (i.e. their definitions cannot be inlined at the call
1163// sites), or C++Builder won't compile the code.
1164static void AddFatalFailure() {
1165 FAIL() << "Expected fatal failure.";
1166}
1167
1168static void AddNonfatalFailure() {
1169 ADD_FAILURE() << "Expected non-fatal failure.";
1170}
1171
shiqiane44602e2008-10-11 07:20:02 +00001172class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001173 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001174 enum FailureMode {
1175 FATAL_FAILURE,
1176 NONFATAL_FAILURE
1177 };
1178 static void AddFailure(FailureMode failure) {
1179 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001180 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001181 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001182 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001183 }
1184 }
shiqian4b6829f2008-07-03 22:38:12 +00001185};
1186
shiqian4b6829f2008-07-03 22:38:12 +00001187// Tests that ScopedFakeTestPartResultReporter intercepts test
1188// failures.
shiqiane44602e2008-10-11 07:20:02 +00001189TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001190 TestPartResultArray results;
1191 {
shiqiane44602e2008-10-11 07:20:02 +00001192 ScopedFakeTestPartResultReporter reporter(
1193 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1194 &results);
1195 AddFailure(NONFATAL_FAILURE);
1196 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001197 }
1198
1199 EXPECT_EQ(2, results.size());
1200 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1201 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1202}
1203
shiqiane44602e2008-10-11 07:20:02 +00001204TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1205 TestPartResultArray results;
1206 {
1207 // Tests, that the deprecated constructor still works.
1208 ScopedFakeTestPartResultReporter reporter(&results);
1209 AddFailure(NONFATAL_FAILURE);
1210 }
1211 EXPECT_EQ(1, results.size());
1212}
1213
1214#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1215
1216class ScopedFakeTestPartResultReporterWithThreadsTest
1217 : public ScopedFakeTestPartResultReporterTest {
1218 protected:
1219 static void AddFailureInOtherThread(FailureMode failure) {
1220 pthread_t tid;
1221 pthread_create(&tid,
1222 NULL,
1223 ScopedFakeTestPartResultReporterWithThreadsTest::
1224 FailureThread,
1225 &failure);
1226 pthread_join(tid, NULL);
1227 }
1228 private:
1229 static void* FailureThread(void* attr) {
1230 FailureMode* failure = static_cast<FailureMode*>(attr);
1231 AddFailure(*failure);
1232 return NULL;
1233 }
1234};
1235
1236TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1237 InterceptsTestFailuresInAllThreads) {
1238 TestPartResultArray results;
1239 {
1240 ScopedFakeTestPartResultReporter reporter(
1241 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1242 AddFailure(NONFATAL_FAILURE);
1243 AddFailure(FATAL_FAILURE);
1244 AddFailureInOtherThread(NONFATAL_FAILURE);
1245 AddFailureInOtherThread(FATAL_FAILURE);
1246 }
1247
1248 EXPECT_EQ(4, results.size());
1249 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1250 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1251 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1252 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1253}
1254
1255#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1256
zhanyong.wan98efcc42009-04-28 00:28:09 +00001257// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1258// work even if the failure is generated in a called function rather than
1259// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001260
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001261typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001262
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001263TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001264 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001265}
1266
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001267TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1268 // We have another test below to verify that the macro catches fatal
1269 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001270 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001271 "Expected fatal failure.");
1272}
1273
zhanyong.wan98efcc42009-04-28 00:28:09 +00001274#ifdef __BORLANDC__
1275// Silences warnings: "Condition is always true"
1276#pragma option push -w-ccc
1277#endif
1278
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001279// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1280// function even when the statement in it contains ASSERT_*.
1281
1282int NonVoidFunction() {
1283 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1284 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1285 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001286}
1287
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001288TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1289 NonVoidFunction();
1290}
1291
1292// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1293// current function even though 'statement' generates a fatal failure.
1294
1295void DoesNotAbortHelper(bool* aborted) {
1296 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1297 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1298
1299 *aborted = false;
1300}
1301
zhanyong.wan98efcc42009-04-28 00:28:09 +00001302#ifdef __BORLANDC__
1303// Restores warnings after previous "#pragma option push" supressed them
1304#pragma option pop
1305#endif
1306
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001307TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1308 bool aborted = true;
1309 DoesNotAbortHelper(&aborted);
1310 EXPECT_FALSE(aborted);
1311}
1312
1313// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1314// statement that contains a macro which expands to code containing an
1315// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001316
1317static int global_var = 0;
1318#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1319
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001320TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001321#ifndef __BORLANDC__
1322 // ICE's in C++Builder 2007.
shiqiane44602e2008-10-11 07:20:02 +00001323 EXPECT_FATAL_FAILURE({
1324 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001325 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001326 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001327#endif
shiqiane44602e2008-10-11 07:20:02 +00001328
1329 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1330 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001331 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001332 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001333}
shiqiane44602e2008-10-11 07:20:02 +00001334
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001335// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1336
1337typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1338
1339TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001340 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001341 "Expected non-fatal failure.");
1342}
1343
1344TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1345 // We have another test below to verify that the macro catches
1346 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001347 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001348 "Expected non-fatal failure.");
1349}
1350
1351// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1352// statement that contains a macro which expands to code containing an
1353// unprotected comma.
1354TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001355 EXPECT_NONFATAL_FAILURE({
1356 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001357 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001358 }, "");
1359
1360 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1361 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001362 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001363 }, "");
1364}
1365
1366#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1367
1368typedef ScopedFakeTestPartResultReporterWithThreadsTest
1369 ExpectFailureWithThreadsTest;
1370
1371TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1372 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1373 "Expected fatal failure.");
1374}
1375
1376TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1377 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1378 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1379}
1380
1381#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1382
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001383// Tests the TestProperty class.
1384
1385TEST(TestPropertyTest, ConstructorWorks) {
1386 const TestProperty property("key", "value");
1387 EXPECT_STREQ("key", property.key());
1388 EXPECT_STREQ("value", property.value());
1389}
1390
1391TEST(TestPropertyTest, SetValue) {
1392 TestProperty property("key", "value_1");
1393 EXPECT_STREQ("key", property.key());
1394 property.SetValue("value_2");
1395 EXPECT_STREQ("key", property.key());
1396 EXPECT_STREQ("value_2", property.value());
1397}
1398
1399// Tests the TestPartResult class.
1400
1401TEST(TestPartResultTest, ConstructorWorks) {
1402 Message message;
1403 message << "something is terribly wrong";
1404 message << static_cast<const char*>(testing::internal::kStackTraceMarker);
1405 message << "some unimportant stack trace";
1406
1407 const TestPartResult result(TPRT_NONFATAL_FAILURE,
1408 "some_file.cc",
1409 42,
1410 message.GetString().c_str());
1411
1412 EXPECT_EQ(TPRT_NONFATAL_FAILURE, result.type());
1413 EXPECT_STREQ("some_file.cc", result.file_name());
1414 EXPECT_EQ(42, result.line_number());
1415 EXPECT_STREQ(message.GetString().c_str(), result.message());
1416 EXPECT_STREQ("something is terribly wrong", result.summary());
1417}
1418
1419TEST(TestPartResultTest, ResultAccessorsWork) {
1420 const TestPartResult success(TPRT_SUCCESS, "file.cc", 42, "message");
1421 EXPECT_TRUE(success.passed());
1422 EXPECT_FALSE(success.failed());
1423 EXPECT_FALSE(success.nonfatally_failed());
1424 EXPECT_FALSE(success.fatally_failed());
1425
1426 const TestPartResult nonfatal_failure(TPRT_NONFATAL_FAILURE,
1427 "file.cc",
1428 42,
1429 "message");
1430 EXPECT_FALSE(nonfatal_failure.passed());
1431 EXPECT_TRUE(nonfatal_failure.failed());
1432 EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
1433 EXPECT_FALSE(nonfatal_failure.fatally_failed());
1434
1435 const TestPartResult fatal_failure(TPRT_FATAL_FAILURE,
1436 "file.cc",
1437 42,
1438 "message");
1439 EXPECT_FALSE(fatal_failure.passed());
1440 EXPECT_TRUE(fatal_failure.failed());
1441 EXPECT_FALSE(fatal_failure.nonfatally_failed());
1442 EXPECT_TRUE(fatal_failure.fatally_failed());
1443}
1444
shiqian4b6829f2008-07-03 22:38:12 +00001445// Tests the TestResult class
1446
1447// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001448class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001449 protected:
zhanyong.wana8a582f2009-07-13 19:25:02 +00001450 typedef Vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001451
1452 // We make use of 2 TestPartResult objects,
1453 TestPartResult * pr1, * pr2;
1454
1455 // ... and 3 TestResult objects.
1456 TestResult * r0, * r1, * r2;
1457
1458 virtual void SetUp() {
1459 // pr1 is for success.
shiqian760af5c2008-08-06 21:43:15 +00001460 pr1 = new TestPartResult(TPRT_SUCCESS, "foo/bar.cc", 10, "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001461
1462 // pr2 is for fatal failure.
shiqian760af5c2008-08-06 21:43:15 +00001463 pr2 = new TestPartResult(TPRT_FATAL_FAILURE, "foo/bar.cc",
1464 -1, // This line number means "unknown"
1465 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001466
1467 // Creates the TestResult objects.
1468 r0 = new TestResult();
1469 r1 = new TestResult();
1470 r2 = new TestResult();
1471
1472 // In order to test TestResult, we need to modify its internal
zhanyong.wana8a582f2009-07-13 19:25:02 +00001473 // state, in particular the TestPartResult Vector it holds.
1474 // test_part_results() returns a const reference to this Vector.
shiqian4b6829f2008-07-03 22:38:12 +00001475 // We cast it to a non-const object s.t. it can be modified (yes,
1476 // this is a hack).
zhanyong.wana8a582f2009-07-13 19:25:02 +00001477 TPRVector* results1 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001478 &TestResultAccessor::test_part_results(*r1));
zhanyong.wana8a582f2009-07-13 19:25:02 +00001479 TPRVector* results2 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001480 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001481
1482 // r0 is an empty TestResult.
1483
1484 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001485 results1->PushBack(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001486
1487 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001488 results2->PushBack(*pr1);
1489 results2->PushBack(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001490 }
1491
1492 virtual void TearDown() {
1493 delete pr1;
1494 delete pr2;
1495
1496 delete r0;
1497 delete r1;
1498 delete r2;
1499 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001500
1501 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001502 static void CompareTestPartResult(const TestPartResult& expected,
1503 const TestPartResult& actual) {
1504 EXPECT_EQ(expected.type(), actual.type());
1505 EXPECT_STREQ(expected.file_name(), actual.file_name());
1506 EXPECT_EQ(expected.line_number(), actual.line_number());
1507 EXPECT_STREQ(expected.summary(), actual.summary());
1508 EXPECT_STREQ(expected.message(), actual.message());
1509 EXPECT_EQ(expected.passed(), actual.passed());
1510 EXPECT_EQ(expected.failed(), actual.failed());
1511 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1512 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001513 }
shiqian4b6829f2008-07-03 22:38:12 +00001514};
1515
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001516// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001517TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001518 ASSERT_EQ(0, r0->total_part_count());
1519 ASSERT_EQ(1, r1->total_part_count());
1520 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001521}
1522
zhanyong.wan9644db82009-06-24 23:02:50 +00001523// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001524TEST_F(TestResultTest, Passed) {
1525 ASSERT_TRUE(r0->Passed());
1526 ASSERT_TRUE(r1->Passed());
1527 ASSERT_FALSE(r2->Passed());
1528}
1529
zhanyong.wan9644db82009-06-24 23:02:50 +00001530// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001531TEST_F(TestResultTest, Failed) {
1532 ASSERT_FALSE(r0->Failed());
1533 ASSERT_FALSE(r1->Failed());
1534 ASSERT_TRUE(r2->Failed());
1535}
1536
zhanyong.wan9644db82009-06-24 23:02:50 +00001537// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001538
1539typedef TestResultTest TestResultDeathTest;
1540
1541TEST_F(TestResultDeathTest, GetTestPartResult) {
1542 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1543 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
zhanyong.wan535de532009-08-07 06:47:47 +00001544 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001545 r2->GetTestPartResult(2),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001546 "Invalid Vector index 2: must be in range \\[0, 1\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +00001547 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001548 r2->GetTestPartResult(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001549 "Invalid Vector index -1: must be in range \\[0, 1\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001550}
1551
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001552// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001553TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1554 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001555 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001556}
1557
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001558// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001559TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1560 TestResult test_result;
1561 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001562 TestResultAccessor::RecordProperty(&test_result, property);
1563 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001564 const TestProperty& actual_property = test_result.GetTestProperty(0);
1565 EXPECT_STREQ("key_1", actual_property.key());
1566 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001567}
1568
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001569// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001570TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1571 TestResult test_result;
1572 TestProperty property_1("key_1", "1");
1573 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001574 TestResultAccessor::RecordProperty(&test_result, property_1);
1575 TestResultAccessor::RecordProperty(&test_result, property_2);
1576 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001577 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1578 EXPECT_STREQ("key_1", actual_property_1.key());
1579 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001580
zhanyong.wan449f84d2009-07-01 22:55:05 +00001581 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1582 EXPECT_STREQ("key_2", actual_property_2.key());
1583 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001584}
1585
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001586// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001587TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1588 TestResult test_result;
1589 TestProperty property_1_1("key_1", "1");
1590 TestProperty property_2_1("key_2", "2");
1591 TestProperty property_1_2("key_1", "12");
1592 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001593 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1594 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1595 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1596 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001597
zhanyong.wan9644db82009-06-24 23:02:50 +00001598 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001599 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1600 EXPECT_STREQ("key_1", actual_property_1.key());
1601 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001602
zhanyong.wan449f84d2009-07-01 22:55:05 +00001603 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1604 EXPECT_STREQ("key_2", actual_property_2.key());
1605 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001606}
1607
1608// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001609TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001610 TestResult test_result;
1611 TestProperty property_1("key_1", "1");
1612 TestProperty property_2("key_2", "2");
1613 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001614 TestResultAccessor::RecordProperty(&test_result, property_1);
1615 TestResultAccessor::RecordProperty(&test_result, property_2);
1616 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001617
zhanyong.wan449f84d2009-07-01 22:55:05 +00001618 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1619 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1620 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001621
zhanyong.wan449f84d2009-07-01 22:55:05 +00001622 EXPECT_STREQ("key_1", fetched_property_1.key());
1623 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001624
zhanyong.wan449f84d2009-07-01 22:55:05 +00001625 EXPECT_STREQ("key_2", fetched_property_2.key());
1626 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001627
zhanyong.wan449f84d2009-07-01 22:55:05 +00001628 EXPECT_STREQ("key_3", fetched_property_3.key());
1629 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001630
zhanyong.wan535de532009-08-07 06:47:47 +00001631 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001632 test_result.GetTestProperty(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001633 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +00001634 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001635 test_result.GetTestProperty(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001636 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001637}
1638
shiqian4b6829f2008-07-03 22:38:12 +00001639// When a property using a reserved key is supplied to this function, it tests
1640// that a non-fatal failure is added, a fatal failure is not added, and that the
1641// property is not recorded.
1642void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1643 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001644 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001645 EXPECT_NONFATAL_FAILURE(
1646 TestResultAccessor::RecordProperty(&test_result, property),
1647 "Reserved key");
1648 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001649}
1650
1651// Attempting to recording a property with the Reserved literal "name"
1652// should add a non-fatal failure and the property should not be recorded.
1653TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1654 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1655}
1656
1657// Attempting to recording a property with the Reserved literal "status"
1658// should add a non-fatal failure and the property should not be recorded.
1659TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1660 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1661}
1662
1663// Attempting to recording a property with the Reserved literal "time"
1664// should add a non-fatal failure and the property should not be recorded.
1665TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1666 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1667}
1668
1669// Attempting to recording a property with the Reserved literal "classname"
1670// should add a non-fatal failure and the property should not be recorded.
1671TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1672 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1673}
1674
1675// Tests that GTestFlagSaver works on Windows and Mac.
1676
shiqian760af5c2008-08-06 21:43:15 +00001677class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001678 protected:
1679 // Saves the Google Test flags such that we can restore them later, and
1680 // then sets them to their default values. This will be called
1681 // before the first test in this test case is run.
1682 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001683 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001684
shiqianca6949f2009-01-10 01:16:33 +00001685 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001686 GTEST_FLAG(break_on_failure) = false;
1687 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001688 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001689 GTEST_FLAG(color) = "auto";
1690 GTEST_FLAG(filter) = "";
1691 GTEST_FLAG(list_tests) = false;
1692 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001693 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001694 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001695 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001696 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001697 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001698 }
1699
1700 // Restores the Google Test flags that the tests have modified. This will
1701 // be called after the last test in this test case is run.
1702 static void TearDownTestCase() {
1703 delete saver_;
1704 saver_ = NULL;
1705 }
1706
1707 // Verifies that the Google Test flags have their default values, and then
1708 // modifies each of them.
1709 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001710 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001711 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1712 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1713 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001714 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001715 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1716 EXPECT_FALSE(GTEST_FLAG(list_tests));
1717 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001718 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001719 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001720 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001721 EXPECT_FALSE(GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001722 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001723
shiqianca6949f2009-01-10 01:16:33 +00001724 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001725 GTEST_FLAG(break_on_failure) = true;
1726 GTEST_FLAG(catch_exceptions) = true;
1727 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001728 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001729 GTEST_FLAG(filter) = "abc";
1730 GTEST_FLAG(list_tests) = true;
1731 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001732 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001733 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001734 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001735 GTEST_FLAG(shuffle) = true;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001736 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001737 }
1738 private:
1739 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001740 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001741};
1742
shiqian760af5c2008-08-06 21:43:15 +00001743GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001744
1745// Google Test doesn't guarantee the order of tests. The following two
1746// tests are designed to work regardless of their order.
1747
1748// Modifies the Google Test flags in the test body.
1749TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1750 VerifyAndModifyFlags();
1751}
1752
1753// Verifies that the Google Test flags in the body of the previous test were
1754// restored to their original values.
1755TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1756 VerifyAndModifyFlags();
1757}
1758
1759// Sets an environment variable with the given name to the given
1760// value. If the value argument is "", unsets the environment
1761// variable. The caller must ensure that both arguments are not NULL.
1762static void SetEnv(const char* name, const char* value) {
1763#ifdef _WIN32_WCE
1764 // Environment variables are not supported on Windows CE.
1765 return;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001766#elif defined(__BORLANDC__)
1767 // C++Builder's putenv only stores a pointer to its parameter; we have to
1768 // ensure that the string remains valid as long as it might be needed.
1769 // We use an std::map to do so.
1770 static std::map<String, String*> added_env;
1771
1772 // Because putenv stores a pointer to the string buffer, we can't delete the
1773 // previous string (if present) until after it's replaced.
1774 String *prev_env = NULL;
1775 if (added_env.find(name) != added_env.end()) {
1776 prev_env = added_env[name];
1777 }
1778 added_env[name] = new String((Message() << name << "=" << value).GetString());
1779 putenv(added_env[name]->c_str());
1780 delete prev_env;
1781
zhanyong.wan4cd62602009-02-23 23:21:55 +00001782#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001783 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001784#else
1785 if (*value == '\0') {
1786 unsetenv(name);
1787 } else {
1788 setenv(name, value, 1);
1789 }
1790#endif
1791}
1792
1793#ifndef _WIN32_WCE
1794// Environment variables are not supported on Windows CE.
1795
shiqian760af5c2008-08-06 21:43:15 +00001796using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001797
1798// Tests Int32FromGTestEnv().
1799
1800// Tests that Int32FromGTestEnv() returns the default value when the
1801// environment variable is not set.
1802TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001803 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001804 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1805}
1806
1807// Tests that Int32FromGTestEnv() returns the default value when the
1808// environment variable overflows as an Int32.
1809TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1810 printf("(expecting 2 warnings)\n");
1811
zhanyong.wan4cd62602009-02-23 23:21:55 +00001812 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001813 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1814
zhanyong.wan4cd62602009-02-23 23:21:55 +00001815 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001816 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1817}
1818
1819// Tests that Int32FromGTestEnv() returns the default value when the
1820// environment variable does not represent a valid decimal integer.
1821TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1822 printf("(expecting 2 warnings)\n");
1823
zhanyong.wan4cd62602009-02-23 23:21:55 +00001824 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001825 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1826
zhanyong.wan4cd62602009-02-23 23:21:55 +00001827 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001828 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1829}
1830
1831// Tests that Int32FromGTestEnv() parses and returns the value of the
1832// environment variable when it represents a valid decimal integer in
1833// the range of an Int32.
1834TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001835 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001836 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1837
zhanyong.wan4cd62602009-02-23 23:21:55 +00001838 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001839 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1840}
1841#endif // !defined(_WIN32_WCE)
1842
1843// Tests ParseInt32Flag().
1844
1845// Tests that ParseInt32Flag() returns false and doesn't change the
1846// output value when the flag has wrong format
1847TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1848 Int32 value = 123;
1849 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1850 EXPECT_EQ(123, value);
1851
1852 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1853 EXPECT_EQ(123, value);
1854}
1855
1856// Tests that ParseInt32Flag() returns false and doesn't change the
1857// output value when the flag overflows as an Int32.
1858TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1859 printf("(expecting 2 warnings)\n");
1860
1861 Int32 value = 123;
1862 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1863 EXPECT_EQ(123, value);
1864
1865 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1866 EXPECT_EQ(123, value);
1867}
1868
1869// Tests that ParseInt32Flag() returns false and doesn't change the
1870// output value when the flag does not represent a valid decimal
1871// integer.
1872TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1873 printf("(expecting 2 warnings)\n");
1874
1875 Int32 value = 123;
1876 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1877 EXPECT_EQ(123, value);
1878
1879 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1880 EXPECT_EQ(123, value);
1881}
1882
1883// Tests that ParseInt32Flag() parses the value of the flag and
1884// returns true when the flag represents a valid decimal integer in
1885// the range of an Int32.
1886TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1887 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001888 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001889 EXPECT_EQ(456, value);
1890
zhanyong.wan98efcc42009-04-28 00:28:09 +00001891 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1892 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001893 EXPECT_EQ(-789, value);
1894}
1895
zhanyong.wan905074c2009-02-09 18:05:21 +00001896// Tests that Int32FromEnvOrDie() parses the value of the var or
1897// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001898// Environment variables are not supported on Windows CE.
1899#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001900TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001901 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1902 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1903 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1904 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1905 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001906}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001907#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001908
1909// Tests that Int32FromEnvOrDie() aborts with an error message
1910// if the variable is not an Int32.
1911TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001912 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan535de532009-08-07 06:47:47 +00001913 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001914 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1915 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001916}
1917
1918// Tests that Int32FromEnvOrDie() aborts with an error message
1919// if the variable cannot be represnted by an Int32.
1920TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001921 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan535de532009-08-07 06:47:47 +00001922 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001923 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1924 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001925}
1926
zhanyong.wan905074c2009-02-09 18:05:21 +00001927// Tests that ShouldRunTestOnShard() selects all tests
1928// where there is 1 shard.
1929TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1930 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1931 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1932 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1933 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1934 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1935}
1936
1937class ShouldShardTest : public testing::Test {
1938 protected:
1939 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001940 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1941 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00001942 }
1943
1944 virtual void TearDown() {
1945 SetEnv(index_var_, "");
1946 SetEnv(total_var_, "");
1947 }
1948
1949 const char* index_var_;
1950 const char* total_var_;
1951};
1952
1953// Tests that sharding is disabled if neither of the environment variables
1954// are set.
1955TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1956 SetEnv(index_var_, "");
1957 SetEnv(total_var_, "");
1958
1959 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1960 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1961}
1962
1963// Tests that sharding is not enabled if total_shards == 1.
1964TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1965 SetEnv(index_var_, "0");
1966 SetEnv(total_var_, "1");
1967 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1968 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1969}
1970
1971// Tests that sharding is enabled if total_shards > 1 and
1972// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001973// Environment variables are not supported on Windows CE.
1974#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001975TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1976 SetEnv(index_var_, "4");
1977 SetEnv(total_var_, "22");
1978 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1979 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1980
1981 SetEnv(index_var_, "8");
1982 SetEnv(total_var_, "9");
1983 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1984 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1985
1986 SetEnv(index_var_, "0");
1987 SetEnv(total_var_, "9");
1988 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1989 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1990}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001991#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001992
1993// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001994
1995typedef ShouldShardTest ShouldShardDeathTest;
1996
1997TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00001998 SetEnv(index_var_, "4");
1999 SetEnv(total_var_, "4");
zhanyong.wan535de532009-08-07 06:47:47 +00002000 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002001
2002 SetEnv(index_var_, "4");
2003 SetEnv(total_var_, "-2");
zhanyong.wan535de532009-08-07 06:47:47 +00002004 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002005
2006 SetEnv(index_var_, "5");
2007 SetEnv(total_var_, "");
zhanyong.wan535de532009-08-07 06:47:47 +00002008 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002009
2010 SetEnv(index_var_, "");
2011 SetEnv(total_var_, "5");
zhanyong.wan535de532009-08-07 06:47:47 +00002012 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002013}
2014
zhanyong.wan905074c2009-02-09 18:05:21 +00002015// Tests that ShouldRunTestOnShard is a partition when 5
2016// shards are used.
2017TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
2018 // Choose an arbitrary number of tests and shards.
2019 const int num_tests = 17;
2020 const int num_shards = 5;
2021
2022 // Check partitioning: each test should be on exactly 1 shard.
2023 for (int test_id = 0; test_id < num_tests; test_id++) {
2024 int prev_selected_shard_index = -1;
2025 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2026 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
2027 if (prev_selected_shard_index < 0) {
2028 prev_selected_shard_index = shard_index;
2029 } else {
2030 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
2031 << shard_index << " are both selected to run test " << test_id;
2032 }
2033 }
2034 }
2035 }
2036
2037 // Check balance: This is not required by the sharding protocol, but is a
2038 // desirable property for performance.
2039 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2040 int num_tests_on_shard = 0;
2041 for (int test_id = 0; test_id < num_tests; test_id++) {
2042 num_tests_on_shard +=
2043 ShouldRunTestOnShard(num_shards, shard_index, test_id);
2044 }
2045 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
2046 }
2047}
2048
shiqian4b6829f2008-07-03 22:38:12 +00002049// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00002050// Test class, there are no separate tests for the following classes
2051// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00002052//
2053// TestCase, UnitTest, UnitTestResultPrinter.
2054//
2055// Similarly, there are no separate tests for the following macros:
2056//
2057// TEST, TEST_F, RUN_ALL_TESTS
2058
shiqianc3b4de32008-09-12 04:01:37 +00002059TEST(UnitTestTest, CanGetOriginalWorkingDir) {
2060 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
2061 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2062}
2063
shiqian4b6829f2008-07-03 22:38:12 +00002064// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2065// of various arities. They do not attempt to be exhaustive. Rather,
2066// view them as smoke tests that can be easily reviewed and verified.
2067// A more complete set of tests for predicate assertions can be found
2068// in gtest_pred_impl_unittest.cc.
2069
2070// First, some predicates and predicate-formatters needed by the tests.
2071
2072// Returns true iff the argument is an even number.
2073bool IsEven(int n) {
2074 return (n % 2) == 0;
2075}
2076
2077// A functor that returns true iff the argument is an even number.
2078struct IsEvenFunctor {
2079 bool operator()(int n) { return IsEven(n); }
2080};
2081
2082// A predicate-formatter function that asserts the argument is an even
2083// number.
shiqian760af5c2008-08-06 21:43:15 +00002084AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002085 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00002086 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002087 }
2088
shiqian760af5c2008-08-06 21:43:15 +00002089 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002090 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002091 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002092}
2093
2094// A predicate-formatter functor that asserts the argument is an even
2095// number.
2096struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00002097 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002098 return AssertIsEven(expr, n);
2099 }
2100};
2101
2102// Returns true iff the sum of the arguments is an even number.
2103bool SumIsEven2(int n1, int n2) {
2104 return IsEven(n1 + n2);
2105}
2106
2107// A functor that returns true iff the sum of the arguments is an even
2108// number.
2109struct SumIsEven3Functor {
2110 bool operator()(int n1, int n2, int n3) {
2111 return IsEven(n1 + n2 + n3);
2112 }
2113};
2114
2115// A predicate-formatter function that asserts the sum of the
2116// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00002117AssertionResult AssertSumIsEven4(
2118 const char* e1, const char* e2, const char* e3, const char* e4,
2119 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00002120 const int sum = n1 + n2 + n3 + n4;
2121 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002122 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002123 }
2124
shiqian760af5c2008-08-06 21:43:15 +00002125 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002126 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2127 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2128 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002129 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002130}
2131
2132// A predicate-formatter functor that asserts the sum of the arguments
2133// is an even number.
2134struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00002135 AssertionResult operator()(
2136 const char* e1, const char* e2, const char* e3, const char* e4,
2137 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00002138 const int sum = n1 + n2 + n3 + n4 + n5;
2139 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002140 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002141 }
2142
shiqian760af5c2008-08-06 21:43:15 +00002143 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002144 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2145 << " ("
2146 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2147 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002148 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002149 }
2150};
2151
2152
2153// Tests unary predicate assertions.
2154
2155// Tests unary predicate assertions that don't use a custom formatter.
2156TEST(Pred1Test, WithoutFormat) {
2157 // Success cases.
2158 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2159 ASSERT_PRED1(IsEven, 4);
2160
2161 // Failure cases.
2162 EXPECT_NONFATAL_FAILURE({ // NOLINT
2163 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2164 }, "This failure is expected.");
2165 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2166 "evaluates to false");
2167}
2168
2169// Tests unary predicate assertions that use a custom formatter.
2170TEST(Pred1Test, WithFormat) {
2171 // Success cases.
2172 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2173 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2174 << "This failure is UNEXPECTED!";
2175
2176 // Failure cases.
2177 const int n = 5;
2178 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2179 "n evaluates to 5, which is not even.");
2180 EXPECT_FATAL_FAILURE({ // NOLINT
2181 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2182 }, "This failure is expected.");
2183}
2184
2185// Tests that unary predicate assertions evaluates their arguments
2186// exactly once.
2187TEST(Pred1Test, SingleEvaluationOnFailure) {
2188 // A success case.
2189 static int n = 0;
2190 EXPECT_PRED1(IsEven, n++);
2191 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2192
2193 // A failure case.
2194 EXPECT_FATAL_FAILURE({ // NOLINT
2195 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2196 << "This failure is expected.";
2197 }, "This failure is expected.");
2198 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2199}
2200
2201
2202// Tests predicate assertions whose arity is >= 2.
2203
2204// Tests predicate assertions that don't use a custom formatter.
2205TEST(PredTest, WithoutFormat) {
2206 // Success cases.
2207 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2208 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2209
2210 // Failure cases.
2211 const int n1 = 1;
2212 const int n2 = 2;
2213 EXPECT_NONFATAL_FAILURE({ // NOLINT
2214 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2215 }, "This failure is expected.");
2216 EXPECT_FATAL_FAILURE({ // NOLINT
2217 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2218 }, "evaluates to false");
2219}
2220
2221// Tests predicate assertions that use a custom formatter.
2222TEST(PredTest, WithFormat) {
2223 // Success cases.
2224 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2225 "This failure is UNEXPECTED!";
2226 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2227
2228 // Failure cases.
2229 const int n1 = 1;
2230 const int n2 = 2;
2231 const int n3 = 4;
2232 const int n4 = 6;
2233 EXPECT_NONFATAL_FAILURE({ // NOLINT
2234 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2235 }, "evaluates to 13, which is not even.");
2236 EXPECT_FATAL_FAILURE({ // NOLINT
2237 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2238 << "This failure is expected.";
2239 }, "This failure is expected.");
2240}
2241
2242// Tests that predicate assertions evaluates their arguments
2243// exactly once.
2244TEST(PredTest, SingleEvaluationOnFailure) {
2245 // A success case.
2246 int n1 = 0;
2247 int n2 = 0;
2248 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2249 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2250 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2251
2252 // Another success case.
2253 n1 = n2 = 0;
2254 int n3 = 0;
2255 int n4 = 0;
2256 int n5 = 0;
2257 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2258 n1++, n2++, n3++, n4++, n5++)
2259 << "This failure is UNEXPECTED!";
2260 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2261 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2262 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2263 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2264 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2265
2266 // A failure case.
2267 n1 = n2 = n3 = 0;
2268 EXPECT_NONFATAL_FAILURE({ // NOLINT
2269 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2270 << "This failure is expected.";
2271 }, "This failure is expected.");
2272 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2273 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2274 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2275
2276 // Another failure case.
2277 n1 = n2 = n3 = n4 = 0;
2278 EXPECT_NONFATAL_FAILURE({ // NOLINT
2279 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2280 }, "evaluates to 1, which is not even.");
2281 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2282 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2283 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2284 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2285}
2286
2287
2288// Some helper functions for testing using overloaded/template
2289// functions with ASSERT_PREDn and EXPECT_PREDn.
2290
2291bool IsPositive(int n) {
2292 return n > 0;
2293}
2294
2295bool IsPositive(double x) {
2296 return x > 0;
2297}
2298
2299template <typename T>
2300bool IsNegative(T x) {
2301 return x < 0;
2302}
2303
2304template <typename T1, typename T2>
2305bool GreaterThan(T1 x1, T2 x2) {
2306 return x1 > x2;
2307}
2308
2309// Tests that overloaded functions can be used in *_PRED* as long as
2310// their types are explicitly specified.
2311TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002312 // C++Builder requires C-style casts rather than static_cast.
2313 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2314 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002315}
2316
2317// Tests that template functions can be used in *_PRED* as long as
2318// their types are explicitly specified.
2319TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2320 EXPECT_PRED1(IsNegative<int>, -5);
2321 // Makes sure that we can handle templates with more than one
2322 // parameter.
2323 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2324}
2325
2326
2327// Some helper functions for testing using overloaded/template
2328// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2329
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002330AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002331 return n > 0 ? AssertionSuccess() :
2332 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002333}
2334
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002335AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002336 return x > 0 ? AssertionSuccess() :
2337 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002338}
2339
2340template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002341AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002342 return x < 0 ? AssertionSuccess() :
2343 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002344}
2345
2346template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002347AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002348 const T1& x1, const T2& x2) {
2349 return x1 == x2 ? AssertionSuccess() :
2350 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002351}
2352
2353// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002354// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002355TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2356 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2357 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2358}
2359
2360// Tests that template functions can be used in *_PRED_FORMAT* without
2361// explicitly specifying their types.
2362TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2363 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2364 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2365}
2366
2367
2368// Tests string assertions.
2369
2370// Tests ASSERT_STREQ with non-NULL arguments.
2371TEST(StringAssertionTest, ASSERT_STREQ) {
2372 const char * const p1 = "good";
2373 ASSERT_STREQ(p1, p1);
2374
2375 // Let p2 have the same content as p1, but be at a different address.
2376 const char p2[] = "good";
2377 ASSERT_STREQ(p1, p2);
2378
2379 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2380 "Expected: \"bad\"");
2381}
2382
2383// Tests ASSERT_STREQ with NULL arguments.
2384TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2385 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2386 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2387 "non-null");
2388}
2389
2390// Tests ASSERT_STREQ with NULL arguments.
2391TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2392 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2393 "non-null");
2394}
2395
2396// Tests ASSERT_STRNE.
2397TEST(StringAssertionTest, ASSERT_STRNE) {
2398 ASSERT_STRNE("hi", "Hi");
2399 ASSERT_STRNE("Hi", NULL);
2400 ASSERT_STRNE(NULL, "Hi");
2401 ASSERT_STRNE("", NULL);
2402 ASSERT_STRNE(NULL, "");
2403 ASSERT_STRNE("", "Hi");
2404 ASSERT_STRNE("Hi", "");
2405 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2406 "\"Hi\" vs \"Hi\"");
2407}
2408
2409// Tests ASSERT_STRCASEEQ.
2410TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2411 ASSERT_STRCASEEQ("hi", "Hi");
2412 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2413
2414 ASSERT_STRCASEEQ("", "");
2415 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2416 "(ignoring case)");
2417}
2418
2419// Tests ASSERT_STRCASENE.
2420TEST(StringAssertionTest, ASSERT_STRCASENE) {
2421 ASSERT_STRCASENE("hi1", "Hi2");
2422 ASSERT_STRCASENE("Hi", NULL);
2423 ASSERT_STRCASENE(NULL, "Hi");
2424 ASSERT_STRCASENE("", NULL);
2425 ASSERT_STRCASENE(NULL, "");
2426 ASSERT_STRCASENE("", "Hi");
2427 ASSERT_STRCASENE("Hi", "");
2428 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2429 "(ignoring case)");
2430}
2431
2432// Tests *_STREQ on wide strings.
2433TEST(StringAssertionTest, STREQ_Wide) {
2434 // NULL strings.
2435 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2436
2437 // Empty strings.
2438 ASSERT_STREQ(L"", L"");
2439
2440 // Non-null vs NULL.
2441 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2442 "non-null");
2443
2444 // Equal strings.
2445 EXPECT_STREQ(L"Hi", L"Hi");
2446
2447 // Unequal strings.
2448 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2449 "Abc");
2450
2451 // Strings containing wide characters.
2452 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2453 "abc");
2454}
2455
2456// Tests *_STRNE on wide strings.
2457TEST(StringAssertionTest, STRNE_Wide) {
2458 // NULL strings.
2459 EXPECT_NONFATAL_FAILURE({ // NOLINT
2460 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2461 }, "");
2462
2463 // Empty strings.
2464 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2465 "L\"\"");
2466
2467 // Non-null vs NULL.
2468 ASSERT_STRNE(L"non-null", NULL);
2469
2470 // Equal strings.
2471 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2472 "L\"Hi\"");
2473
2474 // Unequal strings.
2475 EXPECT_STRNE(L"abc", L"Abc");
2476
2477 // Strings containing wide characters.
2478 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2479 "abc");
2480}
2481
2482// Tests for ::testing::IsSubstring().
2483
2484// Tests that IsSubstring() returns the correct result when the input
2485// argument type is const char*.
2486TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002487 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2488 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2489 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2490
2491 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2492 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2493}
2494
2495// Tests that IsSubstring() returns the correct result when the input
2496// argument type is const wchar_t*.
2497TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002498 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2499 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002500 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2501
2502 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2503 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2504}
2505
2506// Tests that IsSubstring() generates the correct message when the input
2507// argument type is const char*.
2508TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2509 EXPECT_STREQ("Value of: needle_expr\n"
2510 " Actual: \"needle\"\n"
2511 "Expected: a substring of haystack_expr\n"
2512 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002513 IsSubstring("needle_expr", "haystack_expr",
2514 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002515}
2516
2517#if GTEST_HAS_STD_STRING
2518
2519// Tests that IsSubstring returns the correct result when the input
2520// argument type is ::std::string.
2521TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002522 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2523 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002524}
2525
2526#endif // GTEST_HAS_STD_STRING
2527
2528#if GTEST_HAS_STD_WSTRING
2529// Tests that IsSubstring returns the correct result when the input
2530// argument type is ::std::wstring.
2531TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002532 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2533 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2534}
2535
2536// Tests that IsSubstring() generates the correct message when the input
2537// argument type is ::std::wstring.
2538TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2539 EXPECT_STREQ("Value of: needle_expr\n"
2540 " Actual: L\"needle\"\n"
2541 "Expected: a substring of haystack_expr\n"
2542 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002543 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002544 "needle_expr", "haystack_expr",
2545 ::std::wstring(L"needle"), L"haystack").failure_message());
2546}
2547
2548#endif // GTEST_HAS_STD_WSTRING
2549
2550// Tests for ::testing::IsNotSubstring().
2551
2552// Tests that IsNotSubstring() returns the correct result when the input
2553// argument type is const char*.
2554TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002555 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2556 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2557}
2558
2559// Tests that IsNotSubstring() returns the correct result when the input
2560// argument type is const wchar_t*.
2561TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002562 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2563 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2564}
2565
2566// Tests that IsNotSubstring() generates the correct message when the input
2567// argument type is const wchar_t*.
2568TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2569 EXPECT_STREQ("Value of: needle_expr\n"
2570 " Actual: L\"needle\"\n"
2571 "Expected: not a substring of haystack_expr\n"
2572 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002573 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002574 "needle_expr", "haystack_expr",
2575 L"needle", L"two needles").failure_message());
2576}
2577
2578#if GTEST_HAS_STD_STRING
2579
2580// Tests that IsNotSubstring returns the correct result when the input
2581// argument type is ::std::string.
2582TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002583 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2584 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2585}
2586
2587// Tests that IsNotSubstring() generates the correct message when the input
2588// argument type is ::std::string.
2589TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2590 EXPECT_STREQ("Value of: needle_expr\n"
2591 " Actual: \"needle\"\n"
2592 "Expected: not a substring of haystack_expr\n"
2593 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002594 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002595 "needle_expr", "haystack_expr",
2596 ::std::string("needle"), "two needles").failure_message());
2597}
2598
2599#endif // GTEST_HAS_STD_STRING
2600
2601#if GTEST_HAS_STD_WSTRING
2602
2603// Tests that IsNotSubstring returns the correct result when the input
2604// argument type is ::std::wstring.
2605TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002606 EXPECT_FALSE(
2607 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2608 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2609}
2610
2611#endif // GTEST_HAS_STD_WSTRING
2612
2613// Tests floating-point assertions.
2614
2615template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002616class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002617 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002618
2619 // Pre-calculated numbers to be used by the tests.
2620 struct TestValues {
2621 RawType close_to_positive_zero;
2622 RawType close_to_negative_zero;
2623 RawType further_from_negative_zero;
2624
2625 RawType close_to_one;
2626 RawType further_from_one;
2627
2628 RawType infinity;
2629 RawType close_to_infinity;
2630 RawType further_from_infinity;
2631
2632 RawType nan1;
2633 RawType nan2;
2634 };
2635
shiqian4b6829f2008-07-03 22:38:12 +00002636 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2637 typedef typename Floating::Bits Bits;
2638
2639 virtual void SetUp() {
2640 const size_t max_ulps = Floating::kMaxUlps;
2641
2642 // The bits that represent 0.0.
2643 const Bits zero_bits = Floating(0).bits();
2644
2645 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002646 values_.close_to_positive_zero = Floating::ReinterpretBits(
2647 zero_bits + max_ulps/2);
2648 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002649 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002650 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002651 zero_bits + max_ulps + 1 - max_ulps/2);
2652
2653 // The bits that represent 1.0.
2654 const Bits one_bits = Floating(1).bits();
2655
2656 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002657 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2658 values_.further_from_one = Floating::ReinterpretBits(
2659 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002660
2661 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002662 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002663
2664 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002665 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002666
2667 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002668 values_.close_to_infinity = Floating::ReinterpretBits(
2669 infinity_bits - max_ulps);
2670 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002671 infinity_bits - max_ulps - 1);
2672
zhanyong.wan98efcc42009-04-28 00:28:09 +00002673 // Makes some NAN's. Sets the most significant bit of the fraction so that
2674 // our NaN's are quiet; trying to process a signaling NaN would raise an
2675 // exception if our environment enables floating point exceptions.
2676 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2677 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2678 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2679 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002680 }
2681
2682 void TestSize() {
2683 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2684 }
2685
zhanyong.wan98efcc42009-04-28 00:28:09 +00002686 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002687};
2688
2689template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002690typename FloatingPointTest<RawType>::TestValues
2691 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002692
2693// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2694typedef FloatingPointTest<float> FloatTest;
2695
2696// Tests that the size of Float::Bits matches the size of float.
2697TEST_F(FloatTest, Size) {
2698 TestSize();
2699}
2700
2701// Tests comparing with +0 and -0.
2702TEST_F(FloatTest, Zeros) {
2703 EXPECT_FLOAT_EQ(0.0, -0.0);
2704 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2705 "1.0");
2706 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2707 "1.5");
2708}
2709
2710// Tests comparing numbers close to 0.
2711//
2712// This ensures that *_FLOAT_EQ handles the sign correctly and no
2713// overflow occurs when comparing numbers whose absolute value is very
2714// small.
2715TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002716 // In C++Builder, names within local classes (such as used by
2717 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2718 // scoping class. Use a static local alias as a workaround.
2719 static const FloatTest::TestValues& v(this->values_);
2720
2721 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2722 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2723 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002724
2725 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002726 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2727 v.further_from_negative_zero);
2728 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002729}
2730
2731// Tests comparing numbers close to each other.
2732TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002733 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2734 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2735 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002736}
2737
2738// Tests comparing numbers far apart.
2739TEST_F(FloatTest, LargeDiff) {
2740 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2741 "3.0");
2742}
2743
2744// Tests comparing with infinity.
2745//
2746// This ensures that no overflow occurs when comparing numbers whose
2747// absolute value is very large.
2748TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002749 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2750 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002751#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002752 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002753 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2754 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002755
zhanyong.wan98efcc42009-04-28 00:28:09 +00002756 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002757 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002758 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2759 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002760#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002761}
2762
2763// Tests that comparing with NAN always returns false.
2764TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002765#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002766// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002767
zhanyong.wan98efcc42009-04-28 00:28:09 +00002768 // In C++Builder, names within local classes (such as used by
2769 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2770 // scoping class. Use a static local alias as a workaround.
2771 static const FloatTest::TestValues& v(this->values_);
2772
2773 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2774 "v.nan1");
2775 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2776 "v.nan2");
2777 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2778 "v.nan1");
2779
2780 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2781 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002782#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002783}
2784
2785// Tests that *_FLOAT_EQ are reflexive.
2786TEST_F(FloatTest, Reflexive) {
2787 EXPECT_FLOAT_EQ(0.0, 0.0);
2788 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002789 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002790}
2791
2792// Tests that *_FLOAT_EQ are commutative.
2793TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002794 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2795 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002796
zhanyong.wan98efcc42009-04-28 00:28:09 +00002797 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2798 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002799 "1.0");
2800}
2801
2802// Tests EXPECT_NEAR.
2803TEST_F(FloatTest, EXPECT_NEAR) {
2804 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2805 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2806 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2807 "The difference between 1.0f and 1.2f is 0.2, "
2808 "which exceeds 0.1f");
2809 // To work around a bug in gcc 2.95.0, there is intentionally no
2810 // space after the first comma in the previous line.
2811}
2812
2813// Tests ASSERT_NEAR.
2814TEST_F(FloatTest, ASSERT_NEAR) {
2815 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2816 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2817 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2818 "The difference between 1.0f and 1.2f is 0.2, "
2819 "which exceeds 0.1f");
2820 // To work around a bug in gcc 2.95.0, there is intentionally no
2821 // space after the first comma in the previous line.
2822}
2823
2824// Tests the cases where FloatLE() should succeed.
2825TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002826 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2827 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002828
2829 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002830 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002831}
2832
2833// Tests the cases where FloatLE() should fail.
2834TEST_F(FloatTest, FloatLEFails) {
2835 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002836 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002837 "(2.0f) <= (1.0f)");
2838
2839 // or by a small yet non-negligible margin,
2840 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002841 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2842 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002843
zhanyong.wan98efcc42009-04-28 00:28:09 +00002844#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002845 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002846 // C++Builder gives bad results for ordered comparisons involving NaNs
2847 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002848 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002849 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2850 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002851 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002852 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2853 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002854 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002855 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2856 }, "(values_.nan1) <= (values_.nan1)");
2857#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002858}
2859
2860// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2861typedef FloatingPointTest<double> DoubleTest;
2862
2863// Tests that the size of Double::Bits matches the size of double.
2864TEST_F(DoubleTest, Size) {
2865 TestSize();
2866}
2867
2868// Tests comparing with +0 and -0.
2869TEST_F(DoubleTest, Zeros) {
2870 EXPECT_DOUBLE_EQ(0.0, -0.0);
2871 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2872 "1.0");
2873 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2874 "1.0");
2875}
2876
2877// Tests comparing numbers close to 0.
2878//
2879// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2880// overflow occurs when comparing numbers whose absolute value is very
2881// small.
2882TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002883 // In C++Builder, names within local classes (such as used by
2884 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2885 // scoping class. Use a static local alias as a workaround.
2886 static const DoubleTest::TestValues& v(this->values_);
2887
2888 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2889 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2890 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002891
2892 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002893 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2894 v.further_from_negative_zero);
2895 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002896}
2897
2898// Tests comparing numbers close to each other.
2899TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002900 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2901 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2902 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002903}
2904
2905// Tests comparing numbers far apart.
2906TEST_F(DoubleTest, LargeDiff) {
2907 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2908 "3.0");
2909}
2910
2911// Tests comparing with infinity.
2912//
2913// This ensures that no overflow occurs when comparing numbers whose
2914// absolute value is very large.
2915TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002916 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2917 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002918#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002919 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002920 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2921 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002922
2923 // This is interesting as the representations of infinity_ and nan1_
2924 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002925 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2926 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002927#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002928}
2929
2930// Tests that comparing with NAN always returns false.
2931TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002932#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00002933 // In C++Builder, names within local classes (such as used by
2934 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2935 // scoping class. Use a static local alias as a workaround.
2936 static const DoubleTest::TestValues& v(this->values_);
2937
shiqiane44602e2008-10-11 07:20:02 +00002938 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002939 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2940 "v.nan1");
2941 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2942 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2943 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2944 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002945#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002946}
2947
2948// Tests that *_DOUBLE_EQ are reflexive.
2949TEST_F(DoubleTest, Reflexive) {
2950 EXPECT_DOUBLE_EQ(0.0, 0.0);
2951 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002952#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002953 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002954 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002955#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002956}
2957
2958// Tests that *_DOUBLE_EQ are commutative.
2959TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002960 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
2961 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002962
zhanyong.wan98efcc42009-04-28 00:28:09 +00002963 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
2964 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
2965 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00002966}
2967
2968// Tests EXPECT_NEAR.
2969TEST_F(DoubleTest, EXPECT_NEAR) {
2970 EXPECT_NEAR(-1.0, -1.1, 0.2);
2971 EXPECT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002972 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
2973 "The difference between 1.0 and 1.2 is 0.2, "
2974 "which exceeds 0.1");
2975 // To work around a bug in gcc 2.95.0, there is intentionally no
2976 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002977}
2978
2979// Tests ASSERT_NEAR.
2980TEST_F(DoubleTest, ASSERT_NEAR) {
2981 ASSERT_NEAR(-1.0, -1.1, 0.2);
2982 ASSERT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002983 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
2984 "The difference between 1.0 and 1.2 is 0.2, "
2985 "which exceeds 0.1");
2986 // To work around a bug in gcc 2.95.0, there is intentionally no
2987 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002988}
2989
2990// Tests the cases where DoubleLE() should succeed.
2991TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002992 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
2993 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002994
2995 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002996 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00002997}
2998
2999// Tests the cases where DoubleLE() should fail.
3000TEST_F(DoubleTest, DoubleLEFails) {
3001 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003002 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003003 "(2.0) <= (1.0)");
3004
3005 // or by a small yet non-negligible margin,
3006 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003007 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3008 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00003009
zhanyong.wan98efcc42009-04-28 00:28:09 +00003010#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003011 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003012 // C++Builder gives bad results for ordered comparisons involving NaNs
3013 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003014 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003015 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3016 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003017 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003018 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3019 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003020 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003021 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3022 }, "(values_.nan1) <= (values_.nan1)");
3023#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003024}
3025
3026
3027// Verifies that a test or test case whose name starts with DISABLED_ is
3028// not run.
3029
3030// A test whose name starts with DISABLED_.
3031// Should not run.
3032TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3033 FAIL() << "Unexpected failure: Disabled test should not be run.";
3034}
3035
3036// A test whose name does not start with DISABLED_.
3037// Should run.
3038TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3039 EXPECT_EQ(1, 1);
3040}
3041
3042// A test case whose name starts with DISABLED_.
3043// Should not run.
3044TEST(DISABLED_TestCase, TestShouldNotRun) {
3045 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3046}
3047
3048// A test case and test whose names start with DISABLED_.
3049// Should not run.
3050TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3051 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3052}
3053
3054// Check that when all tests in a test case are disabled, SetupTestCase() and
3055// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00003056class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00003057 protected:
3058 static void SetUpTestCase() {
3059 FAIL() << "Unexpected failure: All tests disabled in test case. "
3060 "SetupTestCase() should not be called.";
3061 }
3062
3063 static void TearDownTestCase() {
3064 FAIL() << "Unexpected failure: All tests disabled in test case. "
3065 "TearDownTestCase() should not be called.";
3066 }
3067};
3068
3069TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3070 FAIL() << "Unexpected failure: Disabled test should not be run.";
3071}
3072
3073TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3074 FAIL() << "Unexpected failure: Disabled test should not be run.";
3075}
3076
shiqiane8ff1482008-09-08 17:55:52 +00003077// Tests that disabled typed tests aren't run.
3078
zhanyong.wan4cd62602009-02-23 23:21:55 +00003079#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00003080
3081template <typename T>
3082class TypedTest : public Test {
3083};
3084
3085typedef testing::Types<int, double> NumericTypes;
3086TYPED_TEST_CASE(TypedTest, NumericTypes);
3087
3088TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3089 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3090}
3091
3092template <typename T>
3093class DISABLED_TypedTest : public Test {
3094};
3095
3096TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3097
3098TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3099 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3100}
3101
3102#endif // GTEST_HAS_TYPED_TEST
3103
3104// Tests that disabled type-parameterized tests aren't run.
3105
zhanyong.wan4cd62602009-02-23 23:21:55 +00003106#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00003107
3108template <typename T>
3109class TypedTestP : public Test {
3110};
3111
3112TYPED_TEST_CASE_P(TypedTestP);
3113
3114TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3115 FAIL() << "Unexpected failure: "
3116 << "Disabled type-parameterized test should not run.";
3117}
3118
3119REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3120
3121INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3122
3123template <typename T>
3124class DISABLED_TypedTestP : public Test {
3125};
3126
3127TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3128
3129TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3130 FAIL() << "Unexpected failure: "
3131 << "Disabled type-parameterized test should not run.";
3132}
3133
3134REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3135
3136INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3137
3138#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00003139
3140// Tests that assertion macros evaluate their arguments exactly once.
3141
shiqian760af5c2008-08-06 21:43:15 +00003142class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00003143 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003144 // This helper function is needed by the FailedASSERT_STREQ test
3145 // below. It's public to work around C++Builder's bug with scoping local
3146 // classes.
3147 static void CompareAndIncrementCharPtrs() {
3148 ASSERT_STREQ(p1_++, p2_++);
3149 }
3150
3151 // This helper function is needed by the FailedASSERT_NE test below. It's
3152 // public to work around C++Builder's bug with scoping local classes.
3153 static void CompareAndIncrementInts() {
3154 ASSERT_NE(a_++, b_++);
3155 }
3156
shiqian4b6829f2008-07-03 22:38:12 +00003157 protected:
3158 SingleEvaluationTest() {
3159 p1_ = s1_;
3160 p2_ = s2_;
3161 a_ = 0;
3162 b_ = 0;
3163 }
3164
shiqian4b6829f2008-07-03 22:38:12 +00003165 static const char* const s1_;
3166 static const char* const s2_;
3167 static const char* p1_;
3168 static const char* p2_;
3169
3170 static int a_;
3171 static int b_;
3172};
3173
3174const char* const SingleEvaluationTest::s1_ = "01234";
3175const char* const SingleEvaluationTest::s2_ = "abcde";
3176const char* SingleEvaluationTest::p1_;
3177const char* SingleEvaluationTest::p2_;
3178int SingleEvaluationTest::a_;
3179int SingleEvaluationTest::b_;
3180
3181// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3182// exactly once.
3183TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003184 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003185 "p2_++");
3186 EXPECT_EQ(s1_ + 1, p1_);
3187 EXPECT_EQ(s2_ + 1, p2_);
3188}
3189
3190// Tests that string assertion arguments are evaluated exactly once.
3191TEST_F(SingleEvaluationTest, ASSERT_STR) {
3192 // successful EXPECT_STRNE
3193 EXPECT_STRNE(p1_++, p2_++);
3194 EXPECT_EQ(s1_ + 1, p1_);
3195 EXPECT_EQ(s2_ + 1, p2_);
3196
3197 // failed EXPECT_STRCASEEQ
3198 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3199 "ignoring case");
3200 EXPECT_EQ(s1_ + 2, p1_);
3201 EXPECT_EQ(s2_ + 2, p2_);
3202}
3203
3204// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3205// once.
3206TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003207 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3208 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003209 EXPECT_EQ(1, a_);
3210 EXPECT_EQ(1, b_);
3211}
3212
3213// Tests that assertion arguments are evaluated exactly once.
3214TEST_F(SingleEvaluationTest, OtherCases) {
3215 // successful EXPECT_TRUE
3216 EXPECT_TRUE(0 == a_++); // NOLINT
3217 EXPECT_EQ(1, a_);
3218
3219 // failed EXPECT_TRUE
3220 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3221 EXPECT_EQ(2, a_);
3222
3223 // successful EXPECT_GT
3224 EXPECT_GT(a_++, b_++);
3225 EXPECT_EQ(3, a_);
3226 EXPECT_EQ(1, b_);
3227
3228 // failed EXPECT_LT
3229 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3230 EXPECT_EQ(4, a_);
3231 EXPECT_EQ(2, b_);
3232
3233 // successful ASSERT_TRUE
3234 ASSERT_TRUE(0 < a_++); // NOLINT
3235 EXPECT_EQ(5, a_);
3236
3237 // successful ASSERT_GT
3238 ASSERT_GT(a_++, b_++);
3239 EXPECT_EQ(6, a_);
3240 EXPECT_EQ(3, b_);
3241}
3242
shiqian9204c8e2008-09-12 20:57:22 +00003243#if GTEST_HAS_EXCEPTIONS
3244
3245void ThrowAnInteger() {
3246 throw 1;
3247}
3248
3249// Tests that assertion arguments are evaluated exactly once.
3250TEST_F(SingleEvaluationTest, ExceptionTests) {
3251 // successful EXPECT_THROW
3252 EXPECT_THROW({ // NOLINT
3253 a_++;
3254 ThrowAnInteger();
3255 }, int);
3256 EXPECT_EQ(1, a_);
3257
3258 // failed EXPECT_THROW, throws different
3259 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3260 a_++;
3261 ThrowAnInteger();
3262 }, bool), "throws a different type");
3263 EXPECT_EQ(2, a_);
3264
3265 // failed EXPECT_THROW, throws nothing
3266 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3267 EXPECT_EQ(3, a_);
3268
3269 // successful EXPECT_NO_THROW
3270 EXPECT_NO_THROW(a_++);
3271 EXPECT_EQ(4, a_);
3272
3273 // failed EXPECT_NO_THROW
3274 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3275 a_++;
3276 ThrowAnInteger();
3277 }), "it throws");
3278 EXPECT_EQ(5, a_);
3279
3280 // successful EXPECT_ANY_THROW
3281 EXPECT_ANY_THROW({ // NOLINT
3282 a_++;
3283 ThrowAnInteger();
3284 });
3285 EXPECT_EQ(6, a_);
3286
3287 // failed EXPECT_ANY_THROW
3288 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3289 EXPECT_EQ(7, a_);
3290}
3291
3292#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003293
shiqiane44602e2008-10-11 07:20:02 +00003294// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3295class NoFatalFailureTest : public Test {
3296 protected:
3297 void Succeeds() {}
3298 void FailsNonFatal() {
3299 ADD_FAILURE() << "some non-fatal failure";
3300 }
3301 void Fails() {
3302 FAIL() << "some fatal failure";
3303 }
3304
3305 void DoAssertNoFatalFailureOnFails() {
3306 ASSERT_NO_FATAL_FAILURE(Fails());
3307 ADD_FAILURE() << "shold not reach here.";
3308 }
3309
3310 void DoExpectNoFatalFailureOnFails() {
3311 EXPECT_NO_FATAL_FAILURE(Fails());
3312 ADD_FAILURE() << "other failure";
3313 }
3314};
3315
3316TEST_F(NoFatalFailureTest, NoFailure) {
3317 EXPECT_NO_FATAL_FAILURE(Succeeds());
3318 ASSERT_NO_FATAL_FAILURE(Succeeds());
3319}
3320
3321TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3322 EXPECT_NONFATAL_FAILURE(
3323 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3324 "some non-fatal failure");
3325 EXPECT_NONFATAL_FAILURE(
3326 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3327 "some non-fatal failure");
3328}
3329
3330TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3331 TestPartResultArray gtest_failures;
3332 {
3333 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3334 DoAssertNoFatalFailureOnFails();
3335 }
3336 ASSERT_EQ(2, gtest_failures.size());
3337 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3338 gtest_failures.GetTestPartResult(0).type());
3339 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3340 gtest_failures.GetTestPartResult(1).type());
3341 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3342 gtest_failures.GetTestPartResult(0).message());
3343 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3344 gtest_failures.GetTestPartResult(1).message());
3345}
3346
3347TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3348 TestPartResultArray gtest_failures;
3349 {
3350 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3351 DoExpectNoFatalFailureOnFails();
3352 }
3353 ASSERT_EQ(3, gtest_failures.size());
3354 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3355 gtest_failures.GetTestPartResult(0).type());
3356 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3357 gtest_failures.GetTestPartResult(1).type());
3358 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3359 gtest_failures.GetTestPartResult(2).type());
3360 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3361 gtest_failures.GetTestPartResult(0).message());
3362 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3363 gtest_failures.GetTestPartResult(1).message());
3364 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3365 gtest_failures.GetTestPartResult(2).message());
3366}
3367
3368TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3369 TestPartResultArray gtest_failures;
3370 {
3371 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3372 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3373 }
3374 ASSERT_EQ(2, gtest_failures.size());
3375 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3376 gtest_failures.GetTestPartResult(0).type());
3377 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3378 gtest_failures.GetTestPartResult(1).type());
3379 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3380 gtest_failures.GetTestPartResult(0).message());
3381 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3382 gtest_failures.GetTestPartResult(1).message());
3383}
3384
shiqian4b6829f2008-07-03 22:38:12 +00003385// Tests non-string assertions.
3386
3387// Tests EqFailure(), used for implementing *EQ* assertions.
3388TEST(AssertionTest, EqFailure) {
3389 const String foo_val("5"), bar_val("6");
3390 const String msg1(
3391 EqFailure("foo", "bar", foo_val, bar_val, false)
3392 .failure_message());
3393 EXPECT_STREQ(
3394 "Value of: bar\n"
3395 " Actual: 6\n"
3396 "Expected: foo\n"
3397 "Which is: 5",
3398 msg1.c_str());
3399
3400 const String msg2(
3401 EqFailure("foo", "6", foo_val, bar_val, false)
3402 .failure_message());
3403 EXPECT_STREQ(
3404 "Value of: 6\n"
3405 "Expected: foo\n"
3406 "Which is: 5",
3407 msg2.c_str());
3408
3409 const String msg3(
3410 EqFailure("5", "bar", foo_val, bar_val, false)
3411 .failure_message());
3412 EXPECT_STREQ(
3413 "Value of: bar\n"
3414 " Actual: 6\n"
3415 "Expected: 5",
3416 msg3.c_str());
3417
3418 const String msg4(
3419 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3420 EXPECT_STREQ(
3421 "Value of: 6\n"
3422 "Expected: 5",
3423 msg4.c_str());
3424
3425 const String msg5(
3426 EqFailure("foo", "bar",
3427 String("\"x\""), String("\"y\""),
3428 true).failure_message());
3429 EXPECT_STREQ(
3430 "Value of: bar\n"
3431 " Actual: \"y\"\n"
3432 "Expected: foo (ignoring case)\n"
3433 "Which is: \"x\"",
3434 msg5.c_str());
3435}
3436
3437// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3438TEST(AssertionTest, AppendUserMessage) {
3439 const String foo("foo");
3440
shiqian760af5c2008-08-06 21:43:15 +00003441 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003442 EXPECT_STREQ("foo",
3443 AppendUserMessage(foo, msg).c_str());
3444
3445 msg << "bar";
3446 EXPECT_STREQ("foo\nbar",
3447 AppendUserMessage(foo, msg).c_str());
3448}
3449
zhanyong.wan98efcc42009-04-28 00:28:09 +00003450#ifdef __BORLANDC__
3451// Silences warnings: "Condition is always true", "Unreachable code"
3452#pragma option push -w-ccc -w-rch
3453#endif
3454
shiqian4b6829f2008-07-03 22:38:12 +00003455// Tests ASSERT_TRUE.
3456TEST(AssertionTest, ASSERT_TRUE) {
3457 ASSERT_TRUE(2 > 1); // NOLINT
3458 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3459 "2 < 1");
3460}
3461
3462// Tests ASSERT_FALSE.
3463TEST(AssertionTest, ASSERT_FALSE) {
3464 ASSERT_FALSE(2 < 1); // NOLINT
3465 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3466 "Value of: 2 > 1\n"
3467 " Actual: true\n"
3468 "Expected: false");
3469}
3470
zhanyong.wan98efcc42009-04-28 00:28:09 +00003471#ifdef __BORLANDC__
3472// Restores warnings after previous "#pragma option push" supressed them
3473#pragma option pop
3474#endif
3475
shiqian4b6829f2008-07-03 22:38:12 +00003476// Tests using ASSERT_EQ on double values. The purpose is to make
3477// sure that the specialization we did for integer and anonymous enums
3478// isn't used for double arguments.
3479TEST(ExpectTest, ASSERT_EQ_Double) {
3480 // A success.
3481 ASSERT_EQ(5.6, 5.6);
3482
3483 // A failure.
3484 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3485 "5.1");
3486}
3487
3488// Tests ASSERT_EQ.
3489TEST(AssertionTest, ASSERT_EQ) {
3490 ASSERT_EQ(5, 2 + 3);
3491 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3492 "Value of: 2*3\n"
3493 " Actual: 6\n"
3494 "Expected: 5");
3495}
3496
3497// Tests ASSERT_EQ(NULL, pointer).
zhanyong.wan4cd62602009-02-23 23:21:55 +00003498#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003499// The NULL-detection template magic fails to compile with
3500// the Nokia compiler and crashes the ARM compiler, hence
3501// not testing on Symbian.
3502TEST(AssertionTest, ASSERT_EQ_NULL) {
3503 // A success.
3504 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003505 // Some older GCC versions may issue a spurious waring in this or the next
3506 // assertion statement. This warning should not be suppressed with
3507 // static_cast since the test verifies the ability to use bare NULL as the
3508 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003509 ASSERT_EQ(NULL, p);
3510
3511 // A failure.
3512 static int n = 0;
3513 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3514 "Value of: &n\n");
3515}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003516#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003517
3518// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3519// treated as a null pointer by the compiler, we need to make sure
3520// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3521// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3522TEST(ExpectTest, ASSERT_EQ_0) {
3523 int n = 0;
3524
3525 // A success.
3526 ASSERT_EQ(0, n);
3527
3528 // A failure.
3529 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3530 "Expected: 0");
3531}
3532
3533// Tests ASSERT_NE.
3534TEST(AssertionTest, ASSERT_NE) {
3535 ASSERT_NE(6, 7);
3536 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3537 "Expected: ('a') != ('a'), "
3538 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3539}
3540
3541// Tests ASSERT_LE.
3542TEST(AssertionTest, ASSERT_LE) {
3543 ASSERT_LE(2, 3);
3544 ASSERT_LE(2, 2);
3545 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3546 "Expected: (2) <= (0), actual: 2 vs 0");
3547}
3548
3549// Tests ASSERT_LT.
3550TEST(AssertionTest, ASSERT_LT) {
3551 ASSERT_LT(2, 3);
3552 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3553 "Expected: (2) < (2), actual: 2 vs 2");
3554}
3555
3556// Tests ASSERT_GE.
3557TEST(AssertionTest, ASSERT_GE) {
3558 ASSERT_GE(2, 1);
3559 ASSERT_GE(2, 2);
3560 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3561 "Expected: (2) >= (3), actual: 2 vs 3");
3562}
3563
3564// Tests ASSERT_GT.
3565TEST(AssertionTest, ASSERT_GT) {
3566 ASSERT_GT(2, 1);
3567 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3568 "Expected: (2) > (2), actual: 2 vs 2");
3569}
3570
shiqian9204c8e2008-09-12 20:57:22 +00003571#if GTEST_HAS_EXCEPTIONS
3572
zhanyong.wanac60cef2009-02-08 04:53:35 +00003573void ThrowNothing() {}
3574
shiqian9204c8e2008-09-12 20:57:22 +00003575// Tests ASSERT_THROW.
3576TEST(AssertionTest, ASSERT_THROW) {
3577 ASSERT_THROW(ThrowAnInteger(), int);
zhanyong.wan98efcc42009-04-28 00:28:09 +00003578#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 || defined(_DEBUG)
3579 // ICE's in C++Builder 2007 (Release build).
zhanyong.wanac60cef2009-02-08 04:53:35 +00003580 EXPECT_FATAL_FAILURE(
3581 ASSERT_THROW(ThrowAnInteger(), bool),
3582 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3583 " Actual: it throws a different type.");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003584#endif
zhanyong.wanac60cef2009-02-08 04:53:35 +00003585 EXPECT_FATAL_FAILURE(
3586 ASSERT_THROW(ThrowNothing(), bool),
3587 "Expected: ThrowNothing() throws an exception of type bool.\n"
3588 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003589}
3590
3591// Tests ASSERT_NO_THROW.
3592TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003593 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003594 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003595 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003596 "\n Actual: it throws.");
3597}
3598
3599// Tests ASSERT_ANY_THROW.
3600TEST(AssertionTest, ASSERT_ANY_THROW) {
3601 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003602 EXPECT_FATAL_FAILURE(
3603 ASSERT_ANY_THROW(ThrowNothing()),
3604 "Expected: ThrowNothing() throws an exception.\n"
3605 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003606}
3607
3608#endif // GTEST_HAS_EXCEPTIONS
3609
shiqian4b6829f2008-07-03 22:38:12 +00003610// Makes sure we deal with the precedence of <<. This test should
3611// compile.
3612TEST(AssertionTest, AssertPrecedence) {
3613 ASSERT_EQ(1 < 2, true);
3614 ASSERT_EQ(true && false, false);
3615}
3616
3617// A subroutine used by the following test.
3618void TestEq1(int x) {
3619 ASSERT_EQ(1, x);
3620}
3621
3622// Tests calling a test subroutine that's not part of a fixture.
3623TEST(AssertionTest, NonFixtureSubroutine) {
3624 EXPECT_FATAL_FAILURE(TestEq1(2),
3625 "Value of: x");
3626}
3627
3628// An uncopyable class.
3629class Uncopyable {
3630 public:
3631 explicit Uncopyable(int value) : value_(value) {}
3632
3633 int value() const { return value_; }
3634 bool operator==(const Uncopyable& rhs) const {
3635 return value() == rhs.value();
3636 }
3637 private:
3638 // This constructor deliberately has no implementation, as we don't
3639 // want this class to be copyable.
3640 Uncopyable(const Uncopyable&); // NOLINT
3641
3642 int value_;
3643};
3644
3645::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3646 return os << value.value();
3647}
3648
3649
3650bool IsPositiveUncopyable(const Uncopyable& x) {
3651 return x.value() > 0;
3652}
3653
3654// A subroutine used by the following test.
3655void TestAssertNonPositive() {
3656 Uncopyable y(-1);
3657 ASSERT_PRED1(IsPositiveUncopyable, y);
3658}
3659// A subroutine used by the following test.
3660void TestAssertEqualsUncopyable() {
3661 Uncopyable x(5);
3662 Uncopyable y(-1);
3663 ASSERT_EQ(x, y);
3664}
3665
3666// Tests that uncopyable objects can be used in assertions.
3667TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3668 Uncopyable x(5);
3669 ASSERT_PRED1(IsPositiveUncopyable, x);
3670 ASSERT_EQ(x, x);
3671 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3672 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3673 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3674 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3675}
3676
3677// Tests that uncopyable objects can be used in expects.
3678TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3679 Uncopyable x(5);
3680 EXPECT_PRED1(IsPositiveUncopyable, x);
3681 Uncopyable y(-1);
3682 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3683 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3684 EXPECT_EQ(x, x);
3685 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3686 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3687}
3688
3689
3690// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003691// anonymous enums in assertions. Therefore the following test is not
3692// done on Mac.
3693#if !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003694
3695// Tests using assertions with anonymous enums.
3696enum {
3697 CASE_A = -1,
zhanyong.wan4cd62602009-02-23 23:21:55 +00003698#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003699 // We want to test the case where the size of the anonymous enum is
3700 // larger than sizeof(int), to make sure our implementation of the
3701 // assertions doesn't truncate the enums. However, MSVC
3702 // (incorrectly) doesn't allow an enum value to exceed the range of
3703 // an int, so this has to be conditionally compiled.
3704 //
3705 // On Linux, CASE_B and CASE_A have the same value when truncated to
3706 // int size. We want to test whether this will confuse the
3707 // assertions.
shiqian760af5c2008-08-06 21:43:15 +00003708 CASE_B = testing::internal::kMaxBiggestInt,
shiqian4b6829f2008-07-03 22:38:12 +00003709#else
3710 CASE_B = INT_MAX,
3711#endif // GTEST_OS_LINUX
3712};
3713
3714TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003715#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003716 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
3717#endif // GTEST_OS_LINUX
3718
3719 EXPECT_EQ(CASE_A, CASE_A);
3720 EXPECT_NE(CASE_A, CASE_B);
3721 EXPECT_LT(CASE_A, CASE_B);
3722 EXPECT_LE(CASE_A, CASE_B);
3723 EXPECT_GT(CASE_B, CASE_A);
3724 EXPECT_GE(CASE_A, CASE_A);
3725 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
3726 "(CASE_A) >= (CASE_B)");
3727
3728 ASSERT_EQ(CASE_A, CASE_A);
3729 ASSERT_NE(CASE_A, CASE_B);
3730 ASSERT_LT(CASE_A, CASE_B);
3731 ASSERT_LE(CASE_A, CASE_B);
3732 ASSERT_GT(CASE_B, CASE_A);
3733 ASSERT_GE(CASE_A, CASE_A);
3734 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
3735 "Value of: CASE_B");
3736}
3737
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003738#endif // !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003739
zhanyong.wan4cd62602009-02-23 23:21:55 +00003740#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003741
3742static HRESULT UnexpectedHRESULTFailure() {
3743 return E_UNEXPECTED;
3744}
3745
3746static HRESULT OkHRESULTSuccess() {
3747 return S_OK;
3748}
3749
3750static HRESULT FalseHRESULTSuccess() {
3751 return S_FALSE;
3752}
3753
3754// HRESULT assertion tests test both zero and non-zero
3755// success codes as well as failure message for each.
3756//
3757// Windows CE doesn't support message texts.
3758TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3759 EXPECT_HRESULT_SUCCEEDED(S_OK);
3760 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3761
shiqian4b6829f2008-07-03 22:38:12 +00003762 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003763 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3764 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003765}
3766
3767TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3768 ASSERT_HRESULT_SUCCEEDED(S_OK);
3769 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3770
shiqian4b6829f2008-07-03 22:38:12 +00003771 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003772 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3773 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003774}
3775
3776TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3777 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3778
shiqian4b6829f2008-07-03 22:38:12 +00003779 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003780 "Expected: (OkHRESULTSuccess()) fails.\n"
3781 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00003782 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003783 "Expected: (FalseHRESULTSuccess()) fails.\n"
3784 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003785}
3786
3787TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3788 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3789
zhanyong.wan98efcc42009-04-28 00:28:09 +00003790#ifndef __BORLANDC__
3791 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003792 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003793 "Expected: (OkHRESULTSuccess()) fails.\n"
3794 " Actual: 0x00000000");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003795#endif
shiqian4b6829f2008-07-03 22:38:12 +00003796 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003797 "Expected: (FalseHRESULTSuccess()) fails.\n"
3798 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003799}
3800
3801// Tests that streaming to the HRESULT macros works.
3802TEST(HRESULTAssertionTest, Streaming) {
3803 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3804 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3805 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3806 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3807
3808 EXPECT_NONFATAL_FAILURE(
3809 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3810 "expected failure");
3811
zhanyong.wan98efcc42009-04-28 00:28:09 +00003812#ifndef __BORLANDC__
3813 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003814 EXPECT_FATAL_FAILURE(
3815 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3816 "expected failure");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003817#endif
shiqian4b6829f2008-07-03 22:38:12 +00003818
3819 EXPECT_NONFATAL_FAILURE(
3820 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3821 "expected failure");
3822
3823 EXPECT_FATAL_FAILURE(
3824 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3825 "expected failure");
3826}
3827
zhanyong.wan4cd62602009-02-23 23:21:55 +00003828#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003829
zhanyong.wan98efcc42009-04-28 00:28:09 +00003830#ifdef __BORLANDC__
3831// Silences warnings: "Condition is always true", "Unreachable code"
3832#pragma option push -w-ccc -w-rch
3833#endif
3834
shiqian4b6829f2008-07-03 22:38:12 +00003835// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003836TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
shiqian4b6829f2008-07-03 22:38:12 +00003837 if (false)
3838 ASSERT_TRUE(false) << "This should never be executed; "
3839 "It's a compilation test only.";
3840
3841 if (true)
3842 EXPECT_FALSE(false);
3843 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003844 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003845
3846 if (false)
3847 ASSERT_LT(1, 3);
3848
3849 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003850 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003851 else
3852 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00003853}
shiqian9204c8e2008-09-12 20:57:22 +00003854
3855#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00003856// Tests that the compiler will not complain about unreachable code in the
3857// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3858TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3859 int n = 0;
3860
3861 EXPECT_THROW(throw 1, int);
3862 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3863 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3864 EXPECT_NO_THROW(n++);
3865 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3866 EXPECT_ANY_THROW(throw 1);
3867 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3868}
3869
shiqiane44602e2008-10-11 07:20:02 +00003870TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
shiqian9204c8e2008-09-12 20:57:22 +00003871 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003872 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00003873
3874 if (true)
3875 EXPECT_THROW(ThrowAnInteger(), int);
3876 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003877 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003878
3879 if (false)
3880 EXPECT_NO_THROW(ThrowAnInteger());
3881
3882 if (true)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003883 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003884 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003885 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003886
3887 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003888 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003889
3890 if (true)
3891 EXPECT_ANY_THROW(ThrowAnInteger());
3892 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003893 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003894}
shiqian9204c8e2008-09-12 20:57:22 +00003895#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00003896
3897TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
3898 if (false)
3899 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
3900 << "It's a compilation test only.";
3901 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003902 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003903
3904 if (false)
3905 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
3906 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003907 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003908
3909 if (true)
3910 EXPECT_NO_FATAL_FAILURE(SUCCEED());
3911 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003912 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003913
3914 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003915 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003916 else
3917 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00003918}
3919
3920// Tests that the assertion macros work well with switch statements.
3921TEST(AssertionSyntaxTest, WorksWithSwitch) {
3922 switch (0) {
3923 case 1:
3924 break;
3925 default:
3926 ASSERT_TRUE(true);
3927 }
3928
3929 switch (0)
3930 case 0:
3931 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
3932
3933 // Binary assertions are implemented using a different code path
3934 // than the Boolean assertions. Hence we test them separately.
3935 switch (0) {
3936 case 1:
3937 default:
3938 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
3939 }
3940
3941 switch (0)
3942 case 0:
3943 EXPECT_NE(1, 2);
3944}
3945
shiqian9204c8e2008-09-12 20:57:22 +00003946#if GTEST_HAS_EXCEPTIONS
3947
3948void ThrowAString() {
3949 throw "String";
3950}
3951
3952// Test that the exception assertion macros compile and work with const
3953// type qualifier.
3954TEST(AssertionSyntaxTest, WorksWithConst) {
3955 ASSERT_THROW(ThrowAString(), const char*);
3956
3957 EXPECT_THROW(ThrowAString(), const char*);
3958}
3959
3960#endif // GTEST_HAS_EXCEPTIONS
3961
shiqian4b6829f2008-07-03 22:38:12 +00003962} // namespace
3963
shiqian4b6829f2008-07-03 22:38:12 +00003964namespace testing {
3965
3966// Tests that Google Test tracks SUCCEED*.
3967TEST(SuccessfulAssertionTest, SUCCEED) {
3968 SUCCEED();
3969 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003970 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003971}
3972
3973// Tests that Google Test doesn't track successful EXPECT_*.
3974TEST(SuccessfulAssertionTest, EXPECT) {
3975 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003976 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003977}
3978
3979// Tests that Google Test doesn't track successful EXPECT_STR*.
3980TEST(SuccessfulAssertionTest, EXPECT_STR) {
3981 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003982 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003983}
3984
3985// Tests that Google Test doesn't track successful ASSERT_*.
3986TEST(SuccessfulAssertionTest, ASSERT) {
3987 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003988 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003989}
3990
3991// Tests that Google Test doesn't track successful ASSERT_STR*.
3992TEST(SuccessfulAssertionTest, ASSERT_STR) {
3993 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003994 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003995}
3996
3997} // namespace testing
3998
3999namespace {
4000
4001// Tests EXPECT_TRUE.
4002TEST(ExpectTest, EXPECT_TRUE) {
4003 EXPECT_TRUE(2 > 1); // NOLINT
4004 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4005 "Value of: 2 < 1\n"
4006 " Actual: false\n"
4007 "Expected: true");
4008 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4009 "2 > 3");
4010}
4011
4012// Tests EXPECT_FALSE.
4013TEST(ExpectTest, EXPECT_FALSE) {
4014 EXPECT_FALSE(2 < 1); // NOLINT
4015 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4016 "Value of: 2 > 1\n"
4017 " Actual: true\n"
4018 "Expected: false");
4019 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4020 "2 < 3");
4021}
4022
zhanyong.wan98efcc42009-04-28 00:28:09 +00004023#ifdef __BORLANDC__
4024// Restores warnings after previous "#pragma option push" supressed them
4025#pragma option pop
4026#endif
4027
shiqian4b6829f2008-07-03 22:38:12 +00004028// Tests EXPECT_EQ.
4029TEST(ExpectTest, EXPECT_EQ) {
4030 EXPECT_EQ(5, 2 + 3);
4031 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4032 "Value of: 2*3\n"
4033 " Actual: 6\n"
4034 "Expected: 5");
4035 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4036 "2 - 3");
4037}
4038
4039// Tests using EXPECT_EQ on double values. The purpose is to make
4040// sure that the specialization we did for integer and anonymous enums
4041// isn't used for double arguments.
4042TEST(ExpectTest, EXPECT_EQ_Double) {
4043 // A success.
4044 EXPECT_EQ(5.6, 5.6);
4045
4046 // A failure.
4047 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4048 "5.1");
4049}
4050
zhanyong.wan4cd62602009-02-23 23:21:55 +00004051#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00004052// Tests EXPECT_EQ(NULL, pointer).
4053TEST(ExpectTest, EXPECT_EQ_NULL) {
4054 // A success.
4055 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00004056 // Some older GCC versions may issue a spurious waring in this or the next
4057 // assertion statement. This warning should not be suppressed with
4058 // static_cast since the test verifies the ability to use bare NULL as the
4059 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00004060 EXPECT_EQ(NULL, p);
4061
4062 // A failure.
4063 int n = 0;
4064 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4065 "Value of: &n\n");
4066}
zhanyong.wan4cd62602009-02-23 23:21:55 +00004067#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00004068
4069// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4070// treated as a null pointer by the compiler, we need to make sure
4071// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4072// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4073TEST(ExpectTest, EXPECT_EQ_0) {
4074 int n = 0;
4075
4076 // A success.
4077 EXPECT_EQ(0, n);
4078
4079 // A failure.
4080 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4081 "Expected: 0");
4082}
4083
4084// Tests EXPECT_NE.
4085TEST(ExpectTest, EXPECT_NE) {
4086 EXPECT_NE(6, 7);
4087
4088 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4089 "Expected: ('a') != ('a'), "
4090 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4091 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4092 "2");
4093 char* const p0 = NULL;
4094 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4095 "p0");
4096 // Only way to get the Nokia compiler to compile the cast
4097 // is to have a separate void* variable first. Putting
4098 // the two casts on the same line doesn't work, neither does
4099 // a direct C-style to char*.
4100 void* pv1 = (void*)0x1234; // NOLINT
4101 char* const p1 = reinterpret_cast<char*>(pv1);
4102 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4103 "p1");
4104}
4105
4106// Tests EXPECT_LE.
4107TEST(ExpectTest, EXPECT_LE) {
4108 EXPECT_LE(2, 3);
4109 EXPECT_LE(2, 2);
4110 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4111 "Expected: (2) <= (0), actual: 2 vs 0");
4112 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4113 "(1.1) <= (0.9)");
4114}
4115
4116// Tests EXPECT_LT.
4117TEST(ExpectTest, EXPECT_LT) {
4118 EXPECT_LT(2, 3);
4119 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4120 "Expected: (2) < (2), actual: 2 vs 2");
4121 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4122 "(2) < (1)");
4123}
4124
4125// Tests EXPECT_GE.
4126TEST(ExpectTest, EXPECT_GE) {
4127 EXPECT_GE(2, 1);
4128 EXPECT_GE(2, 2);
4129 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4130 "Expected: (2) >= (3), actual: 2 vs 3");
4131 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4132 "(0.9) >= (1.1)");
4133}
4134
4135// Tests EXPECT_GT.
4136TEST(ExpectTest, EXPECT_GT) {
4137 EXPECT_GT(2, 1);
4138 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4139 "Expected: (2) > (2), actual: 2 vs 2");
4140 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4141 "(2) > (3)");
4142}
4143
shiqian9204c8e2008-09-12 20:57:22 +00004144#if GTEST_HAS_EXCEPTIONS
4145
4146// Tests EXPECT_THROW.
4147TEST(ExpectTest, EXPECT_THROW) {
4148 EXPECT_THROW(ThrowAnInteger(), int);
4149 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004150 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00004151 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00004152 EXPECT_NONFATAL_FAILURE(
4153 EXPECT_THROW(ThrowNothing(), bool),
4154 "Expected: ThrowNothing() throws an exception of type bool.\n"
4155 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00004156}
4157
4158// Tests EXPECT_NO_THROW.
4159TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00004160 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004161 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004162 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00004163 "exception.\n Actual: it throws.");
4164}
4165
4166// Tests EXPECT_ANY_THROW.
4167TEST(ExpectTest, EXPECT_ANY_THROW) {
4168 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004169 EXPECT_NONFATAL_FAILURE(
4170 EXPECT_ANY_THROW(ThrowNothing()),
4171 "Expected: ThrowNothing() throws an exception.\n"
4172 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004173}
4174
4175#endif // GTEST_HAS_EXCEPTIONS
4176
shiqian4b6829f2008-07-03 22:38:12 +00004177// Make sure we deal with the precedence of <<.
4178TEST(ExpectTest, ExpectPrecedence) {
4179 EXPECT_EQ(1 < 2, true);
4180 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4181 "Value of: true && false");
4182}
4183
4184
4185// Tests the StreamableToString() function.
4186
4187// Tests using StreamableToString() on a scalar.
4188TEST(StreamableToStringTest, Scalar) {
4189 EXPECT_STREQ("5", StreamableToString(5).c_str());
4190}
4191
4192// Tests using StreamableToString() on a non-char pointer.
4193TEST(StreamableToStringTest, Pointer) {
4194 int n = 0;
4195 int* p = &n;
4196 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4197}
4198
4199// Tests using StreamableToString() on a NULL non-char pointer.
4200TEST(StreamableToStringTest, NullPointer) {
4201 int* p = NULL;
4202 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4203}
4204
4205// Tests using StreamableToString() on a C string.
4206TEST(StreamableToStringTest, CString) {
4207 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4208}
4209
4210// Tests using StreamableToString() on a NULL C string.
4211TEST(StreamableToStringTest, NullCString) {
4212 char* p = NULL;
4213 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4214}
4215
4216// Tests using streamable values as assertion messages.
4217
4218#if GTEST_HAS_STD_STRING
4219// Tests using std::string as an assertion message.
4220TEST(StreamableTest, string) {
4221 static const std::string str(
4222 "This failure message is a std::string, and is expected.");
4223 EXPECT_FATAL_FAILURE(FAIL() << str,
4224 str.c_str());
4225}
4226
4227// Tests that we can output strings containing embedded NULs.
4228// Limited to Linux because we can only do this with std::string's.
4229TEST(StreamableTest, stringWithEmbeddedNUL) {
4230 static const char char_array_with_nul[] =
4231 "Here's a NUL\0 and some more string";
4232 static const std::string string_with_nul(char_array_with_nul,
4233 sizeof(char_array_with_nul)
4234 - 1); // drops the trailing NUL
4235 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4236 "Here's a NUL\\0 and some more string");
4237}
4238
4239#endif // GTEST_HAS_STD_STRING
4240
4241// Tests that we can output a NUL char.
4242TEST(StreamableTest, NULChar) {
4243 EXPECT_FATAL_FAILURE({ // NOLINT
4244 FAIL() << "A NUL" << '\0' << " and some more string";
4245 }, "A NUL\\0 and some more string");
4246}
4247
4248// Tests using int as an assertion message.
4249TEST(StreamableTest, int) {
4250 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4251 "900913");
4252}
4253
4254// Tests using NULL char pointer as an assertion message.
4255//
4256// In MSVC, streaming a NULL char * causes access violation. Google Test
4257// implemented a workaround (substituting "(null)" for NULL). This
4258// tests whether the workaround works.
4259TEST(StreamableTest, NullCharPtr) {
4260 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4261 "(null)");
4262}
4263
4264// Tests that basic IO manipulators (endl, ends, and flush) can be
4265// streamed to testing::Message.
4266TEST(StreamableTest, BasicIoManip) {
4267 EXPECT_FATAL_FAILURE({ // NOLINT
4268 FAIL() << "Line 1." << std::endl
4269 << "A NUL char " << std::ends << std::flush << " in line 2.";
4270 }, "Line 1.\nA NUL char \\0 in line 2.");
4271}
4272
shiqian4b6829f2008-07-03 22:38:12 +00004273// Tests the macros that haven't been covered so far.
4274
4275void AddFailureHelper(bool* aborted) {
4276 *aborted = true;
4277 ADD_FAILURE() << "Failure";
4278 *aborted = false;
4279}
4280
4281// Tests ADD_FAILURE.
4282TEST(MacroTest, ADD_FAILURE) {
4283 bool aborted = true;
4284 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4285 "Failure");
4286 EXPECT_FALSE(aborted);
4287}
4288
4289// Tests FAIL.
4290TEST(MacroTest, FAIL) {
4291 EXPECT_FATAL_FAILURE(FAIL(),
4292 "Failed");
4293 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4294 "Intentional failure.");
4295}
4296
4297// Tests SUCCEED
4298TEST(MacroTest, SUCCEED) {
4299 SUCCEED();
4300 SUCCEED() << "Explicit success.";
4301}
4302
4303
4304// Tests for EXPECT_EQ() and ASSERT_EQ().
4305//
4306// These tests fail *intentionally*, s.t. the failure messages can be
4307// generated and tested.
4308//
4309// We have different tests for different argument types.
4310
4311// Tests using bool values in {EXPECT|ASSERT}_EQ.
4312TEST(EqAssertionTest, Bool) {
4313 EXPECT_EQ(true, true);
4314 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4315 "Value of: true");
4316}
4317
4318// Tests using int values in {EXPECT|ASSERT}_EQ.
4319TEST(EqAssertionTest, Int) {
4320 ASSERT_EQ(32, 32);
4321 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4322 "33");
4323}
4324
4325// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4326TEST(EqAssertionTest, Time_T) {
4327 EXPECT_EQ(static_cast<time_t>(0),
4328 static_cast<time_t>(0));
4329 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4330 static_cast<time_t>(1234)),
4331 "1234");
4332}
4333
4334// Tests using char values in {EXPECT|ASSERT}_EQ.
4335TEST(EqAssertionTest, Char) {
4336 ASSERT_EQ('z', 'z');
4337 const char ch = 'b';
4338 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4339 "ch");
4340 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4341 "ch");
4342}
4343
4344// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4345TEST(EqAssertionTest, WideChar) {
4346 EXPECT_EQ(L'b', L'b');
4347
4348 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4349 "Value of: L'x'\n"
4350 " Actual: L'x' (120, 0x78)\n"
4351 "Expected: L'\0'\n"
4352 "Which is: L'\0' (0, 0x0)");
4353
4354 static wchar_t wchar;
4355 wchar = L'b';
4356 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4357 "wchar");
4358 wchar = L'\x8119';
4359 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4360 "Value of: wchar");
4361}
4362
4363#if GTEST_HAS_STD_STRING
4364// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4365TEST(EqAssertionTest, StdString) {
4366 // Compares a const char* to an std::string that has identical
4367 // content.
4368 ASSERT_EQ("Test", ::std::string("Test"));
4369
4370 // Compares two identical std::strings.
4371 static const ::std::string str1("A * in the middle");
4372 static const ::std::string str2(str1);
4373 EXPECT_EQ(str1, str2);
4374
4375 // Compares a const char* to an std::string that has different
4376 // content
4377 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4378 "::std::string(\"test\")");
4379
4380 // Compares an std::string to a char* that has different content.
4381 char* const p1 = const_cast<char*>("foo");
4382 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4383 "p1");
4384
4385 // Compares two std::strings that have different contents, one of
4386 // which having a NUL character in the middle. This should fail.
4387 static ::std::string str3(str1);
4388 str3.at(2) = '\0';
4389 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4390 "Value of: str3\n"
4391 " Actual: \"A \\0 in the middle\"");
4392}
4393
4394#endif // GTEST_HAS_STD_STRING
4395
4396#if GTEST_HAS_STD_WSTRING
4397
4398// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4399TEST(EqAssertionTest, StdWideString) {
4400 // Compares an std::wstring to a const wchar_t* that has identical
4401 // content.
4402 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4403
4404 // Compares two identical std::wstrings.
4405 const ::std::wstring wstr1(L"A * in the middle");
4406 const ::std::wstring wstr2(wstr1);
4407 ASSERT_EQ(wstr1, wstr2);
4408
4409 // Compares an std::wstring to a const wchar_t* that has different
4410 // content.
4411 EXPECT_NONFATAL_FAILURE({ // NOLINT
4412 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4413 }, "L\"Test\\x8120\"");
4414
4415 // Compares two std::wstrings that have different contents, one of
4416 // which having a NUL character in the middle.
4417 ::std::wstring wstr3(wstr1);
4418 wstr3.at(2) = L'\0';
4419 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4420 "wstr3");
4421
4422 // Compares a wchar_t* to an std::wstring that has different
4423 // content.
4424 EXPECT_FATAL_FAILURE({ // NOLINT
4425 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4426 }, "");
4427}
4428
4429#endif // GTEST_HAS_STD_WSTRING
4430
4431#if GTEST_HAS_GLOBAL_STRING
4432// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4433TEST(EqAssertionTest, GlobalString) {
4434 // Compares a const char* to a ::string that has identical content.
4435 EXPECT_EQ("Test", ::string("Test"));
4436
4437 // Compares two identical ::strings.
4438 const ::string str1("A * in the middle");
4439 const ::string str2(str1);
4440 ASSERT_EQ(str1, str2);
4441
4442 // Compares a ::string to a const char* that has different content.
4443 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4444 "test");
4445
4446 // Compares two ::strings that have different contents, one of which
4447 // having a NUL character in the middle.
4448 ::string str3(str1);
4449 str3.at(2) = '\0';
4450 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4451 "str3");
4452
4453 // Compares a ::string to a char* that has different content.
4454 EXPECT_FATAL_FAILURE({ // NOLINT
4455 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4456 }, "");
4457}
4458
4459#endif // GTEST_HAS_GLOBAL_STRING
4460
4461#if GTEST_HAS_GLOBAL_WSTRING
4462
4463// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4464TEST(EqAssertionTest, GlobalWideString) {
4465 // Compares a const wchar_t* to a ::wstring that has identical content.
4466 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4467
4468 // Compares two identical ::wstrings.
4469 static const ::wstring wstr1(L"A * in the middle");
4470 static const ::wstring wstr2(wstr1);
4471 EXPECT_EQ(wstr1, wstr2);
4472
4473 // Compares a const wchar_t* to a ::wstring that has different
4474 // content.
4475 EXPECT_NONFATAL_FAILURE({ // NOLINT
4476 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4477 }, "Test\\x8119");
4478
4479 // Compares a wchar_t* to a ::wstring that has different content.
4480 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4481 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4482 "bar");
4483
4484 // Compares two ::wstrings that have different contents, one of which
4485 // having a NUL character in the middle.
4486 static ::wstring wstr3;
4487 wstr3 = wstr1;
4488 wstr3.at(2) = L'\0';
4489 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4490 "wstr3");
4491}
4492
4493#endif // GTEST_HAS_GLOBAL_WSTRING
4494
4495// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4496TEST(EqAssertionTest, CharPointer) {
4497 char* const p0 = NULL;
4498 // Only way to get the Nokia compiler to compile the cast
4499 // is to have a separate void* variable first. Putting
4500 // the two casts on the same line doesn't work, neither does
4501 // a direct C-style to char*.
4502 void* pv1 = (void*)0x1234; // NOLINT
4503 void* pv2 = (void*)0xABC0; // NOLINT
4504 char* const p1 = reinterpret_cast<char*>(pv1);
4505 char* const p2 = reinterpret_cast<char*>(pv2);
4506 ASSERT_EQ(p1, p1);
4507
4508 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4509 "Value of: p2");
4510 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4511 "p2");
4512 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4513 reinterpret_cast<char*>(0xABC0)),
4514 "ABC0");
4515}
4516
4517// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4518TEST(EqAssertionTest, WideCharPointer) {
4519 wchar_t* const p0 = NULL;
4520 // Only way to get the Nokia compiler to compile the cast
4521 // is to have a separate void* variable first. Putting
4522 // the two casts on the same line doesn't work, neither does
4523 // a direct C-style to char*.
4524 void* pv1 = (void*)0x1234; // NOLINT
4525 void* pv2 = (void*)0xABC0; // NOLINT
4526 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4527 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4528 EXPECT_EQ(p0, p0);
4529
4530 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4531 "Value of: p2");
4532 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4533 "p2");
4534 void* pv3 = (void*)0x1234; // NOLINT
4535 void* pv4 = (void*)0xABC0; // NOLINT
4536 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4537 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4538 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4539 "p4");
4540}
4541
4542// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4543TEST(EqAssertionTest, OtherPointer) {
4544 ASSERT_EQ(static_cast<const int*>(NULL),
4545 static_cast<const int*>(NULL));
4546 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4547 reinterpret_cast<const int*>(0x1234)),
4548 "0x1234");
4549}
4550
4551// Tests the FRIEND_TEST macro.
4552
4553// This class has a private member we want to test. We will test it
4554// both in a TEST and in a TEST_F.
4555class Foo {
4556 public:
4557 Foo() {}
4558
4559 private:
4560 int Bar() const { return 1; }
4561
4562 // Declares the friend tests that can access the private member
4563 // Bar().
4564 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4565 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4566};
4567
4568// Tests that the FRIEND_TEST declaration allows a TEST to access a
4569// class's private members. This should compile.
4570TEST(FRIEND_TEST_Test, TEST) {
4571 ASSERT_EQ(1, Foo().Bar());
4572}
4573
4574// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004575class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004576 protected:
4577 Foo foo;
4578};
4579
4580// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4581// class's private members. This should compile.
4582TEST_F(FRIEND_TEST_Test2, TEST_F) {
4583 ASSERT_EQ(1, foo.Bar());
4584}
4585
4586// Tests the life cycle of Test objects.
4587
4588// The test fixture for testing the life cycle of Test objects.
4589//
4590// This class counts the number of live test objects that uses this
4591// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004592class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004593 protected:
4594 // Constructor. Increments the number of test objects that uses
4595 // this fixture.
4596 TestLifeCycleTest() { count_++; }
4597
4598 // Destructor. Decrements the number of test objects that uses this
4599 // fixture.
4600 ~TestLifeCycleTest() { count_--; }
4601
4602 // Returns the number of live test objects that uses this fixture.
4603 int count() const { return count_; }
4604
4605 private:
4606 static int count_;
4607};
4608
4609int TestLifeCycleTest::count_ = 0;
4610
4611// Tests the life cycle of test objects.
4612TEST_F(TestLifeCycleTest, Test1) {
4613 // There should be only one test object in this test case that's
4614 // currently alive.
4615 ASSERT_EQ(1, count());
4616}
4617
4618// Tests the life cycle of test objects.
4619TEST_F(TestLifeCycleTest, Test2) {
4620 // After Test1 is done and Test2 is started, there should still be
4621 // only one live test object, as the object for Test1 should've been
4622 // deleted.
4623 ASSERT_EQ(1, count());
4624}
4625
4626} // namespace
4627
4628// Tests streaming a user type whose definition and operator << are
4629// both in the global namespace.
4630class Base {
4631 public:
4632 explicit Base(int x) : x_(x) {}
4633 int x() const { return x_; }
4634 private:
4635 int x_;
4636};
4637std::ostream& operator<<(std::ostream& os,
4638 const Base& val) {
4639 return os << val.x();
4640}
4641std::ostream& operator<<(std::ostream& os,
4642 const Base* pointer) {
4643 return os << "(" << pointer->x() << ")";
4644}
4645
4646TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004647 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004648 Base a(1);
4649
4650 msg << a << &a; // Uses ::operator<<.
4651 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4652}
4653
4654// Tests streaming a user type whose definition and operator<< are
4655// both in an unnamed namespace.
4656namespace {
4657class MyTypeInUnnamedNameSpace : public Base {
4658 public:
4659 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {}
4660};
4661std::ostream& operator<<(std::ostream& os,
4662 const MyTypeInUnnamedNameSpace& val) {
4663 return os << val.x();
4664}
4665std::ostream& operator<<(std::ostream& os,
4666 const MyTypeInUnnamedNameSpace* pointer) {
4667 return os << "(" << pointer->x() << ")";
4668}
4669} // namespace
4670
4671TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004672 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004673 MyTypeInUnnamedNameSpace a(1);
4674
4675 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4676 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4677}
4678
4679// Tests streaming a user type whose definition and operator<< are
4680// both in a user namespace.
4681namespace namespace1 {
4682class MyTypeInNameSpace1 : public Base {
4683 public:
4684 explicit MyTypeInNameSpace1(int x): Base(x) {}
4685};
4686std::ostream& operator<<(std::ostream& os,
4687 const MyTypeInNameSpace1& val) {
4688 return os << val.x();
4689}
4690std::ostream& operator<<(std::ostream& os,
4691 const MyTypeInNameSpace1* pointer) {
4692 return os << "(" << pointer->x() << ")";
4693}
4694} // namespace namespace1
4695
4696TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004697 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004698 namespace1::MyTypeInNameSpace1 a(1);
4699
4700 msg << a << &a; // Uses namespace1::operator<<.
4701 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4702}
4703
4704// Tests streaming a user type whose definition is in a user namespace
4705// but whose operator<< is in the global namespace.
4706namespace namespace2 {
4707class MyTypeInNameSpace2 : public ::Base {
4708 public:
4709 explicit MyTypeInNameSpace2(int x): Base(x) {}
4710};
4711} // namespace namespace2
4712std::ostream& operator<<(std::ostream& os,
4713 const namespace2::MyTypeInNameSpace2& val) {
4714 return os << val.x();
4715}
4716std::ostream& operator<<(std::ostream& os,
4717 const namespace2::MyTypeInNameSpace2* pointer) {
4718 return os << "(" << pointer->x() << ")";
4719}
4720
4721TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00004722 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004723 namespace2::MyTypeInNameSpace2 a(1);
4724
4725 msg << a << &a; // Uses ::operator<<.
4726 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4727}
4728
4729// Tests streaming NULL pointers to testing::Message.
4730TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00004731 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004732 char* const p1 = NULL;
4733 unsigned char* const p2 = NULL;
4734 int* p3 = NULL;
4735 double* p4 = NULL;
4736 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00004737 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004738
4739 msg << p1 << p2 << p3 << p4 << p5 << p6;
4740 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4741 msg.GetString().c_str());
4742}
4743
4744// Tests streaming wide strings to testing::Message.
4745TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00004746 // Streams a NULL of type const wchar_t*.
4747 const wchar_t* const_wstr = NULL;
4748 EXPECT_STREQ("(null)",
4749 (Message() << const_wstr).GetString().c_str());
4750
4751 // Streams a NULL of type wchar_t*.
4752 wchar_t* wstr = NULL;
4753 EXPECT_STREQ("(null)",
4754 (Message() << wstr).GetString().c_str());
4755
4756 // Streams a non-NULL of type const wchar_t*.
4757 const_wstr = L"abc\x8119";
4758 EXPECT_STREQ("abc\xe8\x84\x99",
4759 (Message() << const_wstr).GetString().c_str());
4760
4761 // Streams a non-NULL of type wchar_t*.
4762 wstr = const_cast<wchar_t*>(const_wstr);
4763 EXPECT_STREQ("abc\xe8\x84\x99",
4764 (Message() << wstr).GetString().c_str());
4765}
4766
4767
4768// This line tests that we can define tests in the testing namespace.
4769namespace testing {
4770
4771// Tests the TestInfo class.
4772
shiqian760af5c2008-08-06 21:43:15 +00004773class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004774 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004775 static const TestInfo* GetTestInfo(const char* test_name) {
4776 const TestCase* const test_case = GetUnitTestImpl()->
4777 GetTestCase("TestInfoTest", "", NULL, NULL);
4778
4779 for (int i = 0; i < test_case->total_test_count(); ++i) {
4780 const TestInfo* const test_info = test_case->GetTestInfo(i);
4781 if (strcmp(test_name, test_info->name()) == 0)
4782 return test_info;
4783 }
4784 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004785 }
4786
4787 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00004788 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00004789 return test_info->result();
4790 }
4791};
4792
4793// Tests TestInfo::test_case_name() and TestInfo::name().
4794TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004795 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00004796
4797 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
4798 ASSERT_STREQ("Names", test_info->name());
4799}
4800
4801// Tests TestInfo::result().
4802TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004803 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00004804
4805 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004806 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004807
4808 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004809 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004810}
4811
4812// Tests setting up and tearing down a test case.
4813
shiqian760af5c2008-08-06 21:43:15 +00004814class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004815 protected:
4816 // This will be called once before the first test in this test case
4817 // is run.
4818 static void SetUpTestCase() {
4819 printf("Setting up the test case . . .\n");
4820
4821 // Initializes some shared resource. In this simple example, we
4822 // just create a C string. More complex stuff can be done if
4823 // desired.
4824 shared_resource_ = "123";
4825
4826 // Increments the number of test cases that have been set up.
4827 counter_++;
4828
4829 // SetUpTestCase() should be called only once.
4830 EXPECT_EQ(1, counter_);
4831 }
4832
4833 // This will be called once after the last test in this test case is
4834 // run.
4835 static void TearDownTestCase() {
4836 printf("Tearing down the test case . . .\n");
4837
4838 // Decrements the number of test cases that have been set up.
4839 counter_--;
4840
4841 // TearDownTestCase() should be called only once.
4842 EXPECT_EQ(0, counter_);
4843
4844 // Cleans up the shared resource.
4845 shared_resource_ = NULL;
4846 }
4847
4848 // This will be called before each test in this test case.
4849 virtual void SetUp() {
4850 // SetUpTestCase() should be called only once, so counter_ should
4851 // always be 1.
4852 EXPECT_EQ(1, counter_);
4853 }
4854
4855 // Number of test cases that have been set up.
4856 static int counter_;
4857
4858 // Some resource to be shared by all tests in this test case.
4859 static const char* shared_resource_;
4860};
4861
4862int SetUpTestCaseTest::counter_ = 0;
4863const char* SetUpTestCaseTest::shared_resource_ = NULL;
4864
4865// A test that uses the shared resource.
4866TEST_F(SetUpTestCaseTest, Test1) {
4867 EXPECT_STRNE(NULL, shared_resource_);
4868}
4869
4870// Another test that uses the shared resource.
4871TEST_F(SetUpTestCaseTest, Test2) {
4872 EXPECT_STREQ("123", shared_resource_);
4873}
4874
4875// The InitGoogleTestTest test case tests testing::InitGoogleTest().
4876
4877// The Flags struct stores a copy of all Google Test flags.
4878struct Flags {
4879 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00004880 Flags() : also_run_disabled_tests(false),
4881 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00004882 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00004883 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00004884 filter(""),
4885 list_tests(false),
4886 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00004887 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004888 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004889 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004890 shuffle(false),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004891 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00004892
4893 // Factory methods.
4894
shiqianca6949f2009-01-10 01:16:33 +00004895 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
4896 // the given value.
4897 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
4898 Flags flags;
4899 flags.also_run_disabled_tests = also_run_disabled_tests;
4900 return flags;
4901 }
4902
shiqian4b6829f2008-07-03 22:38:12 +00004903 // Creates a Flags struct where the gtest_break_on_failure flag has
4904 // the given value.
4905 static Flags BreakOnFailure(bool break_on_failure) {
4906 Flags flags;
4907 flags.break_on_failure = break_on_failure;
4908 return flags;
4909 }
4910
4911 // Creates a Flags struct where the gtest_catch_exceptions flag has
4912 // the given value.
4913 static Flags CatchExceptions(bool catch_exceptions) {
4914 Flags flags;
4915 flags.catch_exceptions = catch_exceptions;
4916 return flags;
4917 }
4918
shiqian21d43d12009-01-08 01:10:31 +00004919 // Creates a Flags struct where the gtest_death_test_use_fork flag has
4920 // the given value.
4921 static Flags DeathTestUseFork(bool death_test_use_fork) {
4922 Flags flags;
4923 flags.death_test_use_fork = death_test_use_fork;
4924 return flags;
4925 }
4926
shiqian4b6829f2008-07-03 22:38:12 +00004927 // Creates a Flags struct where the gtest_filter flag has the given
4928 // value.
4929 static Flags Filter(const char* filter) {
4930 Flags flags;
4931 flags.filter = filter;
4932 return flags;
4933 }
4934
4935 // Creates a Flags struct where the gtest_list_tests flag has the
4936 // given value.
4937 static Flags ListTests(bool list_tests) {
4938 Flags flags;
4939 flags.list_tests = list_tests;
4940 return flags;
4941 }
4942
4943 // Creates a Flags struct where the gtest_output flag has the given
4944 // value.
4945 static Flags Output(const char* output) {
4946 Flags flags;
4947 flags.output = output;
4948 return flags;
4949 }
4950
shiqiand981cee2008-07-25 04:06:16 +00004951 // Creates a Flags struct where the gtest_print_time flag has the given
4952 // value.
4953 static Flags PrintTime(bool print_time) {
4954 Flags flags;
4955 flags.print_time = print_time;
4956 return flags;
4957 }
4958
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004959 // Creates a Flags struct where the gtest_random_seed flag has
4960 // the given value.
4961 static Flags RandomSeed(Int32 random_seed) {
4962 Flags flags;
4963 flags.random_seed = random_seed;
4964 return flags;
4965 }
4966
shiqian4b6829f2008-07-03 22:38:12 +00004967 // Creates a Flags struct where the gtest_repeat flag has the given
4968 // value.
4969 static Flags Repeat(Int32 repeat) {
4970 Flags flags;
4971 flags.repeat = repeat;
4972 return flags;
4973 }
4974
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004975 // Creates a Flags struct where the gtest_shuffle flag has
4976 // the given value.
4977 static Flags Shuffle(bool shuffle) {
4978 Flags flags;
4979 flags.shuffle = shuffle;
4980 return flags;
4981 }
4982
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004983 // Creates a Flags struct where the gtest_throw_on_failure flag has
4984 // the given value.
4985 static Flags ThrowOnFailure(bool throw_on_failure) {
4986 Flags flags;
4987 flags.throw_on_failure = throw_on_failure;
4988 return flags;
4989 }
4990
shiqian4b6829f2008-07-03 22:38:12 +00004991 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00004992 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00004993 bool break_on_failure;
4994 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00004995 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00004996 const char* filter;
4997 bool list_tests;
4998 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00004999 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005000 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00005001 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005002 bool shuffle;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005003 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00005004};
5005
5006// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00005007class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005008 protected:
5009 // Clears the flags before each test.
5010 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00005011 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005012 GTEST_FLAG(break_on_failure) = false;
5013 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00005014 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005015 GTEST_FLAG(filter) = "";
5016 GTEST_FLAG(list_tests) = false;
5017 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005018 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005019 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00005020 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005021 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005022 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005023 }
5024
5025 // Asserts that two narrow or wide string arrays are equal.
5026 template <typename CharType>
5027 static void AssertStringArrayEq(size_t size1, CharType** array1,
5028 size_t size2, CharType** array2) {
5029 ASSERT_EQ(size1, size2) << " Array sizes different.";
5030
5031 for (size_t i = 0; i != size1; i++) {
5032 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5033 }
5034 }
5035
5036 // Verifies that the flag values match the expected values.
5037 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00005038 EXPECT_EQ(expected.also_run_disabled_tests,
5039 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00005040 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5041 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00005042 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00005043 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5044 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5045 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00005046 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005047 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00005048 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005049 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005050 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00005051 }
5052
5053 // Parses a command line (specified by argc1 and argv1), then
5054 // verifies that the flag values are expected and that the
5055 // recognized flags are removed from the command line.
5056 template <typename CharType>
5057 static void TestParsingFlags(int argc1, const CharType** argv1,
5058 int argc2, const CharType** argv2,
5059 const Flags& expected) {
5060 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00005061 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00005062
5063 // Verifies the flag values.
5064 CheckFlags(expected);
5065
5066 // Verifies that the recognized flags are removed from the command
5067 // line.
5068 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5069 }
5070
5071 // This macro wraps TestParsingFlags s.t. the user doesn't need
5072 // to specify the array sizes.
zhanyong.wan4cd62602009-02-23 23:21:55 +00005073#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected) \
shiqian4b6829f2008-07-03 22:38:12 +00005074 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5075 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected)
5076};
5077
5078// Tests parsing an empty command line.
5079TEST_F(InitGoogleTestTest, Empty) {
5080 const char* argv[] = {
5081 NULL
5082 };
5083
5084 const char* argv2[] = {
5085 NULL
5086 };
5087
zhanyong.wan4cd62602009-02-23 23:21:55 +00005088 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00005089}
5090
5091// Tests parsing a command line that has no flag.
5092TEST_F(InitGoogleTestTest, NoFlag) {
5093 const char* argv[] = {
5094 "foo.exe",
5095 NULL
5096 };
5097
5098 const char* argv2[] = {
5099 "foo.exe",
5100 NULL
5101 };
5102
zhanyong.wan4cd62602009-02-23 23:21:55 +00005103 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00005104}
5105
5106// Tests parsing a bad --gtest_filter flag.
5107TEST_F(InitGoogleTestTest, FilterBad) {
5108 const char* argv[] = {
5109 "foo.exe",
5110 "--gtest_filter",
5111 NULL
5112 };
5113
5114 const char* argv2[] = {
5115 "foo.exe",
5116 "--gtest_filter",
5117 NULL
5118 };
5119
zhanyong.wan4cd62602009-02-23 23:21:55 +00005120 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00005121}
5122
5123// Tests parsing an empty --gtest_filter flag.
5124TEST_F(InitGoogleTestTest, FilterEmpty) {
5125 const char* argv[] = {
5126 "foo.exe",
5127 "--gtest_filter=",
5128 NULL
5129 };
5130
5131 const char* argv2[] = {
5132 "foo.exe",
5133 NULL
5134 };
5135
zhanyong.wan4cd62602009-02-23 23:21:55 +00005136 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00005137}
5138
5139// Tests parsing a non-empty --gtest_filter flag.
5140TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5141 const char* argv[] = {
5142 "foo.exe",
5143 "--gtest_filter=abc",
5144 NULL
5145 };
5146
5147 const char* argv2[] = {
5148 "foo.exe",
5149 NULL
5150 };
5151
zhanyong.wan4cd62602009-02-23 23:21:55 +00005152 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"));
shiqian4b6829f2008-07-03 22:38:12 +00005153}
5154
5155// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005156TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00005157 const char* argv[] = {
5158 "foo.exe",
5159 "--gtest_break_on_failure",
5160 NULL
5161};
5162
5163 const char* argv2[] = {
5164 "foo.exe",
5165 NULL
5166 };
5167
zhanyong.wan4cd62602009-02-23 23:21:55 +00005168 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00005169}
5170
5171// Tests parsing --gtest_break_on_failure=0.
5172TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5173 const char* argv[] = {
5174 "foo.exe",
5175 "--gtest_break_on_failure=0",
5176 NULL
5177 };
5178
5179 const char* argv2[] = {
5180 "foo.exe",
5181 NULL
5182 };
5183
zhanyong.wan4cd62602009-02-23 23:21:55 +00005184 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005185}
5186
5187// Tests parsing --gtest_break_on_failure=f.
5188TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5189 const char* argv[] = {
5190 "foo.exe",
5191 "--gtest_break_on_failure=f",
5192 NULL
5193 };
5194
5195 const char* argv2[] = {
5196 "foo.exe",
5197 NULL
5198 };
5199
zhanyong.wan4cd62602009-02-23 23:21:55 +00005200 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005201}
5202
5203// Tests parsing --gtest_break_on_failure=F.
5204TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5205 const char* argv[] = {
5206 "foo.exe",
5207 "--gtest_break_on_failure=F",
5208 NULL
5209 };
5210
5211 const char* argv2[] = {
5212 "foo.exe",
5213 NULL
5214 };
5215
zhanyong.wan4cd62602009-02-23 23:21:55 +00005216 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005217}
5218
5219// Tests parsing a --gtest_break_on_failure flag that has a "true"
5220// definition.
5221TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5222 const char* argv[] = {
5223 "foo.exe",
5224 "--gtest_break_on_failure=1",
5225 NULL
5226 };
5227
5228 const char* argv2[] = {
5229 "foo.exe",
5230 NULL
5231 };
5232
zhanyong.wan4cd62602009-02-23 23:21:55 +00005233 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00005234}
5235
5236// Tests parsing --gtest_catch_exceptions.
5237TEST_F(InitGoogleTestTest, CatchExceptions) {
5238 const char* argv[] = {
5239 "foo.exe",
5240 "--gtest_catch_exceptions",
5241 NULL
5242 };
5243
5244 const char* argv2[] = {
5245 "foo.exe",
5246 NULL
5247 };
5248
zhanyong.wan4cd62602009-02-23 23:21:55 +00005249 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true));
shiqian4b6829f2008-07-03 22:38:12 +00005250}
5251
shiqian21d43d12009-01-08 01:10:31 +00005252// Tests parsing --gtest_death_test_use_fork.
5253TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5254 const char* argv[] = {
5255 "foo.exe",
5256 "--gtest_death_test_use_fork",
5257 NULL
5258 };
5259
5260 const char* argv2[] = {
5261 "foo.exe",
5262 NULL
5263 };
5264
zhanyong.wan4cd62602009-02-23 23:21:55 +00005265 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true));
shiqian21d43d12009-01-08 01:10:31 +00005266}
5267
shiqian4b6829f2008-07-03 22:38:12 +00005268// Tests having the same flag twice with different values. The
5269// expected behavior is that the one coming last takes precedence.
5270TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5271 const char* argv[] = {
5272 "foo.exe",
5273 "--gtest_filter=a",
5274 "--gtest_filter=b",
5275 NULL
5276 };
5277
5278 const char* argv2[] = {
5279 "foo.exe",
5280 NULL
5281 };
5282
zhanyong.wan4cd62602009-02-23 23:21:55 +00005283 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"));
shiqian4b6829f2008-07-03 22:38:12 +00005284}
5285
5286// Tests having an unrecognized flag on the command line.
5287TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5288 const char* argv[] = {
5289 "foo.exe",
5290 "--gtest_break_on_failure",
5291 "bar", // Unrecognized by Google Test.
5292 "--gtest_filter=b",
5293 NULL
5294 };
5295
5296 const char* argv2[] = {
5297 "foo.exe",
5298 "bar",
5299 NULL
5300 };
5301
5302 Flags flags;
5303 flags.break_on_failure = true;
5304 flags.filter = "b";
zhanyong.wan4cd62602009-02-23 23:21:55 +00005305 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags);
shiqian4b6829f2008-07-03 22:38:12 +00005306}
5307
5308// Tests having a --gtest_list_tests flag
5309TEST_F(InitGoogleTestTest, ListTestsFlag) {
5310 const char* argv[] = {
5311 "foo.exe",
5312 "--gtest_list_tests",
5313 NULL
5314 };
5315
5316 const char* argv2[] = {
5317 "foo.exe",
5318 NULL
5319 };
5320
zhanyong.wan4cd62602009-02-23 23:21:55 +00005321 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005322}
5323
5324// Tests having a --gtest_list_tests flag with a "true" value
5325TEST_F(InitGoogleTestTest, ListTestsTrue) {
5326 const char* argv[] = {
5327 "foo.exe",
5328 "--gtest_list_tests=1",
5329 NULL
5330 };
5331
5332 const char* argv2[] = {
5333 "foo.exe",
5334 NULL
5335 };
5336
zhanyong.wan4cd62602009-02-23 23:21:55 +00005337 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005338}
5339
5340// Tests having a --gtest_list_tests flag with a "false" value
5341TEST_F(InitGoogleTestTest, ListTestsFalse) {
5342 const char* argv[] = {
5343 "foo.exe",
5344 "--gtest_list_tests=0",
5345 NULL
5346 };
5347
5348 const char* argv2[] = {
5349 "foo.exe",
5350 NULL
5351 };
5352
zhanyong.wan4cd62602009-02-23 23:21:55 +00005353 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005354}
5355
5356// Tests parsing --gtest_list_tests=f.
5357TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5358 const char* argv[] = {
5359 "foo.exe",
5360 "--gtest_list_tests=f",
5361 NULL
5362 };
5363
5364 const char* argv2[] = {
5365 "foo.exe",
5366 NULL
5367 };
5368
zhanyong.wan4cd62602009-02-23 23:21:55 +00005369 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005370}
5371
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005372// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005373TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5374 const char* argv[] = {
5375 "foo.exe",
5376 "--gtest_list_tests=F",
5377 NULL
5378 };
5379
5380 const char* argv2[] = {
5381 "foo.exe",
5382 NULL
5383 };
5384
zhanyong.wan4cd62602009-02-23 23:21:55 +00005385 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005386}
5387
5388// Tests parsing --gtest_output (invalid).
5389TEST_F(InitGoogleTestTest, OutputEmpty) {
5390 const char* argv[] = {
5391 "foo.exe",
5392 "--gtest_output",
5393 NULL
5394 };
5395
5396 const char* argv2[] = {
5397 "foo.exe",
5398 "--gtest_output",
5399 NULL
5400 };
5401
zhanyong.wan4cd62602009-02-23 23:21:55 +00005402 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00005403}
5404
5405// Tests parsing --gtest_output=xml
5406TEST_F(InitGoogleTestTest, OutputXml) {
5407 const char* argv[] = {
5408 "foo.exe",
5409 "--gtest_output=xml",
5410 NULL
5411 };
5412
5413 const char* argv2[] = {
5414 "foo.exe",
5415 NULL
5416 };
5417
zhanyong.wan4cd62602009-02-23 23:21:55 +00005418 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"));
shiqian4b6829f2008-07-03 22:38:12 +00005419}
5420
5421// Tests parsing --gtest_output=xml:file
5422TEST_F(InitGoogleTestTest, OutputXmlFile) {
5423 const char* argv[] = {
5424 "foo.exe",
5425 "--gtest_output=xml:file",
5426 NULL
5427 };
5428
5429 const char* argv2[] = {
5430 "foo.exe",
5431 NULL
5432 };
5433
zhanyong.wan4cd62602009-02-23 23:21:55 +00005434 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"));
shiqian4b6829f2008-07-03 22:38:12 +00005435}
5436
5437// Tests parsing --gtest_output=xml:directory/path/
5438TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5439 const char* argv[] = {
5440 "foo.exe",
5441 "--gtest_output=xml:directory/path/",
5442 NULL
5443 };
5444
5445 const char* argv2[] = {
5446 "foo.exe",
5447 NULL
5448 };
5449
zhanyong.wan4cd62602009-02-23 23:21:55 +00005450 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"));
shiqian4b6829f2008-07-03 22:38:12 +00005451}
5452
shiqiand981cee2008-07-25 04:06:16 +00005453// Tests having a --gtest_print_time flag
5454TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5455 const char* argv[] = {
5456 "foo.exe",
5457 "--gtest_print_time",
5458 NULL
5459 };
5460
5461 const char* argv2[] = {
5462 "foo.exe",
5463 NULL
5464 };
5465
zhanyong.wan4cd62602009-02-23 23:21:55 +00005466 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005467}
5468
5469// Tests having a --gtest_print_time flag with a "true" value
5470TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5471 const char* argv[] = {
5472 "foo.exe",
5473 "--gtest_print_time=1",
5474 NULL
5475 };
5476
5477 const char* argv2[] = {
5478 "foo.exe",
5479 NULL
5480 };
5481
zhanyong.wan4cd62602009-02-23 23:21:55 +00005482 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005483}
5484
5485// Tests having a --gtest_print_time flag with a "false" value
5486TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5487 const char* argv[] = {
5488 "foo.exe",
5489 "--gtest_print_time=0",
5490 NULL
5491 };
5492
5493 const char* argv2[] = {
5494 "foo.exe",
5495 NULL
5496 };
5497
zhanyong.wan4cd62602009-02-23 23:21:55 +00005498 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005499}
5500
5501// Tests parsing --gtest_print_time=f.
5502TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5503 const char* argv[] = {
5504 "foo.exe",
5505 "--gtest_print_time=f",
5506 NULL
5507 };
5508
5509 const char* argv2[] = {
5510 "foo.exe",
5511 NULL
5512 };
5513
zhanyong.wan4cd62602009-02-23 23:21:55 +00005514 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005515}
5516
5517// Tests parsing --gtest_print_time=F.
5518TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5519 const char* argv[] = {
5520 "foo.exe",
5521 "--gtest_print_time=F",
5522 NULL
5523 };
5524
5525 const char* argv2[] = {
5526 "foo.exe",
5527 NULL
5528 };
5529
zhanyong.wan4cd62602009-02-23 23:21:55 +00005530 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005531}
5532
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005533// Tests parsing --gtest_random_seed=number
5534TEST_F(InitGoogleTestTest, RandomSeed) {
5535 const char* argv[] = {
5536 "foo.exe",
5537 "--gtest_random_seed=1000",
5538 NULL
5539 };
5540
5541 const char* argv2[] = {
5542 "foo.exe",
5543 NULL
5544 };
5545
5546 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000));
5547}
5548
shiqian4b6829f2008-07-03 22:38:12 +00005549// Tests parsing --gtest_repeat=number
5550TEST_F(InitGoogleTestTest, Repeat) {
5551 const char* argv[] = {
5552 "foo.exe",
5553 "--gtest_repeat=1000",
5554 NULL
5555 };
5556
5557 const char* argv2[] = {
5558 "foo.exe",
5559 NULL
5560 };
5561
zhanyong.wan4cd62602009-02-23 23:21:55 +00005562 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000));
shiqian4b6829f2008-07-03 22:38:12 +00005563}
5564
shiqianca6949f2009-01-10 01:16:33 +00005565// Tests having a --gtest_also_run_disabled_tests flag
5566TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5567 const char* argv[] = {
5568 "foo.exe",
5569 "--gtest_also_run_disabled_tests",
5570 NULL
5571 };
5572
5573 const char* argv2[] = {
5574 "foo.exe",
5575 NULL
5576 };
5577
zhanyong.wan4cd62602009-02-23 23:21:55 +00005578 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005579}
5580
5581// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5582TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5583 const char* argv[] = {
5584 "foo.exe",
5585 "--gtest_also_run_disabled_tests=1",
5586 NULL
5587 };
5588
5589 const char* argv2[] = {
5590 "foo.exe",
5591 NULL
5592 };
5593
zhanyong.wan4cd62602009-02-23 23:21:55 +00005594 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005595}
5596
5597// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5598TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5599 const char* argv[] = {
5600 "foo.exe",
5601 "--gtest_also_run_disabled_tests=0",
5602 NULL
5603 };
5604
5605 const char* argv2[] = {
5606 "foo.exe",
5607 NULL
5608 };
5609
zhanyong.wan4cd62602009-02-23 23:21:55 +00005610 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false));
shiqianca6949f2009-01-10 01:16:33 +00005611}
5612
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005613// Tests parsing --gtest_shuffle.
5614TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
5615 const char* argv[] = {
5616 "foo.exe",
5617 "--gtest_shuffle",
5618 NULL
5619};
5620
5621 const char* argv2[] = {
5622 "foo.exe",
5623 NULL
5624 };
5625
5626 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5627}
5628
5629// Tests parsing --gtest_shuffle=0.
5630TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
5631 const char* argv[] = {
5632 "foo.exe",
5633 "--gtest_shuffle=0",
5634 NULL
5635 };
5636
5637 const char* argv2[] = {
5638 "foo.exe",
5639 NULL
5640 };
5641
5642 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false));
5643}
5644
5645// Tests parsing a --gtest_shuffle flag that has a "true"
5646// definition.
5647TEST_F(InitGoogleTestTest, ShuffleTrue) {
5648 const char* argv[] = {
5649 "foo.exe",
5650 "--gtest_shuffle=1",
5651 NULL
5652 };
5653
5654 const char* argv2[] = {
5655 "foo.exe",
5656 NULL
5657 };
5658
5659 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5660}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005661
5662// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005663TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005664 const char* argv[] = {
5665 "foo.exe",
5666 "--gtest_throw_on_failure",
5667 NULL
5668};
5669
5670 const char* argv2[] = {
5671 "foo.exe",
5672 NULL
5673 };
5674
5675 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5676}
5677
5678// Tests parsing --gtest_throw_on_failure=0.
5679TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5680 const char* argv[] = {
5681 "foo.exe",
5682 "--gtest_throw_on_failure=0",
5683 NULL
5684 };
5685
5686 const char* argv2[] = {
5687 "foo.exe",
5688 NULL
5689 };
5690
5691 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false));
5692}
5693
5694// Tests parsing a --gtest_throw_on_failure flag that has a "true"
5695// definition.
5696TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
5697 const char* argv[] = {
5698 "foo.exe",
5699 "--gtest_throw_on_failure=1",
5700 NULL
5701 };
5702
5703 const char* argv2[] = {
5704 "foo.exe",
5705 NULL
5706 };
5707
5708 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5709}
5710
zhanyong.wan4cd62602009-02-23 23:21:55 +00005711#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00005712// Tests parsing wide strings.
5713TEST_F(InitGoogleTestTest, WideStrings) {
5714 const wchar_t* argv[] = {
5715 L"foo.exe",
5716 L"--gtest_filter=Foo*",
5717 L"--gtest_list_tests=1",
5718 L"--gtest_break_on_failure",
5719 L"--non_gtest_flag",
5720 NULL
5721 };
5722
5723 const wchar_t* argv2[] = {
5724 L"foo.exe",
5725 L"--non_gtest_flag",
5726 NULL
5727 };
5728
5729 Flags expected_flags;
5730 expected_flags.break_on_failure = true;
5731 expected_flags.filter = "Foo*";
5732 expected_flags.list_tests = true;
5733
zhanyong.wan4cd62602009-02-23 23:21:55 +00005734 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags);
shiqian4b6829f2008-07-03 22:38:12 +00005735}
5736#endif // GTEST_OS_WINDOWS
5737
5738// Tests current_test_info() in UnitTest.
5739class CurrentTestInfoTest : public Test {
5740 protected:
5741 // Tests that current_test_info() returns NULL before the first test in
5742 // the test case is run.
5743 static void SetUpTestCase() {
5744 // There should be no tests running at this point.
5745 const TestInfo* test_info =
5746 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005747 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005748 << "There should be no tests running at this point.";
5749 }
5750
5751 // Tests that current_test_info() returns NULL after the last test in
5752 // the test case has run.
5753 static void TearDownTestCase() {
5754 const TestInfo* test_info =
5755 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005756 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005757 << "There should be no tests running at this point.";
5758 }
5759};
5760
5761// Tests that current_test_info() returns TestInfo for currently running
5762// test by checking the expected test name against the actual one.
5763TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
5764 const TestInfo* test_info =
5765 UnitTest::GetInstance()->current_test_info();
5766 ASSERT_TRUE(NULL != test_info)
5767 << "There is a test running so we should have a valid TestInfo.";
5768 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5769 << "Expected the name of the currently running test case.";
5770 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
5771 << "Expected the name of the currently running test.";
5772}
5773
5774// Tests that current_test_info() returns TestInfo for currently running
5775// test by checking the expected test name against the actual one. We
5776// use this test to see that the TestInfo object actually changed from
5777// the previous invocation.
5778TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
5779 const TestInfo* test_info =
5780 UnitTest::GetInstance()->current_test_info();
5781 ASSERT_TRUE(NULL != test_info)
5782 << "There is a test running so we should have a valid TestInfo.";
5783 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5784 << "Expected the name of the currently running test case.";
5785 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
5786 << "Expected the name of the currently running test.";
5787}
5788
5789} // namespace testing
5790
5791// These two lines test that we can define tests in a namespace that
5792// has the name "testing" and is nested in another namespace.
5793namespace my_namespace {
5794namespace testing {
5795
5796// Makes sure that TEST knows to use ::testing::Test instead of
5797// ::my_namespace::testing::Test.
5798class Test {};
5799
5800// Makes sure that an assertion knows to use ::testing::Message instead of
5801// ::my_namespace::testing::Message.
5802class Message {};
5803
5804// Makes sure that an assertion knows to use
5805// ::testing::AssertionResult instead of
5806// ::my_namespace::testing::AssertionResult.
5807class AssertionResult {};
5808
5809// Tests that an assertion that should succeed works as expected.
5810TEST(NestedTestingNamespaceTest, Success) {
5811 EXPECT_EQ(1, 1) << "This shouldn't fail.";
5812}
5813
5814// Tests that an assertion that should fail works as expected.
5815TEST(NestedTestingNamespaceTest, Failure) {
5816 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
5817 "This failure is expected.");
5818}
5819
5820} // namespace testing
5821} // namespace my_namespace
5822
5823// Tests that one can call superclass SetUp and TearDown methods--
5824// that is, that they are not private.
5825// No tests are based on this fixture; the test "passes" if it compiles
5826// successfully.
shiqian760af5c2008-08-06 21:43:15 +00005827class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005828 protected:
5829 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00005830 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00005831 }
5832 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00005833 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00005834 }
5835};
5836
5837// StreamingAssertionsTest tests the streaming versions of a representative
5838// sample of assertions.
5839TEST(StreamingAssertionsTest, Unconditional) {
5840 SUCCEED() << "expected success";
5841 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
5842 "expected failure");
5843 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
5844 "expected failure");
5845}
5846
zhanyong.wan98efcc42009-04-28 00:28:09 +00005847#ifdef __BORLANDC__
5848// Silences warnings: "Condition is always true", "Unreachable code"
5849#pragma option push -w-ccc -w-rch
5850#endif
5851
shiqian4b6829f2008-07-03 22:38:12 +00005852TEST(StreamingAssertionsTest, Truth) {
5853 EXPECT_TRUE(true) << "unexpected failure";
5854 ASSERT_TRUE(true) << "unexpected failure";
5855 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
5856 "expected failure");
5857 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
5858 "expected failure");
5859}
5860
5861TEST(StreamingAssertionsTest, Truth2) {
5862 EXPECT_FALSE(false) << "unexpected failure";
5863 ASSERT_FALSE(false) << "unexpected failure";
5864 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
5865 "expected failure");
5866 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
5867 "expected failure");
5868}
5869
zhanyong.wan98efcc42009-04-28 00:28:09 +00005870#ifdef __BORLANDC__
5871// Restores warnings after previous "#pragma option push" supressed them
5872#pragma option pop
5873#endif
5874
shiqian4b6829f2008-07-03 22:38:12 +00005875TEST(StreamingAssertionsTest, IntegerEquals) {
5876 EXPECT_EQ(1, 1) << "unexpected failure";
5877 ASSERT_EQ(1, 1) << "unexpected failure";
5878 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
5879 "expected failure");
5880 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
5881 "expected failure");
5882}
5883
5884TEST(StreamingAssertionsTest, IntegerLessThan) {
5885 EXPECT_LT(1, 2) << "unexpected failure";
5886 ASSERT_LT(1, 2) << "unexpected failure";
5887 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
5888 "expected failure");
5889 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
5890 "expected failure");
5891}
5892
5893TEST(StreamingAssertionsTest, StringsEqual) {
5894 EXPECT_STREQ("foo", "foo") << "unexpected failure";
5895 ASSERT_STREQ("foo", "foo") << "unexpected failure";
5896 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
5897 "expected failure");
5898 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
5899 "expected failure");
5900}
5901
5902TEST(StreamingAssertionsTest, StringsNotEqual) {
5903 EXPECT_STRNE("foo", "bar") << "unexpected failure";
5904 ASSERT_STRNE("foo", "bar") << "unexpected failure";
5905 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
5906 "expected failure");
5907 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
5908 "expected failure");
5909}
5910
5911TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
5912 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5913 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5914 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
5915 "expected failure");
5916 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
5917 "expected failure");
5918}
5919
5920TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
5921 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
5922 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
5923 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
5924 "expected failure");
5925 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
5926 "expected failure");
5927}
5928
5929TEST(StreamingAssertionsTest, FloatingPointEquals) {
5930 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5931 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5932 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5933 "expected failure");
5934 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5935 "expected failure");
5936}
5937
shiqian9204c8e2008-09-12 20:57:22 +00005938#if GTEST_HAS_EXCEPTIONS
5939
5940TEST(StreamingAssertionsTest, Throw) {
5941 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5942 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5943 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
5944 "expected failure", "expected failure");
5945 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
5946 "expected failure", "expected failure");
5947}
5948
5949TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00005950 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
5951 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00005952 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
5953 "expected failure", "expected failure");
5954 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
5955 "expected failure", "expected failure");
5956}
5957
5958TEST(StreamingAssertionsTest, AnyThrow) {
5959 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
5960 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00005961 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005962 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00005963 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005964 "expected failure", "expected failure");
5965}
5966
5967#endif // GTEST_HAS_EXCEPTIONS
5968
shiqian4b6829f2008-07-03 22:38:12 +00005969// Tests that Google Test correctly decides whether to use colors in the output.
5970
5971TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
5972 GTEST_FLAG(color) = "yes";
5973
5974 SetEnv("TERM", "xterm"); // TERM supports colors.
5975 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5976 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5977
5978 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5979 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5980 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5981}
5982
5983TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
5984 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5985
5986 GTEST_FLAG(color) = "True";
5987 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5988
5989 GTEST_FLAG(color) = "t";
5990 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5991
5992 GTEST_FLAG(color) = "1";
5993 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5994}
5995
5996TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
5997 GTEST_FLAG(color) = "no";
5998
5999 SetEnv("TERM", "xterm"); // TERM supports colors.
6000 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6001 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6002
6003 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6004 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6005 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6006}
6007
6008TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6009 SetEnv("TERM", "xterm"); // TERM supports colors.
6010
6011 GTEST_FLAG(color) = "F";
6012 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6013
6014 GTEST_FLAG(color) = "0";
6015 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6016
6017 GTEST_FLAG(color) = "unknown";
6018 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6019}
6020
6021TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6022 GTEST_FLAG(color) = "auto";
6023
6024 SetEnv("TERM", "xterm"); // TERM supports colors.
6025 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6026 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6027}
6028
6029TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6030 GTEST_FLAG(color) = "auto";
6031
zhanyong.wan4cd62602009-02-23 23:21:55 +00006032#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006033 // On Windows, we ignore the TERM variable as it's usually not set.
6034
6035 SetEnv("TERM", "dumb");
6036 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6037
6038 SetEnv("TERM", "");
6039 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6040
6041 SetEnv("TERM", "xterm");
6042 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6043#else
6044 // On non-Windows platforms, we rely on TERM to determine if the
6045 // terminal supports colors.
6046
6047 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6048 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6049
6050 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6051 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6052
6053 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6054 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6055
6056 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6057 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6058
6059 SetEnv("TERM", "xterm"); // TERM supports colors.
6060 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6061
6062 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6063 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00006064
6065 SetEnv("TERM", "linux"); // TERM supports colors.
6066 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00006067#endif // GTEST_OS_WINDOWS
6068}
6069
shiqian21d43d12009-01-08 01:10:31 +00006070// Verifies that StaticAssertTypeEq works in a namespace scope.
6071
6072static bool dummy1 = StaticAssertTypeEq<bool, bool>();
6073static bool dummy2 = StaticAssertTypeEq<const int, const int>();
6074
6075// Verifies that StaticAssertTypeEq works in a class.
6076
6077template <typename T>
6078class StaticAssertTypeEqTestHelper {
6079 public:
6080 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6081};
6082
6083TEST(StaticAssertTypeEqTest, WorksInClass) {
6084 StaticAssertTypeEqTestHelper<bool>();
6085}
6086
6087// Verifies that StaticAssertTypeEq works inside a function.
6088
6089typedef int IntAlias;
6090
6091TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6092 StaticAssertTypeEq<int, IntAlias>();
6093 StaticAssertTypeEq<int*, IntAlias*>();
6094}
6095
shiqiane44602e2008-10-11 07:20:02 +00006096TEST(ThreadLocalTest, DefaultConstructor) {
6097 ThreadLocal<int> t1;
6098 EXPECT_EQ(0, t1.get());
6099
6100 ThreadLocal<void*> t2;
6101 EXPECT_TRUE(t2.get() == NULL);
6102}
6103
6104TEST(ThreadLocalTest, Init) {
6105 ThreadLocal<int> t1(123);
6106 EXPECT_EQ(123, t1.get());
6107
6108 int i = 0;
6109 ThreadLocal<int*> t2(&i);
6110 EXPECT_EQ(&i, t2.get());
6111}
6112
vladlosevf904a612008-11-20 01:40:35 +00006113TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6114 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6115
6116 // We don't have a stack walker in Google Test yet.
6117 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6118 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6119}
zhanyong.wan1b171102009-04-07 21:03:22 +00006120
6121TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6122 EXPECT_FALSE(HasNonfatalFailure());
6123}
6124
6125static void FailFatally() { FAIL(); }
6126
6127TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6128 FailFatally();
6129 const bool has_nonfatal_failure = HasNonfatalFailure();
6130 ClearCurrentTestPartResults();
6131 EXPECT_FALSE(has_nonfatal_failure);
6132}
6133
6134TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6135 ADD_FAILURE();
6136 const bool has_nonfatal_failure = HasNonfatalFailure();
6137 ClearCurrentTestPartResults();
6138 EXPECT_TRUE(has_nonfatal_failure);
6139}
6140
6141TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6142 FailFatally();
6143 ADD_FAILURE();
6144 const bool has_nonfatal_failure = HasNonfatalFailure();
6145 ClearCurrentTestPartResults();
6146 EXPECT_TRUE(has_nonfatal_failure);
6147}
6148
6149// A wrapper for calling HasNonfatalFailure outside of a test body.
6150static bool HasNonfatalFailureHelper() {
6151 return testing::Test::HasNonfatalFailure();
6152}
6153
6154TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6155 EXPECT_FALSE(HasNonfatalFailureHelper());
6156}
6157
6158TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6159 ADD_FAILURE();
6160 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6161 ClearCurrentTestPartResults();
6162 EXPECT_TRUE(has_nonfatal_failure);
6163}
6164
6165TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6166 EXPECT_FALSE(HasFailure());
6167}
6168
6169TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6170 FailFatally();
6171 const bool has_failure = HasFailure();
6172 ClearCurrentTestPartResults();
6173 EXPECT_TRUE(has_failure);
6174}
6175
6176TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6177 ADD_FAILURE();
6178 const bool has_failure = HasFailure();
6179 ClearCurrentTestPartResults();
6180 EXPECT_TRUE(has_failure);
6181}
6182
6183TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6184 FailFatally();
6185 ADD_FAILURE();
6186 const bool has_failure = HasFailure();
6187 ClearCurrentTestPartResults();
6188 EXPECT_TRUE(has_failure);
6189}
6190
6191// A wrapper for calling HasFailure outside of a test body.
6192static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6193
6194TEST(HasFailureTest, WorksOutsideOfTestBody) {
6195 EXPECT_FALSE(HasFailureHelper());
6196}
6197
6198TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6199 ADD_FAILURE();
6200 const bool has_failure = HasFailureHelper();
6201 ClearCurrentTestPartResults();
6202 EXPECT_TRUE(has_failure);
6203}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006204
6205class TestListener : public EmptyTestEventListener {
6206 public:
6207 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6208 TestListener(int* on_start_counter, bool* is_destroyed)
6209 : on_start_counter_(on_start_counter),
6210 is_destroyed_(is_destroyed) {}
6211
6212 virtual ~TestListener() {
6213 if (is_destroyed_)
6214 *is_destroyed_ = true;
6215 }
6216
6217 protected:
6218 virtual void OnUnitTestStart(const UnitTest& /*unit_test*/) {
6219 if (on_start_counter_ != NULL)
6220 (*on_start_counter_)++;
6221 }
6222
6223 private:
6224 int* on_start_counter_;
6225 bool* is_destroyed_;
6226};
6227
6228// Tests the constructor.
6229TEST(EventListenersTest, ConstructionWorks) {
6230 EventListeners listeners;
6231
6232 EXPECT_TRUE(EventListenersAccessor::GetRepeater(&listeners) != NULL);
6233 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6234 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6235}
6236
6237// Tests that the EventListeners destructor deletes all the listeners it
6238// owns.
6239TEST(EventListenersTest, DestructionWorks) {
6240 bool default_result_printer_is_destroyed = false;
6241 bool default_xml_printer_is_destroyed = false;
6242 bool extra_listener_is_destroyed = false;
6243 TestListener* default_result_printer = new TestListener(
6244 NULL, &default_result_printer_is_destroyed);
6245 TestListener* default_xml_printer = new TestListener(
6246 NULL, &default_xml_printer_is_destroyed);
6247 TestListener* extra_listener = new TestListener(
6248 NULL, &extra_listener_is_destroyed);
6249
6250 {
6251 EventListeners listeners;
6252 EventListenersAccessor::SetDefaultResultPrinter(&listeners,
6253 default_result_printer);
6254 EventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6255 default_xml_printer);
6256 listeners.Append(extra_listener);
6257 }
6258 EXPECT_TRUE(default_result_printer_is_destroyed);
6259 EXPECT_TRUE(default_xml_printer_is_destroyed);
6260 EXPECT_TRUE(extra_listener_is_destroyed);
6261}
6262
6263// Tests that a listener Append'ed to an EventListeners list starts
6264// receiving events.
6265TEST(EventListenersTest, Append) {
6266 int on_start_counter = 0;
6267 bool is_destroyed = false;
6268 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6269 {
6270 EventListeners listeners;
6271 listeners.Append(listener);
6272 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6273 *UnitTest::GetInstance());
6274 EXPECT_EQ(1, on_start_counter);
6275 }
6276 EXPECT_TRUE(is_destroyed);
6277}
6278
6279// Tests that listeners receive requests in the order they were appended to
6280// the list.
6281class SequenceTestingListener : public EmptyTestEventListener {
6282 public:
6283 SequenceTestingListener(Vector<const char*>* vector, const char* signature)
6284 : vector_(vector), signature_(signature) {}
6285
6286 protected:
6287 virtual void OnUnitTestStart(const UnitTest& /*unit_test*/) {
6288 if (vector_ != NULL)
6289 vector_->PushBack(signature_);
6290 }
6291
6292 private:
6293 Vector<const char*>* vector_;
6294 const char* const signature_;
6295};
6296
6297TEST(EventListenerTest, AppendKeepsOrder) {
6298 Vector<const char*> vec;
6299 EventListeners listeners;
6300 listeners.Append(new SequenceTestingListener(&vec, "0"));
6301 listeners.Append(new SequenceTestingListener(&vec, "1"));
6302 listeners.Append(new SequenceTestingListener(&vec, "2"));
6303 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6304 *UnitTest::GetInstance());
6305 ASSERT_EQ(3, vec.size());
6306 ASSERT_STREQ("0", vec.GetElement(0));
6307 ASSERT_STREQ("1", vec.GetElement(1));
6308 ASSERT_STREQ("2", vec.GetElement(2));
6309}
6310
6311// Tests that a listener removed from an EventListeners list stops receiving
6312// events and is not deleted when the list is destroyed.
6313TEST(EventListenersTest, Release) {
6314 int on_start_counter = 0;
6315 bool is_destroyed = false;
6316 // Although Append passes the ownership of this object to the list,
6317 // the following calls release it, and we need to delete it before the
6318 // test ends.
6319 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6320 {
6321 EventListeners listeners;
6322 listeners.Append(listener);
6323 EXPECT_EQ(listener, listeners.Release(listener));
6324 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6325 *UnitTest::GetInstance());
6326 EXPECT_TRUE(listeners.Release(listener) == NULL);
6327 }
6328 EXPECT_EQ(0, on_start_counter);
6329 EXPECT_FALSE(is_destroyed);
6330 delete listener;
6331}
6332
6333// Tests that no events are forwarded when event forwarding is disabled.
6334TEST(EventListenerTest, SuppressEventForwarding) {
6335 int on_start_counter = 0;
6336 TestListener* listener = new TestListener(&on_start_counter, NULL);
6337
6338 EventListeners listeners;
6339 listeners.Append(listener);
6340 ASSERT_TRUE(EventListenersAccessor::EventForwardingEnabled(listeners));
6341 EventListenersAccessor::SuppressEventForwarding(&listeners);
6342 ASSERT_FALSE(EventListenersAccessor::EventForwardingEnabled(listeners));
6343 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6344 *UnitTest::GetInstance());
6345 EXPECT_EQ(0, on_start_counter);
6346}
6347
zhanyong.wanf39160b2009-09-04 18:30:25 +00006348// Tests that events generated by Google Test are not forwarded in
6349// death test subprocesses.
6350TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
zhanyong.wand541f022009-09-11 06:59:42 +00006351 EXPECT_DEATH_IF_SUPPORTED({
zhanyong.wanf39160b2009-09-04 18:30:25 +00006352 GTEST_CHECK_(EventListenersAccessor::EventForwardingEnabled(
6353 *GetUnitTestImpl()->listeners())) << "expected failure";},
6354 "expected failure");
6355}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006356
6357// Tests that a listener installed via SetDefaultResultPrinter() starts
6358// receiving events and is returned via default_result_printer() and that
6359// the previous default_result_printer is removed from the list and deleted.
6360TEST(EventListenerTest, default_result_printer) {
6361 int on_start_counter = 0;
6362 bool is_destroyed = false;
6363 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6364
6365 EventListeners listeners;
6366 EventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6367
6368 EXPECT_EQ(listener, listeners.default_result_printer());
6369
6370 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6371 *UnitTest::GetInstance());
6372
6373 EXPECT_EQ(1, on_start_counter);
6374
6375 // Replacing default_result_printer with something else should remove it
6376 // from the list and destroy it.
6377 EventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
6378
6379 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6380 EXPECT_TRUE(is_destroyed);
6381
6382 // After broadcasting an event the counter is still the same, indicating
6383 // the listener is not in the list anymore.
6384 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6385 *UnitTest::GetInstance());
6386 EXPECT_EQ(1, on_start_counter);
6387}
6388
6389// Tests that the default_result_printer listener stops receiving events
6390// when removed via Release and that is not owned by the list anymore.
6391TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6392 int on_start_counter = 0;
6393 bool is_destroyed = false;
6394 // Although Append passes the ownership of this object to the list,
6395 // the following calls release it, and we need to delete it before the
6396 // test ends.
6397 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6398 {
6399 EventListeners listeners;
6400 EventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6401
6402 EXPECT_EQ(listener, listeners.Release(listener));
6403 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6404 EXPECT_FALSE(is_destroyed);
6405
6406 // Broadcasting events now should not affect default_result_printer.
6407 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6408 *UnitTest::GetInstance());
6409 EXPECT_EQ(0, on_start_counter);
6410 }
6411 // Destroying the list should not affect the listener now, too.
6412 EXPECT_FALSE(is_destroyed);
6413 delete listener;
6414}
6415
6416// Tests that a listener installed via SetDefaultXmlGenerator() starts
6417// receiving events and is returned via default_xml_generator() and that
6418// the previous default_xml_generator is removed from the list and deleted.
6419TEST(EventListenerTest, default_xml_generator) {
6420 int on_start_counter = 0;
6421 bool is_destroyed = false;
6422 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6423
6424 EventListeners listeners;
6425 EventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
6426
6427 EXPECT_EQ(listener, listeners.default_xml_generator());
6428
6429 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6430 *UnitTest::GetInstance());
6431
6432 EXPECT_EQ(1, on_start_counter);
6433
6434 // Replacing default_xml_generator with something else should remove it
6435 // from the list and destroy it.
6436 EventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
6437
6438 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6439 EXPECT_TRUE(is_destroyed);
6440
6441 // After broadcasting an event the counter is still the same, indicating
6442 // the listener is not in the list anymore.
6443 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6444 *UnitTest::GetInstance());
6445 EXPECT_EQ(1, on_start_counter);
6446}
6447
6448// Tests that the default_xml_generator listener stops receiving events
6449// when removed via Release and that is not owned by the list anymore.
6450TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6451 int on_start_counter = 0;
6452 bool is_destroyed = false;
6453 // Although Append passes the ownership of this object to the list,
6454 // the following calls release it, and we need to delete it before the
6455 // test ends.
6456 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6457 {
6458 EventListeners listeners;
6459 EventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
6460
6461 EXPECT_EQ(listener, listeners.Release(listener));
6462 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6463 EXPECT_FALSE(is_destroyed);
6464
6465 // Broadcasting events now should not affect default_xml_generator.
6466 EventListenersAccessor::GetRepeater(&listeners)->OnUnitTestStart(
6467 *UnitTest::GetInstance());
6468 EXPECT_EQ(0, on_start_counter);
6469 }
6470 // Destroying the list should not affect the listener now, too.
6471 EXPECT_FALSE(is_destroyed);
6472 delete listener;
6473}