blob: 7cdfa17208dc1ba607256e5d98a640e251f99a26 [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
zhanyong.wan449f84d2009-07-01 22:55:05 +000081// GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex) expands to a
82// real death test if death tests are supported; otherwise it expands
83// to empty.
84#if GTEST_HAS_DEATH_TEST
85#define GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex) \
86 EXPECT_DEATH(statement, regex)
87#else
88#define GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex)
89#endif
90
shiqian4b6829f2008-07-03 22:38:12 +000091namespace testing {
92namespace internal {
shiqianf0e809a2008-09-26 16:08:30 +000093const char* FormatTimeInMillisAsSeconds(TimeInMillis ms);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000094
shiqian4b6829f2008-07-03 22:38:12 +000095bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000096
97// TestResult contains some private methods that should be hidden from
98// Google Test user but are required for testing. This class allow our tests
99// to access them.
100class TestResultAccessor {
101 public:
102 static void RecordProperty(TestResult* test_result,
103 const TestProperty& property) {
104 test_result->RecordProperty(property);
105 }
106
107 static void ClearTestPartResults(TestResult* test_result) {
108 test_result->ClearTestPartResults();
109 }
110
zhanyong.wana8a582f2009-07-13 19:25:02 +0000111 static const Vector<testing::TestPartResult>& test_part_results(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000112 const TestResult& test_result) {
113 return test_result.test_part_results();
114 }
115};
116
shiqian4b6829f2008-07-03 22:38:12 +0000117} // namespace internal
118} // namespace testing
119
shiqianf0e809a2008-09-26 16:08:30 +0000120using testing::internal::FormatTimeInMillisAsSeconds;
shiqian4b6829f2008-07-03 22:38:12 +0000121using testing::internal::ParseInt32Flag;
122
123namespace testing {
124
shiqiane44602e2008-10-11 07:20:02 +0000125GTEST_DECLARE_string_(output);
126GTEST_DECLARE_string_(color);
shiqian4b6829f2008-07-03 22:38:12 +0000127
128namespace internal {
129bool ShouldUseColor(bool stdout_is_tty);
130} // namespace internal
131} // namespace testing
132
shiqian760af5c2008-08-06 21:43:15 +0000133using testing::AssertionFailure;
134using testing::AssertionResult;
135using testing::AssertionSuccess;
136using testing::DoubleLE;
137using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000138using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000139using testing::GTEST_FLAG(break_on_failure);
140using testing::GTEST_FLAG(catch_exceptions);
shiqian21d43d12009-01-08 01:10:31 +0000141using testing::GTEST_FLAG(death_test_use_fork);
shiqian4b6829f2008-07-03 22:38:12 +0000142using testing::GTEST_FLAG(color);
shiqian760af5c2008-08-06 21:43:15 +0000143using testing::GTEST_FLAG(filter);
144using testing::GTEST_FLAG(list_tests);
145using testing::GTEST_FLAG(output);
146using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000147using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000148using testing::GTEST_FLAG(repeat);
149using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000150using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000151using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000152using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000153using testing::IsNotSubstring;
154using testing::IsSubstring;
155using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000156using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000157using testing::StaticAssertTypeEq;
shiqian760af5c2008-08-06 21:43:15 +0000158using testing::Test;
shiqian4b6829f2008-07-03 22:38:12 +0000159using testing::TestPartResult;
160using testing::TestPartResultArray;
shiqian760af5c2008-08-06 21:43:15 +0000161using testing::TPRT_FATAL_FAILURE;
162using testing::TPRT_NONFATAL_FAILURE;
163using testing::TPRT_SUCCESS;
shiqian4b6829f2008-07-03 22:38:12 +0000164using testing::UnitTest;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000165using testing::internal::kMaxRandomSeed;
shiqianfe6a9a42008-11-24 20:13:22 +0000166using testing::internal::kTestTypeIdInGoogleTest;
shiqian4b6829f2008-07-03 22:38:12 +0000167using testing::internal::AppendUserMessage;
vladloseve006e682008-08-25 23:11:54 +0000168using testing::internal::CodePointToUtf8;
shiqian4b6829f2008-07-03 22:38:12 +0000169using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000170using testing::internal::FloatingPoint;
vladlosevf904a612008-11-20 01:40:35 +0000171using testing::internal::GetCurrentOsStackTraceExceptTop;
172using testing::internal::GetFailedPartCount;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000173using testing::internal::GetNextRandomSeed;
174using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000175using testing::internal::GetTestTypeId;
176using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000177using testing::internal::GetUnitTestImpl;
shiqian760af5c2008-08-06 21:43:15 +0000178using testing::internal::GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +0000179using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000180using testing::internal::Int32FromEnvOrDie;
zhanyong.wan905074c2009-02-09 18:05:21 +0000181using testing::internal::ShouldRunTestOnShard;
182using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000183using testing::internal::ShouldUseColor;
184using testing::internal::StreamableToString;
185using testing::internal::String;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000186using testing::internal::TestCase;
shiqian4b6829f2008-07-03 22:38:12 +0000187using testing::internal::TestProperty;
188using testing::internal::TestResult;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000189using testing::internal::TestResultAccessor;
shiqiane44602e2008-10-11 07:20:02 +0000190using testing::internal::ThreadLocal;
zhanyong.wana8a582f2009-07-13 19:25:02 +0000191using testing::internal::Vector;
vladloseve006e682008-08-25 23:11:54 +0000192using testing::internal::WideStringToUtf8;
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.
653 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
654 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
669 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
670 a1.Erase(3),
671 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
672 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
673 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));
720 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
721 a.GetElement(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000722 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +0000723 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
724 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
728// Tests the String class.
729
730// Tests String's constructors.
731TEST(StringTest, Constructors) {
732 // Default ctor.
733 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +0000734 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
735 // pointers with NULL isn't supported on all platforms.
736 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +0000737
738 // Implicitly constructs from a C-string.
739 String s2 = "Hi";
740 EXPECT_STREQ("Hi", s2.c_str());
741
742 // Constructs from a C-string and a length.
743 String s3("hello", 3);
744 EXPECT_STREQ("hel", s3.c_str());
745
746 // Copy ctor.
747 String s4 = s3;
748 EXPECT_STREQ("hel", s4.c_str());
749}
750
vladlosevf179f4e2008-11-26 20:48:45 +0000751#if GTEST_HAS_STD_STRING
752
753TEST(StringTest, ConvertsFromStdString) {
754 // An empty std::string.
755 const std::string src1("");
756 const String dest1 = src1;
757 EXPECT_STREQ("", dest1.c_str());
758
759 // A normal std::string.
760 const std::string src2("Hi");
761 const String dest2 = src2;
762 EXPECT_STREQ("Hi", dest2.c_str());
763
764 // An std::string with an embedded NUL character.
765 const char src3[] = "Hello\0world.";
766 const String dest3 = std::string(src3, sizeof(src3));
767 EXPECT_STREQ("Hello", dest3.c_str());
768}
769
770TEST(StringTest, ConvertsToStdString) {
771 // An empty String.
772 const String src1("");
773 const std::string dest1 = src1;
774 EXPECT_EQ("", dest1);
775
776 // A normal String.
777 const String src2("Hi");
778 const std::string dest2 = src2;
779 EXPECT_EQ("Hi", dest2);
780}
781
782#endif // GTEST_HAS_STD_STRING
783
784#if GTEST_HAS_GLOBAL_STRING
785
786TEST(StringTest, ConvertsFromGlobalString) {
787 // An empty ::string.
788 const ::string src1("");
789 const String dest1 = src1;
790 EXPECT_STREQ("", dest1.c_str());
791
792 // A normal ::string.
793 const ::string src2("Hi");
794 const String dest2 = src2;
795 EXPECT_STREQ("Hi", dest2.c_str());
796
797 // An ::string with an embedded NUL character.
798 const char src3[] = "Hello\0world.";
799 const String dest3 = ::string(src3, sizeof(src3));
800 EXPECT_STREQ("Hello", dest3.c_str());
801}
802
803TEST(StringTest, ConvertsToGlobalString) {
804 // An empty String.
805 const String src1("");
806 const ::string dest1 = src1;
807 EXPECT_EQ("", dest1);
808
809 // A normal String.
810 const String src2("Hi");
811 const ::string dest2 = src2;
812 EXPECT_EQ("Hi", dest2);
813}
814
815#endif // GTEST_HAS_GLOBAL_STRING
816
shiqian4b6829f2008-07-03 22:38:12 +0000817// Tests String::ShowCString().
818TEST(StringTest, ShowCString) {
819 EXPECT_STREQ("(null)", String::ShowCString(NULL));
820 EXPECT_STREQ("", String::ShowCString(""));
821 EXPECT_STREQ("foo", String::ShowCString("foo"));
822}
823
824// Tests String::ShowCStringQuoted().
825TEST(StringTest, ShowCStringQuoted) {
826 EXPECT_STREQ("(null)",
827 String::ShowCStringQuoted(NULL).c_str());
828 EXPECT_STREQ("\"\"",
829 String::ShowCStringQuoted("").c_str());
830 EXPECT_STREQ("\"foo\"",
831 String::ShowCStringQuoted("foo").c_str());
832}
833
834// Tests String::operator==().
835TEST(StringTest, Equals) {
836 const String null(NULL);
837 EXPECT_TRUE(null == NULL); // NOLINT
838 EXPECT_FALSE(null == ""); // NOLINT
839 EXPECT_FALSE(null == "bar"); // NOLINT
840
841 const String empty("");
842 EXPECT_FALSE(empty == NULL); // NOLINT
843 EXPECT_TRUE(empty == ""); // NOLINT
844 EXPECT_FALSE(empty == "bar"); // NOLINT
845
846 const String foo("foo");
847 EXPECT_FALSE(foo == NULL); // NOLINT
848 EXPECT_FALSE(foo == ""); // NOLINT
849 EXPECT_FALSE(foo == "bar"); // NOLINT
850 EXPECT_TRUE(foo == "foo"); // NOLINT
851}
852
853// Tests String::operator!=().
854TEST(StringTest, NotEquals) {
855 const String null(NULL);
856 EXPECT_FALSE(null != NULL); // NOLINT
857 EXPECT_TRUE(null != ""); // NOLINT
858 EXPECT_TRUE(null != "bar"); // NOLINT
859
860 const String empty("");
861 EXPECT_TRUE(empty != NULL); // NOLINT
862 EXPECT_FALSE(empty != ""); // NOLINT
863 EXPECT_TRUE(empty != "bar"); // NOLINT
864
865 const String foo("foo");
866 EXPECT_TRUE(foo != NULL); // NOLINT
867 EXPECT_TRUE(foo != ""); // NOLINT
868 EXPECT_TRUE(foo != "bar"); // NOLINT
869 EXPECT_FALSE(foo != "foo"); // NOLINT
870}
871
872// Tests String::EndsWith().
873TEST(StringTest, EndsWith) {
874 EXPECT_TRUE(String("foobar").EndsWith("bar"));
875 EXPECT_TRUE(String("foobar").EndsWith(""));
876 EXPECT_TRUE(String("").EndsWith(""));
877
878 EXPECT_FALSE(String("foobar").EndsWith("foo"));
879 EXPECT_FALSE(String("").EndsWith("foo"));
880}
881
882// Tests String::EndsWithCaseInsensitive().
883TEST(StringTest, EndsWithCaseInsensitive) {
884 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
885 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
886 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
887 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
888
889 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
890 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
891 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
892}
893
zhanyong.wan98efcc42009-04-28 00:28:09 +0000894// C++Builder's preprocessor is buggy; it fails to expand macros that
895// appear in macro parameters after wide char literals. Provide an alias
896// for NULL as a workaround.
897static const wchar_t* const kNull = NULL;
898
shiqiane8ff1482008-09-08 17:55:52 +0000899// Tests String::CaseInsensitiveWideCStringEquals
900TEST(StringTest, CaseInsensitiveWideCStringEquals) {
901 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000902 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
903 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
904 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
905 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +0000906 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
907 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
908 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
909}
910
shiqian4b6829f2008-07-03 22:38:12 +0000911// Tests that NULL can be assigned to a String.
912TEST(StringTest, CanBeAssignedNULL) {
913 const String src(NULL);
914 String dest;
915
916 dest = src;
917 EXPECT_STREQ(NULL, dest.c_str());
918}
919
920// Tests that the empty string "" can be assigned to a String.
921TEST(StringTest, CanBeAssignedEmpty) {
922 const String src("");
923 String dest;
924
925 dest = src;
926 EXPECT_STREQ("", dest.c_str());
927}
928
929// Tests that a non-empty string can be assigned to a String.
930TEST(StringTest, CanBeAssignedNonEmpty) {
931 const String src("hello");
932 String dest;
933
934 dest = src;
935 EXPECT_STREQ("hello", dest.c_str());
936}
937
938// Tests that a String can be assigned to itself.
939TEST(StringTest, CanBeAssignedSelf) {
940 String dest("hello");
941
942 dest = dest;
943 EXPECT_STREQ("hello", dest.c_str());
944}
945
zhanyong.wan4cd62602009-02-23 23:21:55 +0000946#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +0000947
948// Tests String::ShowWideCString().
949TEST(StringTest, ShowWideCString) {
950 EXPECT_STREQ("(null)",
951 String::ShowWideCString(NULL).c_str());
952 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
953 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
954}
955
956// Tests String::ShowWideCStringQuoted().
957TEST(StringTest, ShowWideCStringQuoted) {
958 EXPECT_STREQ("(null)",
959 String::ShowWideCStringQuoted(NULL).c_str());
960 EXPECT_STREQ("L\"\"",
961 String::ShowWideCStringQuoted(L"").c_str());
962 EXPECT_STREQ("L\"foo\"",
963 String::ShowWideCStringQuoted(L"foo").c_str());
964}
965
shiqiandd4a17b2008-07-31 18:34:08 +0000966#ifdef _WIN32_WCE
967TEST(StringTest, AnsiAndUtf16Null) {
968 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
969 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
970}
971
972TEST(StringTest, AnsiAndUtf16ConvertBasic) {
973 const char* ansi = String::Utf16ToAnsi(L"str");
974 EXPECT_STREQ("str", ansi);
975 delete [] ansi;
976 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +0000977 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +0000978 delete [] utf16;
979}
980
981TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
982 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
983 EXPECT_STREQ(".:\\ \"*?", ansi);
984 delete [] ansi;
985 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +0000986 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +0000987 delete [] utf16;
988}
989#endif // _WIN32_WCE
990
shiqian4b6829f2008-07-03 22:38:12 +0000991#endif // GTEST_OS_WINDOWS
992
993// Tests TestProperty construction.
994TEST(TestPropertyTest, StringValue) {
995 TestProperty property("key", "1");
996 EXPECT_STREQ("key", property.key());
997 EXPECT_STREQ("1", property.value());
998}
999
1000// Tests TestProperty replacing a value.
1001TEST(TestPropertyTest, ReplaceStringValue) {
1002 TestProperty property("key", "1");
1003 EXPECT_STREQ("1", property.value());
1004 property.SetValue("2");
1005 EXPECT_STREQ("2", property.value());
1006}
1007
zhanyong.wan98efcc42009-04-28 00:28:09 +00001008// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1009// functions (i.e. their definitions cannot be inlined at the call
1010// sites), or C++Builder won't compile the code.
1011static void AddFatalFailure() {
1012 FAIL() << "Expected fatal failure.";
1013}
1014
1015static void AddNonfatalFailure() {
1016 ADD_FAILURE() << "Expected non-fatal failure.";
1017}
1018
shiqiane44602e2008-10-11 07:20:02 +00001019class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001020 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001021 enum FailureMode {
1022 FATAL_FAILURE,
1023 NONFATAL_FAILURE
1024 };
1025 static void AddFailure(FailureMode failure) {
1026 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001027 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001028 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001029 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001030 }
1031 }
shiqian4b6829f2008-07-03 22:38:12 +00001032};
1033
shiqian4b6829f2008-07-03 22:38:12 +00001034// Tests that ScopedFakeTestPartResultReporter intercepts test
1035// failures.
shiqiane44602e2008-10-11 07:20:02 +00001036TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001037 TestPartResultArray results;
1038 {
shiqiane44602e2008-10-11 07:20:02 +00001039 ScopedFakeTestPartResultReporter reporter(
1040 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1041 &results);
1042 AddFailure(NONFATAL_FAILURE);
1043 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001044 }
1045
1046 EXPECT_EQ(2, results.size());
1047 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1048 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1049}
1050
shiqiane44602e2008-10-11 07:20:02 +00001051TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1052 TestPartResultArray results;
1053 {
1054 // Tests, that the deprecated constructor still works.
1055 ScopedFakeTestPartResultReporter reporter(&results);
1056 AddFailure(NONFATAL_FAILURE);
1057 }
1058 EXPECT_EQ(1, results.size());
1059}
1060
1061#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1062
1063class ScopedFakeTestPartResultReporterWithThreadsTest
1064 : public ScopedFakeTestPartResultReporterTest {
1065 protected:
1066 static void AddFailureInOtherThread(FailureMode failure) {
1067 pthread_t tid;
1068 pthread_create(&tid,
1069 NULL,
1070 ScopedFakeTestPartResultReporterWithThreadsTest::
1071 FailureThread,
1072 &failure);
1073 pthread_join(tid, NULL);
1074 }
1075 private:
1076 static void* FailureThread(void* attr) {
1077 FailureMode* failure = static_cast<FailureMode*>(attr);
1078 AddFailure(*failure);
1079 return NULL;
1080 }
1081};
1082
1083TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1084 InterceptsTestFailuresInAllThreads) {
1085 TestPartResultArray results;
1086 {
1087 ScopedFakeTestPartResultReporter reporter(
1088 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1089 AddFailure(NONFATAL_FAILURE);
1090 AddFailure(FATAL_FAILURE);
1091 AddFailureInOtherThread(NONFATAL_FAILURE);
1092 AddFailureInOtherThread(FATAL_FAILURE);
1093 }
1094
1095 EXPECT_EQ(4, results.size());
1096 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1097 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1098 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1099 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1100}
1101
1102#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1103
zhanyong.wan98efcc42009-04-28 00:28:09 +00001104// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1105// work even if the failure is generated in a called function rather than
1106// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001107
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001108typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001109
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001110TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001111 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001112}
1113
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001114TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1115 // We have another test below to verify that the macro catches fatal
1116 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001117 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001118 "Expected fatal failure.");
1119}
1120
zhanyong.wan98efcc42009-04-28 00:28:09 +00001121#ifdef __BORLANDC__
1122// Silences warnings: "Condition is always true"
1123#pragma option push -w-ccc
1124#endif
1125
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001126// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1127// function even when the statement in it contains ASSERT_*.
1128
1129int NonVoidFunction() {
1130 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1131 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1132 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001133}
1134
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001135TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1136 NonVoidFunction();
1137}
1138
1139// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1140// current function even though 'statement' generates a fatal failure.
1141
1142void DoesNotAbortHelper(bool* aborted) {
1143 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1144 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1145
1146 *aborted = false;
1147}
1148
zhanyong.wan98efcc42009-04-28 00:28:09 +00001149#ifdef __BORLANDC__
1150// Restores warnings after previous "#pragma option push" supressed them
1151#pragma option pop
1152#endif
1153
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001154TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1155 bool aborted = true;
1156 DoesNotAbortHelper(&aborted);
1157 EXPECT_FALSE(aborted);
1158}
1159
1160// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1161// statement that contains a macro which expands to code containing an
1162// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001163
1164static int global_var = 0;
1165#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1166
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001167TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001168#ifndef __BORLANDC__
1169 // ICE's in C++Builder 2007.
shiqiane44602e2008-10-11 07:20:02 +00001170 EXPECT_FATAL_FAILURE({
1171 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001172 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001173 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001174#endif
shiqiane44602e2008-10-11 07:20:02 +00001175
1176 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1177 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001178 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001179 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001180}
shiqiane44602e2008-10-11 07:20:02 +00001181
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001182// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1183
1184typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1185
1186TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001187 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001188 "Expected non-fatal failure.");
1189}
1190
1191TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1192 // We have another test below to verify that the macro catches
1193 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001194 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001195 "Expected non-fatal failure.");
1196}
1197
1198// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1199// statement that contains a macro which expands to code containing an
1200// unprotected comma.
1201TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001202 EXPECT_NONFATAL_FAILURE({
1203 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001204 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001205 }, "");
1206
1207 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1208 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001209 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001210 }, "");
1211}
1212
1213#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1214
1215typedef ScopedFakeTestPartResultReporterWithThreadsTest
1216 ExpectFailureWithThreadsTest;
1217
1218TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1219 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1220 "Expected fatal failure.");
1221}
1222
1223TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1224 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1225 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1226}
1227
1228#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1229
shiqian4b6829f2008-07-03 22:38:12 +00001230// Tests the TestResult class
1231
1232// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001233class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001234 protected:
zhanyong.wana8a582f2009-07-13 19:25:02 +00001235 typedef Vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001236
1237 // We make use of 2 TestPartResult objects,
1238 TestPartResult * pr1, * pr2;
1239
1240 // ... and 3 TestResult objects.
1241 TestResult * r0, * r1, * r2;
1242
1243 virtual void SetUp() {
1244 // pr1 is for success.
shiqian760af5c2008-08-06 21:43:15 +00001245 pr1 = new TestPartResult(TPRT_SUCCESS, "foo/bar.cc", 10, "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001246
1247 // pr2 is for fatal failure.
shiqian760af5c2008-08-06 21:43:15 +00001248 pr2 = new TestPartResult(TPRT_FATAL_FAILURE, "foo/bar.cc",
1249 -1, // This line number means "unknown"
1250 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001251
1252 // Creates the TestResult objects.
1253 r0 = new TestResult();
1254 r1 = new TestResult();
1255 r2 = new TestResult();
1256
1257 // In order to test TestResult, we need to modify its internal
zhanyong.wana8a582f2009-07-13 19:25:02 +00001258 // state, in particular the TestPartResult Vector it holds.
1259 // test_part_results() returns a const reference to this Vector.
shiqian4b6829f2008-07-03 22:38:12 +00001260 // We cast it to a non-const object s.t. it can be modified (yes,
1261 // this is a hack).
zhanyong.wana8a582f2009-07-13 19:25:02 +00001262 TPRVector* results1 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001263 &TestResultAccessor::test_part_results(*r1));
zhanyong.wana8a582f2009-07-13 19:25:02 +00001264 TPRVector* results2 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001265 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001266
1267 // r0 is an empty TestResult.
1268
1269 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001270 results1->PushBack(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001271
1272 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001273 results2->PushBack(*pr1);
1274 results2->PushBack(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001275 }
1276
1277 virtual void TearDown() {
1278 delete pr1;
1279 delete pr2;
1280
1281 delete r0;
1282 delete r1;
1283 delete r2;
1284 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001285
1286 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001287 static void CompareTestPartResult(const TestPartResult& expected,
1288 const TestPartResult& actual) {
1289 EXPECT_EQ(expected.type(), actual.type());
1290 EXPECT_STREQ(expected.file_name(), actual.file_name());
1291 EXPECT_EQ(expected.line_number(), actual.line_number());
1292 EXPECT_STREQ(expected.summary(), actual.summary());
1293 EXPECT_STREQ(expected.message(), actual.message());
1294 EXPECT_EQ(expected.passed(), actual.passed());
1295 EXPECT_EQ(expected.failed(), actual.failed());
1296 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1297 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001298 }
shiqian4b6829f2008-07-03 22:38:12 +00001299};
1300
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001301// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001302TEST_F(TestResultTest, test_part_results) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001303 ASSERT_EQ(0, r0->total_part_count());
1304 ASSERT_EQ(1, r1->total_part_count());
1305 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001306}
1307
zhanyong.wan9644db82009-06-24 23:02:50 +00001308// Tests TestResult::successful_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001309TEST_F(TestResultTest, successful_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001310 ASSERT_EQ(0, r0->successful_part_count());
1311 ASSERT_EQ(1, r1->successful_part_count());
1312 ASSERT_EQ(1, r2->successful_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001313}
1314
zhanyong.wan9644db82009-06-24 23:02:50 +00001315// Tests TestResult::failed_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001316TEST_F(TestResultTest, failed_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001317 ASSERT_EQ(0, r0->failed_part_count());
1318 ASSERT_EQ(0, r1->failed_part_count());
1319 ASSERT_EQ(1, r2->failed_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001320}
1321
vladlosevf904a612008-11-20 01:40:35 +00001322// Tests testing::internal::GetFailedPartCount().
1323TEST_F(TestResultTest, GetFailedPartCount) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001324 ASSERT_EQ(0, GetFailedPartCount(r0));
1325 ASSERT_EQ(0, GetFailedPartCount(r1));
1326 ASSERT_EQ(1, GetFailedPartCount(r2));
vladlosevf904a612008-11-20 01:40:35 +00001327}
1328
zhanyong.wan9644db82009-06-24 23:02:50 +00001329// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001330TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001331 ASSERT_EQ(0, r0->total_part_count());
1332 ASSERT_EQ(1, r1->total_part_count());
1333 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001334}
1335
zhanyong.wan9644db82009-06-24 23:02:50 +00001336// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001337TEST_F(TestResultTest, Passed) {
1338 ASSERT_TRUE(r0->Passed());
1339 ASSERT_TRUE(r1->Passed());
1340 ASSERT_FALSE(r2->Passed());
1341}
1342
zhanyong.wan9644db82009-06-24 23:02:50 +00001343// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001344TEST_F(TestResultTest, Failed) {
1345 ASSERT_FALSE(r0->Failed());
1346 ASSERT_FALSE(r1->Failed());
1347 ASSERT_TRUE(r2->Failed());
1348}
1349
zhanyong.wan9644db82009-06-24 23:02:50 +00001350// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001351
1352typedef TestResultTest TestResultDeathTest;
1353
1354TEST_F(TestResultDeathTest, GetTestPartResult) {
1355 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1356 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1357 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1358 r2->GetTestPartResult(2),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001359 "Invalid Vector index 2: must be in range \\[0, 1\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001360 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1361 r2->GetTestPartResult(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001362 "Invalid Vector index -1: must be in range \\[0, 1\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001363}
1364
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001365// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001366TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1367 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001368 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001369}
1370
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001371// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001372TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1373 TestResult test_result;
1374 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001375 TestResultAccessor::RecordProperty(&test_result, property);
1376 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001377 const TestProperty& actual_property = test_result.GetTestProperty(0);
1378 EXPECT_STREQ("key_1", actual_property.key());
1379 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001380}
1381
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001382// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001383TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1384 TestResult test_result;
1385 TestProperty property_1("key_1", "1");
1386 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001387 TestResultAccessor::RecordProperty(&test_result, property_1);
1388 TestResultAccessor::RecordProperty(&test_result, property_2);
1389 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001390 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1391 EXPECT_STREQ("key_1", actual_property_1.key());
1392 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001393
zhanyong.wan449f84d2009-07-01 22:55:05 +00001394 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1395 EXPECT_STREQ("key_2", actual_property_2.key());
1396 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001397}
1398
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001399// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001400TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1401 TestResult test_result;
1402 TestProperty property_1_1("key_1", "1");
1403 TestProperty property_2_1("key_2", "2");
1404 TestProperty property_1_2("key_1", "12");
1405 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001406 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1407 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1408 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1409 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001410
zhanyong.wan9644db82009-06-24 23:02:50 +00001411 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001412 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1413 EXPECT_STREQ("key_1", actual_property_1.key());
1414 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001415
zhanyong.wan449f84d2009-07-01 22:55:05 +00001416 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1417 EXPECT_STREQ("key_2", actual_property_2.key());
1418 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001419}
1420
1421// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001422TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001423 TestResult test_result;
1424 TestProperty property_1("key_1", "1");
1425 TestProperty property_2("key_2", "2");
1426 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001427 TestResultAccessor::RecordProperty(&test_result, property_1);
1428 TestResultAccessor::RecordProperty(&test_result, property_2);
1429 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001430
zhanyong.wan449f84d2009-07-01 22:55:05 +00001431 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1432 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1433 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001434
zhanyong.wan449f84d2009-07-01 22:55:05 +00001435 EXPECT_STREQ("key_1", fetched_property_1.key());
1436 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001437
zhanyong.wan449f84d2009-07-01 22:55:05 +00001438 EXPECT_STREQ("key_2", fetched_property_2.key());
1439 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001440
zhanyong.wan449f84d2009-07-01 22:55:05 +00001441 EXPECT_STREQ("key_3", fetched_property_3.key());
1442 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001443
zhanyong.wan449f84d2009-07-01 22:55:05 +00001444 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1445 test_result.GetTestProperty(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001446 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001447 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1448 test_result.GetTestProperty(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001449 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001450}
1451
shiqian4b6829f2008-07-03 22:38:12 +00001452// When a property using a reserved key is supplied to this function, it tests
1453// that a non-fatal failure is added, a fatal failure is not added, and that the
1454// property is not recorded.
1455void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1456 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001457 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001458 EXPECT_NONFATAL_FAILURE(
1459 TestResultAccessor::RecordProperty(&test_result, property),
1460 "Reserved key");
1461 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001462}
1463
1464// Attempting to recording a property with the Reserved literal "name"
1465// should add a non-fatal failure and the property should not be recorded.
1466TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1467 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1468}
1469
1470// Attempting to recording a property with the Reserved literal "status"
1471// should add a non-fatal failure and the property should not be recorded.
1472TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1473 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1474}
1475
1476// Attempting to recording a property with the Reserved literal "time"
1477// should add a non-fatal failure and the property should not be recorded.
1478TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1479 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1480}
1481
1482// Attempting to recording a property with the Reserved literal "classname"
1483// should add a non-fatal failure and the property should not be recorded.
1484TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1485 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1486}
1487
1488// Tests that GTestFlagSaver works on Windows and Mac.
1489
shiqian760af5c2008-08-06 21:43:15 +00001490class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001491 protected:
1492 // Saves the Google Test flags such that we can restore them later, and
1493 // then sets them to their default values. This will be called
1494 // before the first test in this test case is run.
1495 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001496 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001497
shiqianca6949f2009-01-10 01:16:33 +00001498 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001499 GTEST_FLAG(break_on_failure) = false;
1500 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001501 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001502 GTEST_FLAG(color) = "auto";
1503 GTEST_FLAG(filter) = "";
1504 GTEST_FLAG(list_tests) = false;
1505 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001506 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001507 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001508 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001509 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001510 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001511 }
1512
1513 // Restores the Google Test flags that the tests have modified. This will
1514 // be called after the last test in this test case is run.
1515 static void TearDownTestCase() {
1516 delete saver_;
1517 saver_ = NULL;
1518 }
1519
1520 // Verifies that the Google Test flags have their default values, and then
1521 // modifies each of them.
1522 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001523 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001524 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1525 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1526 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001527 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001528 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1529 EXPECT_FALSE(GTEST_FLAG(list_tests));
1530 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001531 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001532 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001533 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001534 EXPECT_FALSE(GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001535 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001536
shiqianca6949f2009-01-10 01:16:33 +00001537 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001538 GTEST_FLAG(break_on_failure) = true;
1539 GTEST_FLAG(catch_exceptions) = true;
1540 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001541 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001542 GTEST_FLAG(filter) = "abc";
1543 GTEST_FLAG(list_tests) = true;
1544 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001545 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001546 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001547 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001548 GTEST_FLAG(shuffle) = true;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001549 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001550 }
1551 private:
1552 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001553 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001554};
1555
shiqian760af5c2008-08-06 21:43:15 +00001556GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001557
1558// Google Test doesn't guarantee the order of tests. The following two
1559// tests are designed to work regardless of their order.
1560
1561// Modifies the Google Test flags in the test body.
1562TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1563 VerifyAndModifyFlags();
1564}
1565
1566// Verifies that the Google Test flags in the body of the previous test were
1567// restored to their original values.
1568TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1569 VerifyAndModifyFlags();
1570}
1571
1572// Sets an environment variable with the given name to the given
1573// value. If the value argument is "", unsets the environment
1574// variable. The caller must ensure that both arguments are not NULL.
1575static void SetEnv(const char* name, const char* value) {
1576#ifdef _WIN32_WCE
1577 // Environment variables are not supported on Windows CE.
1578 return;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001579#elif defined(__BORLANDC__)
1580 // C++Builder's putenv only stores a pointer to its parameter; we have to
1581 // ensure that the string remains valid as long as it might be needed.
1582 // We use an std::map to do so.
1583 static std::map<String, String*> added_env;
1584
1585 // Because putenv stores a pointer to the string buffer, we can't delete the
1586 // previous string (if present) until after it's replaced.
1587 String *prev_env = NULL;
1588 if (added_env.find(name) != added_env.end()) {
1589 prev_env = added_env[name];
1590 }
1591 added_env[name] = new String((Message() << name << "=" << value).GetString());
1592 putenv(added_env[name]->c_str());
1593 delete prev_env;
1594
zhanyong.wan4cd62602009-02-23 23:21:55 +00001595#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001596 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001597#else
1598 if (*value == '\0') {
1599 unsetenv(name);
1600 } else {
1601 setenv(name, value, 1);
1602 }
1603#endif
1604}
1605
1606#ifndef _WIN32_WCE
1607// Environment variables are not supported on Windows CE.
1608
shiqian760af5c2008-08-06 21:43:15 +00001609using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001610
1611// Tests Int32FromGTestEnv().
1612
1613// Tests that Int32FromGTestEnv() returns the default value when the
1614// environment variable is not set.
1615TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001616 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001617 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1618}
1619
1620// Tests that Int32FromGTestEnv() returns the default value when the
1621// environment variable overflows as an Int32.
1622TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1623 printf("(expecting 2 warnings)\n");
1624
zhanyong.wan4cd62602009-02-23 23:21:55 +00001625 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001626 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1627
zhanyong.wan4cd62602009-02-23 23:21:55 +00001628 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001629 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1630}
1631
1632// Tests that Int32FromGTestEnv() returns the default value when the
1633// environment variable does not represent a valid decimal integer.
1634TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1635 printf("(expecting 2 warnings)\n");
1636
zhanyong.wan4cd62602009-02-23 23:21:55 +00001637 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001638 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1639
zhanyong.wan4cd62602009-02-23 23:21:55 +00001640 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001641 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1642}
1643
1644// Tests that Int32FromGTestEnv() parses and returns the value of the
1645// environment variable when it represents a valid decimal integer in
1646// the range of an Int32.
1647TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001648 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001649 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1650
zhanyong.wan4cd62602009-02-23 23:21:55 +00001651 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001652 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1653}
1654#endif // !defined(_WIN32_WCE)
1655
1656// Tests ParseInt32Flag().
1657
1658// Tests that ParseInt32Flag() returns false and doesn't change the
1659// output value when the flag has wrong format
1660TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1661 Int32 value = 123;
1662 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1663 EXPECT_EQ(123, value);
1664
1665 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1666 EXPECT_EQ(123, value);
1667}
1668
1669// Tests that ParseInt32Flag() returns false and doesn't change the
1670// output value when the flag overflows as an Int32.
1671TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1672 printf("(expecting 2 warnings)\n");
1673
1674 Int32 value = 123;
1675 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1676 EXPECT_EQ(123, value);
1677
1678 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1679 EXPECT_EQ(123, value);
1680}
1681
1682// Tests that ParseInt32Flag() returns false and doesn't change the
1683// output value when the flag does not represent a valid decimal
1684// integer.
1685TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1686 printf("(expecting 2 warnings)\n");
1687
1688 Int32 value = 123;
1689 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1690 EXPECT_EQ(123, value);
1691
1692 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1693 EXPECT_EQ(123, value);
1694}
1695
1696// Tests that ParseInt32Flag() parses the value of the flag and
1697// returns true when the flag represents a valid decimal integer in
1698// the range of an Int32.
1699TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1700 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001701 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001702 EXPECT_EQ(456, value);
1703
zhanyong.wan98efcc42009-04-28 00:28:09 +00001704 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1705 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001706 EXPECT_EQ(-789, value);
1707}
1708
zhanyong.wan905074c2009-02-09 18:05:21 +00001709// Tests that Int32FromEnvOrDie() parses the value of the var or
1710// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001711// Environment variables are not supported on Windows CE.
1712#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001713TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001714 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1715 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1716 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1717 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1718 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001719}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001720#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001721
1722// Tests that Int32FromEnvOrDie() aborts with an error message
1723// if the variable is not an Int32.
1724TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001725 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001726 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1727 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1728 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001729}
1730
1731// Tests that Int32FromEnvOrDie() aborts with an error message
1732// if the variable cannot be represnted by an Int32.
1733TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001734 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001735 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1736 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1737 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001738}
1739
zhanyong.wan905074c2009-02-09 18:05:21 +00001740// Tests that ShouldRunTestOnShard() selects all tests
1741// where there is 1 shard.
1742TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1743 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1744 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1745 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1746 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1747 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1748}
1749
1750class ShouldShardTest : public testing::Test {
1751 protected:
1752 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001753 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1754 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00001755 }
1756
1757 virtual void TearDown() {
1758 SetEnv(index_var_, "");
1759 SetEnv(total_var_, "");
1760 }
1761
1762 const char* index_var_;
1763 const char* total_var_;
1764};
1765
1766// Tests that sharding is disabled if neither of the environment variables
1767// are set.
1768TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1769 SetEnv(index_var_, "");
1770 SetEnv(total_var_, "");
1771
1772 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1773 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1774}
1775
1776// Tests that sharding is not enabled if total_shards == 1.
1777TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1778 SetEnv(index_var_, "0");
1779 SetEnv(total_var_, "1");
1780 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1781 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1782}
1783
1784// Tests that sharding is enabled if total_shards > 1 and
1785// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001786// Environment variables are not supported on Windows CE.
1787#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001788TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1789 SetEnv(index_var_, "4");
1790 SetEnv(total_var_, "22");
1791 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1792 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1793
1794 SetEnv(index_var_, "8");
1795 SetEnv(total_var_, "9");
1796 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1797 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1798
1799 SetEnv(index_var_, "0");
1800 SetEnv(total_var_, "9");
1801 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1802 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1803}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001804#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001805
1806// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001807
1808typedef ShouldShardTest ShouldShardDeathTest;
1809
1810TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00001811 SetEnv(index_var_, "4");
1812 SetEnv(total_var_, "4");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001813 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1814 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001815
1816 SetEnv(index_var_, "4");
1817 SetEnv(total_var_, "-2");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001818 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1819 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001820
1821 SetEnv(index_var_, "5");
1822 SetEnv(total_var_, "");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001823 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1824 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001825
1826 SetEnv(index_var_, "");
1827 SetEnv(total_var_, "5");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001828 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1829 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001830}
1831
zhanyong.wan905074c2009-02-09 18:05:21 +00001832// Tests that ShouldRunTestOnShard is a partition when 5
1833// shards are used.
1834TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1835 // Choose an arbitrary number of tests and shards.
1836 const int num_tests = 17;
1837 const int num_shards = 5;
1838
1839 // Check partitioning: each test should be on exactly 1 shard.
1840 for (int test_id = 0; test_id < num_tests; test_id++) {
1841 int prev_selected_shard_index = -1;
1842 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1843 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1844 if (prev_selected_shard_index < 0) {
1845 prev_selected_shard_index = shard_index;
1846 } else {
1847 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1848 << shard_index << " are both selected to run test " << test_id;
1849 }
1850 }
1851 }
1852 }
1853
1854 // Check balance: This is not required by the sharding protocol, but is a
1855 // desirable property for performance.
1856 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1857 int num_tests_on_shard = 0;
1858 for (int test_id = 0; test_id < num_tests; test_id++) {
1859 num_tests_on_shard +=
1860 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1861 }
1862 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1863 }
1864}
1865
shiqian4b6829f2008-07-03 22:38:12 +00001866// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00001867// Test class, there are no separate tests for the following classes
1868// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00001869//
1870// TestCase, UnitTest, UnitTestResultPrinter.
1871//
1872// Similarly, there are no separate tests for the following macros:
1873//
1874// TEST, TEST_F, RUN_ALL_TESTS
1875
shiqianc3b4de32008-09-12 04:01:37 +00001876TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1877 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1878 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1879}
1880
shiqian4b6829f2008-07-03 22:38:12 +00001881// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
1882// of various arities. They do not attempt to be exhaustive. Rather,
1883// view them as smoke tests that can be easily reviewed and verified.
1884// A more complete set of tests for predicate assertions can be found
1885// in gtest_pred_impl_unittest.cc.
1886
1887// First, some predicates and predicate-formatters needed by the tests.
1888
1889// Returns true iff the argument is an even number.
1890bool IsEven(int n) {
1891 return (n % 2) == 0;
1892}
1893
1894// A functor that returns true iff the argument is an even number.
1895struct IsEvenFunctor {
1896 bool operator()(int n) { return IsEven(n); }
1897};
1898
1899// A predicate-formatter function that asserts the argument is an even
1900// number.
shiqian760af5c2008-08-06 21:43:15 +00001901AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00001902 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00001903 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001904 }
1905
shiqian760af5c2008-08-06 21:43:15 +00001906 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001907 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001908 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001909}
1910
1911// A predicate-formatter functor that asserts the argument is an even
1912// number.
1913struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00001914 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00001915 return AssertIsEven(expr, n);
1916 }
1917};
1918
1919// Returns true iff the sum of the arguments is an even number.
1920bool SumIsEven2(int n1, int n2) {
1921 return IsEven(n1 + n2);
1922}
1923
1924// A functor that returns true iff the sum of the arguments is an even
1925// number.
1926struct SumIsEven3Functor {
1927 bool operator()(int n1, int n2, int n3) {
1928 return IsEven(n1 + n2 + n3);
1929 }
1930};
1931
1932// A predicate-formatter function that asserts the sum of the
1933// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00001934AssertionResult AssertSumIsEven4(
1935 const char* e1, const char* e2, const char* e3, const char* e4,
1936 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00001937 const int sum = n1 + n2 + n3 + n4;
1938 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00001939 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001940 }
1941
shiqian760af5c2008-08-06 21:43:15 +00001942 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001943 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
1944 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
1945 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001946 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001947}
1948
1949// A predicate-formatter functor that asserts the sum of the arguments
1950// is an even number.
1951struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00001952 AssertionResult operator()(
1953 const char* e1, const char* e2, const char* e3, const char* e4,
1954 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00001955 const int sum = n1 + n2 + n3 + n4 + n5;
1956 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00001957 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001958 }
1959
shiqian760af5c2008-08-06 21:43:15 +00001960 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001961 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
1962 << " ("
1963 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
1964 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001965 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001966 }
1967};
1968
1969
1970// Tests unary predicate assertions.
1971
1972// Tests unary predicate assertions that don't use a custom formatter.
1973TEST(Pred1Test, WithoutFormat) {
1974 // Success cases.
1975 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
1976 ASSERT_PRED1(IsEven, 4);
1977
1978 // Failure cases.
1979 EXPECT_NONFATAL_FAILURE({ // NOLINT
1980 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
1981 }, "This failure is expected.");
1982 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
1983 "evaluates to false");
1984}
1985
1986// Tests unary predicate assertions that use a custom formatter.
1987TEST(Pred1Test, WithFormat) {
1988 // Success cases.
1989 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
1990 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
1991 << "This failure is UNEXPECTED!";
1992
1993 // Failure cases.
1994 const int n = 5;
1995 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
1996 "n evaluates to 5, which is not even.");
1997 EXPECT_FATAL_FAILURE({ // NOLINT
1998 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
1999 }, "This failure is expected.");
2000}
2001
2002// Tests that unary predicate assertions evaluates their arguments
2003// exactly once.
2004TEST(Pred1Test, SingleEvaluationOnFailure) {
2005 // A success case.
2006 static int n = 0;
2007 EXPECT_PRED1(IsEven, n++);
2008 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2009
2010 // A failure case.
2011 EXPECT_FATAL_FAILURE({ // NOLINT
2012 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2013 << "This failure is expected.";
2014 }, "This failure is expected.");
2015 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2016}
2017
2018
2019// Tests predicate assertions whose arity is >= 2.
2020
2021// Tests predicate assertions that don't use a custom formatter.
2022TEST(PredTest, WithoutFormat) {
2023 // Success cases.
2024 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2025 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2026
2027 // Failure cases.
2028 const int n1 = 1;
2029 const int n2 = 2;
2030 EXPECT_NONFATAL_FAILURE({ // NOLINT
2031 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2032 }, "This failure is expected.");
2033 EXPECT_FATAL_FAILURE({ // NOLINT
2034 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2035 }, "evaluates to false");
2036}
2037
2038// Tests predicate assertions that use a custom formatter.
2039TEST(PredTest, WithFormat) {
2040 // Success cases.
2041 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2042 "This failure is UNEXPECTED!";
2043 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2044
2045 // Failure cases.
2046 const int n1 = 1;
2047 const int n2 = 2;
2048 const int n3 = 4;
2049 const int n4 = 6;
2050 EXPECT_NONFATAL_FAILURE({ // NOLINT
2051 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2052 }, "evaluates to 13, which is not even.");
2053 EXPECT_FATAL_FAILURE({ // NOLINT
2054 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2055 << "This failure is expected.";
2056 }, "This failure is expected.");
2057}
2058
2059// Tests that predicate assertions evaluates their arguments
2060// exactly once.
2061TEST(PredTest, SingleEvaluationOnFailure) {
2062 // A success case.
2063 int n1 = 0;
2064 int n2 = 0;
2065 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2066 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2067 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2068
2069 // Another success case.
2070 n1 = n2 = 0;
2071 int n3 = 0;
2072 int n4 = 0;
2073 int n5 = 0;
2074 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2075 n1++, n2++, n3++, n4++, n5++)
2076 << "This failure is UNEXPECTED!";
2077 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2078 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2079 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2080 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2081 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2082
2083 // A failure case.
2084 n1 = n2 = n3 = 0;
2085 EXPECT_NONFATAL_FAILURE({ // NOLINT
2086 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2087 << "This failure is expected.";
2088 }, "This failure is expected.");
2089 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2090 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2091 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2092
2093 // Another failure case.
2094 n1 = n2 = n3 = n4 = 0;
2095 EXPECT_NONFATAL_FAILURE({ // NOLINT
2096 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2097 }, "evaluates to 1, which is not even.");
2098 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2099 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2100 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2101 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2102}
2103
2104
2105// Some helper functions for testing using overloaded/template
2106// functions with ASSERT_PREDn and EXPECT_PREDn.
2107
2108bool IsPositive(int n) {
2109 return n > 0;
2110}
2111
2112bool IsPositive(double x) {
2113 return x > 0;
2114}
2115
2116template <typename T>
2117bool IsNegative(T x) {
2118 return x < 0;
2119}
2120
2121template <typename T1, typename T2>
2122bool GreaterThan(T1 x1, T2 x2) {
2123 return x1 > x2;
2124}
2125
2126// Tests that overloaded functions can be used in *_PRED* as long as
2127// their types are explicitly specified.
2128TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002129 // C++Builder requires C-style casts rather than static_cast.
2130 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2131 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002132}
2133
2134// Tests that template functions can be used in *_PRED* as long as
2135// their types are explicitly specified.
2136TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2137 EXPECT_PRED1(IsNegative<int>, -5);
2138 // Makes sure that we can handle templates with more than one
2139 // parameter.
2140 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2141}
2142
2143
2144// Some helper functions for testing using overloaded/template
2145// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2146
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002147AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002148 return n > 0 ? AssertionSuccess() :
2149 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002150}
2151
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002152AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002153 return x > 0 ? AssertionSuccess() :
2154 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002155}
2156
2157template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002158AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002159 return x < 0 ? AssertionSuccess() :
2160 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002161}
2162
2163template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002164AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002165 const T1& x1, const T2& x2) {
2166 return x1 == x2 ? AssertionSuccess() :
2167 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002168}
2169
2170// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002171// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002172TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2173 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2174 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2175}
2176
2177// Tests that template functions can be used in *_PRED_FORMAT* without
2178// explicitly specifying their types.
2179TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2180 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2181 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2182}
2183
2184
2185// Tests string assertions.
2186
2187// Tests ASSERT_STREQ with non-NULL arguments.
2188TEST(StringAssertionTest, ASSERT_STREQ) {
2189 const char * const p1 = "good";
2190 ASSERT_STREQ(p1, p1);
2191
2192 // Let p2 have the same content as p1, but be at a different address.
2193 const char p2[] = "good";
2194 ASSERT_STREQ(p1, p2);
2195
2196 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2197 "Expected: \"bad\"");
2198}
2199
2200// Tests ASSERT_STREQ with NULL arguments.
2201TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2202 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2203 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2204 "non-null");
2205}
2206
2207// Tests ASSERT_STREQ with NULL arguments.
2208TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2209 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2210 "non-null");
2211}
2212
2213// Tests ASSERT_STRNE.
2214TEST(StringAssertionTest, ASSERT_STRNE) {
2215 ASSERT_STRNE("hi", "Hi");
2216 ASSERT_STRNE("Hi", NULL);
2217 ASSERT_STRNE(NULL, "Hi");
2218 ASSERT_STRNE("", NULL);
2219 ASSERT_STRNE(NULL, "");
2220 ASSERT_STRNE("", "Hi");
2221 ASSERT_STRNE("Hi", "");
2222 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2223 "\"Hi\" vs \"Hi\"");
2224}
2225
2226// Tests ASSERT_STRCASEEQ.
2227TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2228 ASSERT_STRCASEEQ("hi", "Hi");
2229 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2230
2231 ASSERT_STRCASEEQ("", "");
2232 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2233 "(ignoring case)");
2234}
2235
2236// Tests ASSERT_STRCASENE.
2237TEST(StringAssertionTest, ASSERT_STRCASENE) {
2238 ASSERT_STRCASENE("hi1", "Hi2");
2239 ASSERT_STRCASENE("Hi", NULL);
2240 ASSERT_STRCASENE(NULL, "Hi");
2241 ASSERT_STRCASENE("", NULL);
2242 ASSERT_STRCASENE(NULL, "");
2243 ASSERT_STRCASENE("", "Hi");
2244 ASSERT_STRCASENE("Hi", "");
2245 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2246 "(ignoring case)");
2247}
2248
2249// Tests *_STREQ on wide strings.
2250TEST(StringAssertionTest, STREQ_Wide) {
2251 // NULL strings.
2252 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2253
2254 // Empty strings.
2255 ASSERT_STREQ(L"", L"");
2256
2257 // Non-null vs NULL.
2258 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2259 "non-null");
2260
2261 // Equal strings.
2262 EXPECT_STREQ(L"Hi", L"Hi");
2263
2264 // Unequal strings.
2265 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2266 "Abc");
2267
2268 // Strings containing wide characters.
2269 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2270 "abc");
2271}
2272
2273// Tests *_STRNE on wide strings.
2274TEST(StringAssertionTest, STRNE_Wide) {
2275 // NULL strings.
2276 EXPECT_NONFATAL_FAILURE({ // NOLINT
2277 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2278 }, "");
2279
2280 // Empty strings.
2281 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2282 "L\"\"");
2283
2284 // Non-null vs NULL.
2285 ASSERT_STRNE(L"non-null", NULL);
2286
2287 // Equal strings.
2288 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2289 "L\"Hi\"");
2290
2291 // Unequal strings.
2292 EXPECT_STRNE(L"abc", L"Abc");
2293
2294 // Strings containing wide characters.
2295 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2296 "abc");
2297}
2298
2299// Tests for ::testing::IsSubstring().
2300
2301// Tests that IsSubstring() returns the correct result when the input
2302// argument type is const char*.
2303TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002304 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2305 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2306 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2307
2308 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2309 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2310}
2311
2312// Tests that IsSubstring() returns the correct result when the input
2313// argument type is const wchar_t*.
2314TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002315 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2316 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002317 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2318
2319 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2320 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2321}
2322
2323// Tests that IsSubstring() generates the correct message when the input
2324// argument type is const char*.
2325TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2326 EXPECT_STREQ("Value of: needle_expr\n"
2327 " Actual: \"needle\"\n"
2328 "Expected: a substring of haystack_expr\n"
2329 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002330 IsSubstring("needle_expr", "haystack_expr",
2331 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002332}
2333
2334#if GTEST_HAS_STD_STRING
2335
2336// Tests that IsSubstring returns the correct result when the input
2337// argument type is ::std::string.
2338TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002339 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2340 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002341}
2342
2343#endif // GTEST_HAS_STD_STRING
2344
2345#if GTEST_HAS_STD_WSTRING
2346// Tests that IsSubstring returns the correct result when the input
2347// argument type is ::std::wstring.
2348TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002349 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2350 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2351}
2352
2353// Tests that IsSubstring() generates the correct message when the input
2354// argument type is ::std::wstring.
2355TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2356 EXPECT_STREQ("Value of: needle_expr\n"
2357 " Actual: L\"needle\"\n"
2358 "Expected: a substring of haystack_expr\n"
2359 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002360 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002361 "needle_expr", "haystack_expr",
2362 ::std::wstring(L"needle"), L"haystack").failure_message());
2363}
2364
2365#endif // GTEST_HAS_STD_WSTRING
2366
2367// Tests for ::testing::IsNotSubstring().
2368
2369// Tests that IsNotSubstring() returns the correct result when the input
2370// argument type is const char*.
2371TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002372 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2373 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2374}
2375
2376// Tests that IsNotSubstring() returns the correct result when the input
2377// argument type is const wchar_t*.
2378TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002379 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2380 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2381}
2382
2383// Tests that IsNotSubstring() generates the correct message when the input
2384// argument type is const wchar_t*.
2385TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2386 EXPECT_STREQ("Value of: needle_expr\n"
2387 " Actual: L\"needle\"\n"
2388 "Expected: not a substring of haystack_expr\n"
2389 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002390 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002391 "needle_expr", "haystack_expr",
2392 L"needle", L"two needles").failure_message());
2393}
2394
2395#if GTEST_HAS_STD_STRING
2396
2397// Tests that IsNotSubstring returns the correct result when the input
2398// argument type is ::std::string.
2399TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002400 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2401 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2402}
2403
2404// Tests that IsNotSubstring() generates the correct message when the input
2405// argument type is ::std::string.
2406TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2407 EXPECT_STREQ("Value of: needle_expr\n"
2408 " Actual: \"needle\"\n"
2409 "Expected: not a substring of haystack_expr\n"
2410 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002411 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002412 "needle_expr", "haystack_expr",
2413 ::std::string("needle"), "two needles").failure_message());
2414}
2415
2416#endif // GTEST_HAS_STD_STRING
2417
2418#if GTEST_HAS_STD_WSTRING
2419
2420// Tests that IsNotSubstring returns the correct result when the input
2421// argument type is ::std::wstring.
2422TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002423 EXPECT_FALSE(
2424 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2425 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2426}
2427
2428#endif // GTEST_HAS_STD_WSTRING
2429
2430// Tests floating-point assertions.
2431
2432template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002433class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002434 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002435
2436 // Pre-calculated numbers to be used by the tests.
2437 struct TestValues {
2438 RawType close_to_positive_zero;
2439 RawType close_to_negative_zero;
2440 RawType further_from_negative_zero;
2441
2442 RawType close_to_one;
2443 RawType further_from_one;
2444
2445 RawType infinity;
2446 RawType close_to_infinity;
2447 RawType further_from_infinity;
2448
2449 RawType nan1;
2450 RawType nan2;
2451 };
2452
shiqian4b6829f2008-07-03 22:38:12 +00002453 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2454 typedef typename Floating::Bits Bits;
2455
2456 virtual void SetUp() {
2457 const size_t max_ulps = Floating::kMaxUlps;
2458
2459 // The bits that represent 0.0.
2460 const Bits zero_bits = Floating(0).bits();
2461
2462 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002463 values_.close_to_positive_zero = Floating::ReinterpretBits(
2464 zero_bits + max_ulps/2);
2465 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002466 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002467 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002468 zero_bits + max_ulps + 1 - max_ulps/2);
2469
2470 // The bits that represent 1.0.
2471 const Bits one_bits = Floating(1).bits();
2472
2473 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002474 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2475 values_.further_from_one = Floating::ReinterpretBits(
2476 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002477
2478 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002479 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002480
2481 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002482 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002483
2484 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002485 values_.close_to_infinity = Floating::ReinterpretBits(
2486 infinity_bits - max_ulps);
2487 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002488 infinity_bits - max_ulps - 1);
2489
zhanyong.wan98efcc42009-04-28 00:28:09 +00002490 // Makes some NAN's. Sets the most significant bit of the fraction so that
2491 // our NaN's are quiet; trying to process a signaling NaN would raise an
2492 // exception if our environment enables floating point exceptions.
2493 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2494 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2495 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2496 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002497 }
2498
2499 void TestSize() {
2500 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2501 }
2502
zhanyong.wan98efcc42009-04-28 00:28:09 +00002503 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002504};
2505
2506template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002507typename FloatingPointTest<RawType>::TestValues
2508 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002509
2510// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2511typedef FloatingPointTest<float> FloatTest;
2512
2513// Tests that the size of Float::Bits matches the size of float.
2514TEST_F(FloatTest, Size) {
2515 TestSize();
2516}
2517
2518// Tests comparing with +0 and -0.
2519TEST_F(FloatTest, Zeros) {
2520 EXPECT_FLOAT_EQ(0.0, -0.0);
2521 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2522 "1.0");
2523 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2524 "1.5");
2525}
2526
2527// Tests comparing numbers close to 0.
2528//
2529// This ensures that *_FLOAT_EQ handles the sign correctly and no
2530// overflow occurs when comparing numbers whose absolute value is very
2531// small.
2532TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002533 // In C++Builder, names within local classes (such as used by
2534 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2535 // scoping class. Use a static local alias as a workaround.
2536 static const FloatTest::TestValues& v(this->values_);
2537
2538 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2539 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2540 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002541
2542 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002543 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2544 v.further_from_negative_zero);
2545 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002546}
2547
2548// Tests comparing numbers close to each other.
2549TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002550 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2551 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2552 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002553}
2554
2555// Tests comparing numbers far apart.
2556TEST_F(FloatTest, LargeDiff) {
2557 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2558 "3.0");
2559}
2560
2561// Tests comparing with infinity.
2562//
2563// This ensures that no overflow occurs when comparing numbers whose
2564// absolute value is very large.
2565TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002566 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2567 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002568#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002569 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002570 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2571 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002572
zhanyong.wan98efcc42009-04-28 00:28:09 +00002573 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002574 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002575 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2576 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002577#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002578}
2579
2580// Tests that comparing with NAN always returns false.
2581TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002582#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002583// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002584
zhanyong.wan98efcc42009-04-28 00:28:09 +00002585 // In C++Builder, names within local classes (such as used by
2586 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2587 // scoping class. Use a static local alias as a workaround.
2588 static const FloatTest::TestValues& v(this->values_);
2589
2590 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2591 "v.nan1");
2592 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2593 "v.nan2");
2594 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2595 "v.nan1");
2596
2597 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2598 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002599#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002600}
2601
2602// Tests that *_FLOAT_EQ are reflexive.
2603TEST_F(FloatTest, Reflexive) {
2604 EXPECT_FLOAT_EQ(0.0, 0.0);
2605 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002606 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002607}
2608
2609// Tests that *_FLOAT_EQ are commutative.
2610TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002611 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2612 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002613
zhanyong.wan98efcc42009-04-28 00:28:09 +00002614 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2615 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002616 "1.0");
2617}
2618
2619// Tests EXPECT_NEAR.
2620TEST_F(FloatTest, EXPECT_NEAR) {
2621 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2622 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2623 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2624 "The difference between 1.0f and 1.2f is 0.2, "
2625 "which exceeds 0.1f");
2626 // To work around a bug in gcc 2.95.0, there is intentionally no
2627 // space after the first comma in the previous line.
2628}
2629
2630// Tests ASSERT_NEAR.
2631TEST_F(FloatTest, ASSERT_NEAR) {
2632 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2633 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2634 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2635 "The difference between 1.0f and 1.2f is 0.2, "
2636 "which exceeds 0.1f");
2637 // To work around a bug in gcc 2.95.0, there is intentionally no
2638 // space after the first comma in the previous line.
2639}
2640
2641// Tests the cases where FloatLE() should succeed.
2642TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002643 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2644 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002645
2646 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002647 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002648}
2649
2650// Tests the cases where FloatLE() should fail.
2651TEST_F(FloatTest, FloatLEFails) {
2652 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002653 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002654 "(2.0f) <= (1.0f)");
2655
2656 // or by a small yet non-negligible margin,
2657 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002658 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2659 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002660
zhanyong.wan98efcc42009-04-28 00:28:09 +00002661#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002662 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002663 // C++Builder gives bad results for ordered comparisons involving NaNs
2664 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002665 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002666 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2667 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002668 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002669 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2670 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002671 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002672 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2673 }, "(values_.nan1) <= (values_.nan1)");
2674#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002675}
2676
2677// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2678typedef FloatingPointTest<double> DoubleTest;
2679
2680// Tests that the size of Double::Bits matches the size of double.
2681TEST_F(DoubleTest, Size) {
2682 TestSize();
2683}
2684
2685// Tests comparing with +0 and -0.
2686TEST_F(DoubleTest, Zeros) {
2687 EXPECT_DOUBLE_EQ(0.0, -0.0);
2688 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2689 "1.0");
2690 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2691 "1.0");
2692}
2693
2694// Tests comparing numbers close to 0.
2695//
2696// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2697// overflow occurs when comparing numbers whose absolute value is very
2698// small.
2699TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002700 // In C++Builder, names within local classes (such as used by
2701 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2702 // scoping class. Use a static local alias as a workaround.
2703 static const DoubleTest::TestValues& v(this->values_);
2704
2705 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2706 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2707 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002708
2709 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002710 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2711 v.further_from_negative_zero);
2712 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002713}
2714
2715// Tests comparing numbers close to each other.
2716TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002717 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2718 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2719 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002720}
2721
2722// Tests comparing numbers far apart.
2723TEST_F(DoubleTest, LargeDiff) {
2724 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2725 "3.0");
2726}
2727
2728// Tests comparing with infinity.
2729//
2730// This ensures that no overflow occurs when comparing numbers whose
2731// absolute value is very large.
2732TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002733 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2734 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002735#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002736 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002737 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2738 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002739
2740 // This is interesting as the representations of infinity_ and nan1_
2741 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002742 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2743 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002744#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002745}
2746
2747// Tests that comparing with NAN always returns false.
2748TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002749#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00002750 // In C++Builder, names within local classes (such as used by
2751 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2752 // scoping class. Use a static local alias as a workaround.
2753 static const DoubleTest::TestValues& v(this->values_);
2754
shiqiane44602e2008-10-11 07:20:02 +00002755 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002756 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2757 "v.nan1");
2758 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2759 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2760 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2761 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002762#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002763}
2764
2765// Tests that *_DOUBLE_EQ are reflexive.
2766TEST_F(DoubleTest, Reflexive) {
2767 EXPECT_DOUBLE_EQ(0.0, 0.0);
2768 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002769#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002770 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002771 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002772#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002773}
2774
2775// Tests that *_DOUBLE_EQ are commutative.
2776TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002777 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
2778 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002779
zhanyong.wan98efcc42009-04-28 00:28:09 +00002780 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
2781 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
2782 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00002783}
2784
2785// Tests EXPECT_NEAR.
2786TEST_F(DoubleTest, EXPECT_NEAR) {
2787 EXPECT_NEAR(-1.0, -1.1, 0.2);
2788 EXPECT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002789 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
2790 "The difference between 1.0 and 1.2 is 0.2, "
2791 "which exceeds 0.1");
2792 // To work around a bug in gcc 2.95.0, there is intentionally no
2793 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002794}
2795
2796// Tests ASSERT_NEAR.
2797TEST_F(DoubleTest, ASSERT_NEAR) {
2798 ASSERT_NEAR(-1.0, -1.1, 0.2);
2799 ASSERT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002800 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
2801 "The difference between 1.0 and 1.2 is 0.2, "
2802 "which exceeds 0.1");
2803 // To work around a bug in gcc 2.95.0, there is intentionally no
2804 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002805}
2806
2807// Tests the cases where DoubleLE() should succeed.
2808TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002809 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
2810 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002811
2812 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002813 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00002814}
2815
2816// Tests the cases where DoubleLE() should fail.
2817TEST_F(DoubleTest, DoubleLEFails) {
2818 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002819 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002820 "(2.0) <= (1.0)");
2821
2822 // or by a small yet non-negligible margin,
2823 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002824 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
2825 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00002826
zhanyong.wan98efcc42009-04-28 00:28:09 +00002827#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002828 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002829 // C++Builder gives bad results for ordered comparisons involving NaNs
2830 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002831 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002832 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
2833 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002834 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002835 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
2836 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002837 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002838 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
2839 }, "(values_.nan1) <= (values_.nan1)");
2840#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002841}
2842
2843
2844// Verifies that a test or test case whose name starts with DISABLED_ is
2845// not run.
2846
2847// A test whose name starts with DISABLED_.
2848// Should not run.
2849TEST(DisabledTest, DISABLED_TestShouldNotRun) {
2850 FAIL() << "Unexpected failure: Disabled test should not be run.";
2851}
2852
2853// A test whose name does not start with DISABLED_.
2854// Should run.
2855TEST(DisabledTest, NotDISABLED_TestShouldRun) {
2856 EXPECT_EQ(1, 1);
2857}
2858
2859// A test case whose name starts with DISABLED_.
2860// Should not run.
2861TEST(DISABLED_TestCase, TestShouldNotRun) {
2862 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2863}
2864
2865// A test case and test whose names start with DISABLED_.
2866// Should not run.
2867TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
2868 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2869}
2870
2871// Check that when all tests in a test case are disabled, SetupTestCase() and
2872// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00002873class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002874 protected:
2875 static void SetUpTestCase() {
2876 FAIL() << "Unexpected failure: All tests disabled in test case. "
2877 "SetupTestCase() should not be called.";
2878 }
2879
2880 static void TearDownTestCase() {
2881 FAIL() << "Unexpected failure: All tests disabled in test case. "
2882 "TearDownTestCase() should not be called.";
2883 }
2884};
2885
2886TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
2887 FAIL() << "Unexpected failure: Disabled test should not be run.";
2888}
2889
2890TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
2891 FAIL() << "Unexpected failure: Disabled test should not be run.";
2892}
2893
shiqiane8ff1482008-09-08 17:55:52 +00002894// Tests that disabled typed tests aren't run.
2895
zhanyong.wan4cd62602009-02-23 23:21:55 +00002896#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00002897
2898template <typename T>
2899class TypedTest : public Test {
2900};
2901
2902typedef testing::Types<int, double> NumericTypes;
2903TYPED_TEST_CASE(TypedTest, NumericTypes);
2904
2905TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
2906 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2907}
2908
2909template <typename T>
2910class DISABLED_TypedTest : public Test {
2911};
2912
2913TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
2914
2915TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
2916 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2917}
2918
2919#endif // GTEST_HAS_TYPED_TEST
2920
2921// Tests that disabled type-parameterized tests aren't run.
2922
zhanyong.wan4cd62602009-02-23 23:21:55 +00002923#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00002924
2925template <typename T>
2926class TypedTestP : public Test {
2927};
2928
2929TYPED_TEST_CASE_P(TypedTestP);
2930
2931TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
2932 FAIL() << "Unexpected failure: "
2933 << "Disabled type-parameterized test should not run.";
2934}
2935
2936REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
2937
2938INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
2939
2940template <typename T>
2941class DISABLED_TypedTestP : public Test {
2942};
2943
2944TYPED_TEST_CASE_P(DISABLED_TypedTestP);
2945
2946TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
2947 FAIL() << "Unexpected failure: "
2948 << "Disabled type-parameterized test should not run.";
2949}
2950
2951REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
2952
2953INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
2954
2955#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00002956
2957// Tests that assertion macros evaluate their arguments exactly once.
2958
shiqian760af5c2008-08-06 21:43:15 +00002959class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00002960 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002961 // This helper function is needed by the FailedASSERT_STREQ test
2962 // below. It's public to work around C++Builder's bug with scoping local
2963 // classes.
2964 static void CompareAndIncrementCharPtrs() {
2965 ASSERT_STREQ(p1_++, p2_++);
2966 }
2967
2968 // This helper function is needed by the FailedASSERT_NE test below. It's
2969 // public to work around C++Builder's bug with scoping local classes.
2970 static void CompareAndIncrementInts() {
2971 ASSERT_NE(a_++, b_++);
2972 }
2973
shiqian4b6829f2008-07-03 22:38:12 +00002974 protected:
2975 SingleEvaluationTest() {
2976 p1_ = s1_;
2977 p2_ = s2_;
2978 a_ = 0;
2979 b_ = 0;
2980 }
2981
shiqian4b6829f2008-07-03 22:38:12 +00002982 static const char* const s1_;
2983 static const char* const s2_;
2984 static const char* p1_;
2985 static const char* p2_;
2986
2987 static int a_;
2988 static int b_;
2989};
2990
2991const char* const SingleEvaluationTest::s1_ = "01234";
2992const char* const SingleEvaluationTest::s2_ = "abcde";
2993const char* SingleEvaluationTest::p1_;
2994const char* SingleEvaluationTest::p2_;
2995int SingleEvaluationTest::a_;
2996int SingleEvaluationTest::b_;
2997
2998// Tests that when ASSERT_STREQ fails, it evaluates its arguments
2999// exactly once.
3000TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003001 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003002 "p2_++");
3003 EXPECT_EQ(s1_ + 1, p1_);
3004 EXPECT_EQ(s2_ + 1, p2_);
3005}
3006
3007// Tests that string assertion arguments are evaluated exactly once.
3008TEST_F(SingleEvaluationTest, ASSERT_STR) {
3009 // successful EXPECT_STRNE
3010 EXPECT_STRNE(p1_++, p2_++);
3011 EXPECT_EQ(s1_ + 1, p1_);
3012 EXPECT_EQ(s2_ + 1, p2_);
3013
3014 // failed EXPECT_STRCASEEQ
3015 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3016 "ignoring case");
3017 EXPECT_EQ(s1_ + 2, p1_);
3018 EXPECT_EQ(s2_ + 2, p2_);
3019}
3020
3021// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3022// once.
3023TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003024 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3025 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003026 EXPECT_EQ(1, a_);
3027 EXPECT_EQ(1, b_);
3028}
3029
3030// Tests that assertion arguments are evaluated exactly once.
3031TEST_F(SingleEvaluationTest, OtherCases) {
3032 // successful EXPECT_TRUE
3033 EXPECT_TRUE(0 == a_++); // NOLINT
3034 EXPECT_EQ(1, a_);
3035
3036 // failed EXPECT_TRUE
3037 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3038 EXPECT_EQ(2, a_);
3039
3040 // successful EXPECT_GT
3041 EXPECT_GT(a_++, b_++);
3042 EXPECT_EQ(3, a_);
3043 EXPECT_EQ(1, b_);
3044
3045 // failed EXPECT_LT
3046 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3047 EXPECT_EQ(4, a_);
3048 EXPECT_EQ(2, b_);
3049
3050 // successful ASSERT_TRUE
3051 ASSERT_TRUE(0 < a_++); // NOLINT
3052 EXPECT_EQ(5, a_);
3053
3054 // successful ASSERT_GT
3055 ASSERT_GT(a_++, b_++);
3056 EXPECT_EQ(6, a_);
3057 EXPECT_EQ(3, b_);
3058}
3059
shiqian9204c8e2008-09-12 20:57:22 +00003060#if GTEST_HAS_EXCEPTIONS
3061
3062void ThrowAnInteger() {
3063 throw 1;
3064}
3065
3066// Tests that assertion arguments are evaluated exactly once.
3067TEST_F(SingleEvaluationTest, ExceptionTests) {
3068 // successful EXPECT_THROW
3069 EXPECT_THROW({ // NOLINT
3070 a_++;
3071 ThrowAnInteger();
3072 }, int);
3073 EXPECT_EQ(1, a_);
3074
3075 // failed EXPECT_THROW, throws different
3076 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3077 a_++;
3078 ThrowAnInteger();
3079 }, bool), "throws a different type");
3080 EXPECT_EQ(2, a_);
3081
3082 // failed EXPECT_THROW, throws nothing
3083 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3084 EXPECT_EQ(3, a_);
3085
3086 // successful EXPECT_NO_THROW
3087 EXPECT_NO_THROW(a_++);
3088 EXPECT_EQ(4, a_);
3089
3090 // failed EXPECT_NO_THROW
3091 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3092 a_++;
3093 ThrowAnInteger();
3094 }), "it throws");
3095 EXPECT_EQ(5, a_);
3096
3097 // successful EXPECT_ANY_THROW
3098 EXPECT_ANY_THROW({ // NOLINT
3099 a_++;
3100 ThrowAnInteger();
3101 });
3102 EXPECT_EQ(6, a_);
3103
3104 // failed EXPECT_ANY_THROW
3105 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3106 EXPECT_EQ(7, a_);
3107}
3108
3109#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003110
shiqiane44602e2008-10-11 07:20:02 +00003111// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3112class NoFatalFailureTest : public Test {
3113 protected:
3114 void Succeeds() {}
3115 void FailsNonFatal() {
3116 ADD_FAILURE() << "some non-fatal failure";
3117 }
3118 void Fails() {
3119 FAIL() << "some fatal failure";
3120 }
3121
3122 void DoAssertNoFatalFailureOnFails() {
3123 ASSERT_NO_FATAL_FAILURE(Fails());
3124 ADD_FAILURE() << "shold not reach here.";
3125 }
3126
3127 void DoExpectNoFatalFailureOnFails() {
3128 EXPECT_NO_FATAL_FAILURE(Fails());
3129 ADD_FAILURE() << "other failure";
3130 }
3131};
3132
3133TEST_F(NoFatalFailureTest, NoFailure) {
3134 EXPECT_NO_FATAL_FAILURE(Succeeds());
3135 ASSERT_NO_FATAL_FAILURE(Succeeds());
3136}
3137
3138TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3139 EXPECT_NONFATAL_FAILURE(
3140 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3141 "some non-fatal failure");
3142 EXPECT_NONFATAL_FAILURE(
3143 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3144 "some non-fatal failure");
3145}
3146
3147TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3148 TestPartResultArray gtest_failures;
3149 {
3150 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3151 DoAssertNoFatalFailureOnFails();
3152 }
3153 ASSERT_EQ(2, gtest_failures.size());
3154 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3155 gtest_failures.GetTestPartResult(0).type());
3156 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3157 gtest_failures.GetTestPartResult(1).type());
3158 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3159 gtest_failures.GetTestPartResult(0).message());
3160 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3161 gtest_failures.GetTestPartResult(1).message());
3162}
3163
3164TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3165 TestPartResultArray gtest_failures;
3166 {
3167 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3168 DoExpectNoFatalFailureOnFails();
3169 }
3170 ASSERT_EQ(3, gtest_failures.size());
3171 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3172 gtest_failures.GetTestPartResult(0).type());
3173 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3174 gtest_failures.GetTestPartResult(1).type());
3175 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3176 gtest_failures.GetTestPartResult(2).type());
3177 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3178 gtest_failures.GetTestPartResult(0).message());
3179 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3180 gtest_failures.GetTestPartResult(1).message());
3181 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3182 gtest_failures.GetTestPartResult(2).message());
3183}
3184
3185TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3186 TestPartResultArray gtest_failures;
3187 {
3188 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3189 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3190 }
3191 ASSERT_EQ(2, gtest_failures.size());
3192 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3193 gtest_failures.GetTestPartResult(0).type());
3194 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3195 gtest_failures.GetTestPartResult(1).type());
3196 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3197 gtest_failures.GetTestPartResult(0).message());
3198 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3199 gtest_failures.GetTestPartResult(1).message());
3200}
3201
shiqian4b6829f2008-07-03 22:38:12 +00003202// Tests non-string assertions.
3203
3204// Tests EqFailure(), used for implementing *EQ* assertions.
3205TEST(AssertionTest, EqFailure) {
3206 const String foo_val("5"), bar_val("6");
3207 const String msg1(
3208 EqFailure("foo", "bar", foo_val, bar_val, false)
3209 .failure_message());
3210 EXPECT_STREQ(
3211 "Value of: bar\n"
3212 " Actual: 6\n"
3213 "Expected: foo\n"
3214 "Which is: 5",
3215 msg1.c_str());
3216
3217 const String msg2(
3218 EqFailure("foo", "6", foo_val, bar_val, false)
3219 .failure_message());
3220 EXPECT_STREQ(
3221 "Value of: 6\n"
3222 "Expected: foo\n"
3223 "Which is: 5",
3224 msg2.c_str());
3225
3226 const String msg3(
3227 EqFailure("5", "bar", foo_val, bar_val, false)
3228 .failure_message());
3229 EXPECT_STREQ(
3230 "Value of: bar\n"
3231 " Actual: 6\n"
3232 "Expected: 5",
3233 msg3.c_str());
3234
3235 const String msg4(
3236 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3237 EXPECT_STREQ(
3238 "Value of: 6\n"
3239 "Expected: 5",
3240 msg4.c_str());
3241
3242 const String msg5(
3243 EqFailure("foo", "bar",
3244 String("\"x\""), String("\"y\""),
3245 true).failure_message());
3246 EXPECT_STREQ(
3247 "Value of: bar\n"
3248 " Actual: \"y\"\n"
3249 "Expected: foo (ignoring case)\n"
3250 "Which is: \"x\"",
3251 msg5.c_str());
3252}
3253
3254// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3255TEST(AssertionTest, AppendUserMessage) {
3256 const String foo("foo");
3257
shiqian760af5c2008-08-06 21:43:15 +00003258 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003259 EXPECT_STREQ("foo",
3260 AppendUserMessage(foo, msg).c_str());
3261
3262 msg << "bar";
3263 EXPECT_STREQ("foo\nbar",
3264 AppendUserMessage(foo, msg).c_str());
3265}
3266
zhanyong.wan98efcc42009-04-28 00:28:09 +00003267#ifdef __BORLANDC__
3268// Silences warnings: "Condition is always true", "Unreachable code"
3269#pragma option push -w-ccc -w-rch
3270#endif
3271
shiqian4b6829f2008-07-03 22:38:12 +00003272// Tests ASSERT_TRUE.
3273TEST(AssertionTest, ASSERT_TRUE) {
3274 ASSERT_TRUE(2 > 1); // NOLINT
3275 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3276 "2 < 1");
3277}
3278
3279// Tests ASSERT_FALSE.
3280TEST(AssertionTest, ASSERT_FALSE) {
3281 ASSERT_FALSE(2 < 1); // NOLINT
3282 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3283 "Value of: 2 > 1\n"
3284 " Actual: true\n"
3285 "Expected: false");
3286}
3287
zhanyong.wan98efcc42009-04-28 00:28:09 +00003288#ifdef __BORLANDC__
3289// Restores warnings after previous "#pragma option push" supressed them
3290#pragma option pop
3291#endif
3292
shiqian4b6829f2008-07-03 22:38:12 +00003293// Tests using ASSERT_EQ on double values. The purpose is to make
3294// sure that the specialization we did for integer and anonymous enums
3295// isn't used for double arguments.
3296TEST(ExpectTest, ASSERT_EQ_Double) {
3297 // A success.
3298 ASSERT_EQ(5.6, 5.6);
3299
3300 // A failure.
3301 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3302 "5.1");
3303}
3304
3305// Tests ASSERT_EQ.
3306TEST(AssertionTest, ASSERT_EQ) {
3307 ASSERT_EQ(5, 2 + 3);
3308 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3309 "Value of: 2*3\n"
3310 " Actual: 6\n"
3311 "Expected: 5");
3312}
3313
3314// Tests ASSERT_EQ(NULL, pointer).
zhanyong.wan4cd62602009-02-23 23:21:55 +00003315#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003316// The NULL-detection template magic fails to compile with
3317// the Nokia compiler and crashes the ARM compiler, hence
3318// not testing on Symbian.
3319TEST(AssertionTest, ASSERT_EQ_NULL) {
3320 // A success.
3321 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003322 // Some older GCC versions may issue a spurious waring in this or the next
3323 // assertion statement. This warning should not be suppressed with
3324 // static_cast since the test verifies the ability to use bare NULL as the
3325 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003326 ASSERT_EQ(NULL, p);
3327
3328 // A failure.
3329 static int n = 0;
3330 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3331 "Value of: &n\n");
3332}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003333#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003334
3335// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3336// treated as a null pointer by the compiler, we need to make sure
3337// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3338// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3339TEST(ExpectTest, ASSERT_EQ_0) {
3340 int n = 0;
3341
3342 // A success.
3343 ASSERT_EQ(0, n);
3344
3345 // A failure.
3346 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3347 "Expected: 0");
3348}
3349
3350// Tests ASSERT_NE.
3351TEST(AssertionTest, ASSERT_NE) {
3352 ASSERT_NE(6, 7);
3353 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3354 "Expected: ('a') != ('a'), "
3355 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3356}
3357
3358// Tests ASSERT_LE.
3359TEST(AssertionTest, ASSERT_LE) {
3360 ASSERT_LE(2, 3);
3361 ASSERT_LE(2, 2);
3362 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3363 "Expected: (2) <= (0), actual: 2 vs 0");
3364}
3365
3366// Tests ASSERT_LT.
3367TEST(AssertionTest, ASSERT_LT) {
3368 ASSERT_LT(2, 3);
3369 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3370 "Expected: (2) < (2), actual: 2 vs 2");
3371}
3372
3373// Tests ASSERT_GE.
3374TEST(AssertionTest, ASSERT_GE) {
3375 ASSERT_GE(2, 1);
3376 ASSERT_GE(2, 2);
3377 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3378 "Expected: (2) >= (3), actual: 2 vs 3");
3379}
3380
3381// Tests ASSERT_GT.
3382TEST(AssertionTest, ASSERT_GT) {
3383 ASSERT_GT(2, 1);
3384 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3385 "Expected: (2) > (2), actual: 2 vs 2");
3386}
3387
shiqian9204c8e2008-09-12 20:57:22 +00003388#if GTEST_HAS_EXCEPTIONS
3389
zhanyong.wanac60cef2009-02-08 04:53:35 +00003390void ThrowNothing() {}
3391
shiqian9204c8e2008-09-12 20:57:22 +00003392// Tests ASSERT_THROW.
3393TEST(AssertionTest, ASSERT_THROW) {
3394 ASSERT_THROW(ThrowAnInteger(), int);
zhanyong.wan98efcc42009-04-28 00:28:09 +00003395#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 || defined(_DEBUG)
3396 // ICE's in C++Builder 2007 (Release build).
zhanyong.wanac60cef2009-02-08 04:53:35 +00003397 EXPECT_FATAL_FAILURE(
3398 ASSERT_THROW(ThrowAnInteger(), bool),
3399 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3400 " Actual: it throws a different type.");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003401#endif
zhanyong.wanac60cef2009-02-08 04:53:35 +00003402 EXPECT_FATAL_FAILURE(
3403 ASSERT_THROW(ThrowNothing(), bool),
3404 "Expected: ThrowNothing() throws an exception of type bool.\n"
3405 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003406}
3407
3408// Tests ASSERT_NO_THROW.
3409TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003410 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003411 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003412 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003413 "\n Actual: it throws.");
3414}
3415
3416// Tests ASSERT_ANY_THROW.
3417TEST(AssertionTest, ASSERT_ANY_THROW) {
3418 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003419 EXPECT_FATAL_FAILURE(
3420 ASSERT_ANY_THROW(ThrowNothing()),
3421 "Expected: ThrowNothing() throws an exception.\n"
3422 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003423}
3424
3425#endif // GTEST_HAS_EXCEPTIONS
3426
shiqian4b6829f2008-07-03 22:38:12 +00003427// Makes sure we deal with the precedence of <<. This test should
3428// compile.
3429TEST(AssertionTest, AssertPrecedence) {
3430 ASSERT_EQ(1 < 2, true);
3431 ASSERT_EQ(true && false, false);
3432}
3433
3434// A subroutine used by the following test.
3435void TestEq1(int x) {
3436 ASSERT_EQ(1, x);
3437}
3438
3439// Tests calling a test subroutine that's not part of a fixture.
3440TEST(AssertionTest, NonFixtureSubroutine) {
3441 EXPECT_FATAL_FAILURE(TestEq1(2),
3442 "Value of: x");
3443}
3444
3445// An uncopyable class.
3446class Uncopyable {
3447 public:
3448 explicit Uncopyable(int value) : value_(value) {}
3449
3450 int value() const { return value_; }
3451 bool operator==(const Uncopyable& rhs) const {
3452 return value() == rhs.value();
3453 }
3454 private:
3455 // This constructor deliberately has no implementation, as we don't
3456 // want this class to be copyable.
3457 Uncopyable(const Uncopyable&); // NOLINT
3458
3459 int value_;
3460};
3461
3462::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3463 return os << value.value();
3464}
3465
3466
3467bool IsPositiveUncopyable(const Uncopyable& x) {
3468 return x.value() > 0;
3469}
3470
3471// A subroutine used by the following test.
3472void TestAssertNonPositive() {
3473 Uncopyable y(-1);
3474 ASSERT_PRED1(IsPositiveUncopyable, y);
3475}
3476// A subroutine used by the following test.
3477void TestAssertEqualsUncopyable() {
3478 Uncopyable x(5);
3479 Uncopyable y(-1);
3480 ASSERT_EQ(x, y);
3481}
3482
3483// Tests that uncopyable objects can be used in assertions.
3484TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3485 Uncopyable x(5);
3486 ASSERT_PRED1(IsPositiveUncopyable, x);
3487 ASSERT_EQ(x, x);
3488 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3489 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3490 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3491 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3492}
3493
3494// Tests that uncopyable objects can be used in expects.
3495TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3496 Uncopyable x(5);
3497 EXPECT_PRED1(IsPositiveUncopyable, x);
3498 Uncopyable y(-1);
3499 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3500 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3501 EXPECT_EQ(x, x);
3502 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3503 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3504}
3505
3506
3507// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003508// anonymous enums in assertions. Therefore the following test is not
3509// done on Mac.
3510#if !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003511
3512// Tests using assertions with anonymous enums.
3513enum {
3514 CASE_A = -1,
zhanyong.wan4cd62602009-02-23 23:21:55 +00003515#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003516 // We want to test the case where the size of the anonymous enum is
3517 // larger than sizeof(int), to make sure our implementation of the
3518 // assertions doesn't truncate the enums. However, MSVC
3519 // (incorrectly) doesn't allow an enum value to exceed the range of
3520 // an int, so this has to be conditionally compiled.
3521 //
3522 // On Linux, CASE_B and CASE_A have the same value when truncated to
3523 // int size. We want to test whether this will confuse the
3524 // assertions.
shiqian760af5c2008-08-06 21:43:15 +00003525 CASE_B = testing::internal::kMaxBiggestInt,
shiqian4b6829f2008-07-03 22:38:12 +00003526#else
3527 CASE_B = INT_MAX,
3528#endif // GTEST_OS_LINUX
3529};
3530
3531TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003532#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003533 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
3534#endif // GTEST_OS_LINUX
3535
3536 EXPECT_EQ(CASE_A, CASE_A);
3537 EXPECT_NE(CASE_A, CASE_B);
3538 EXPECT_LT(CASE_A, CASE_B);
3539 EXPECT_LE(CASE_A, CASE_B);
3540 EXPECT_GT(CASE_B, CASE_A);
3541 EXPECT_GE(CASE_A, CASE_A);
3542 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
3543 "(CASE_A) >= (CASE_B)");
3544
3545 ASSERT_EQ(CASE_A, CASE_A);
3546 ASSERT_NE(CASE_A, CASE_B);
3547 ASSERT_LT(CASE_A, CASE_B);
3548 ASSERT_LE(CASE_A, CASE_B);
3549 ASSERT_GT(CASE_B, CASE_A);
3550 ASSERT_GE(CASE_A, CASE_A);
3551 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
3552 "Value of: CASE_B");
3553}
3554
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003555#endif // !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003556
zhanyong.wan4cd62602009-02-23 23:21:55 +00003557#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003558
3559static HRESULT UnexpectedHRESULTFailure() {
3560 return E_UNEXPECTED;
3561}
3562
3563static HRESULT OkHRESULTSuccess() {
3564 return S_OK;
3565}
3566
3567static HRESULT FalseHRESULTSuccess() {
3568 return S_FALSE;
3569}
3570
3571// HRESULT assertion tests test both zero and non-zero
3572// success codes as well as failure message for each.
3573//
3574// Windows CE doesn't support message texts.
3575TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3576 EXPECT_HRESULT_SUCCEEDED(S_OK);
3577 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3578
shiqian4b6829f2008-07-03 22:38:12 +00003579 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003580 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3581 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003582}
3583
3584TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3585 ASSERT_HRESULT_SUCCEEDED(S_OK);
3586 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3587
shiqian4b6829f2008-07-03 22:38:12 +00003588 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003589 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3590 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003591}
3592
3593TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3594 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3595
shiqian4b6829f2008-07-03 22:38:12 +00003596 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003597 "Expected: (OkHRESULTSuccess()) fails.\n"
3598 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00003599 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003600 "Expected: (FalseHRESULTSuccess()) fails.\n"
3601 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003602}
3603
3604TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3605 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3606
zhanyong.wan98efcc42009-04-28 00:28:09 +00003607#ifndef __BORLANDC__
3608 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003609 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003610 "Expected: (OkHRESULTSuccess()) fails.\n"
3611 " Actual: 0x00000000");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003612#endif
shiqian4b6829f2008-07-03 22:38:12 +00003613 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003614 "Expected: (FalseHRESULTSuccess()) fails.\n"
3615 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003616}
3617
3618// Tests that streaming to the HRESULT macros works.
3619TEST(HRESULTAssertionTest, Streaming) {
3620 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3621 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3622 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3623 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3624
3625 EXPECT_NONFATAL_FAILURE(
3626 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3627 "expected failure");
3628
zhanyong.wan98efcc42009-04-28 00:28:09 +00003629#ifndef __BORLANDC__
3630 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003631 EXPECT_FATAL_FAILURE(
3632 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3633 "expected failure");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003634#endif
shiqian4b6829f2008-07-03 22:38:12 +00003635
3636 EXPECT_NONFATAL_FAILURE(
3637 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3638 "expected failure");
3639
3640 EXPECT_FATAL_FAILURE(
3641 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3642 "expected failure");
3643}
3644
zhanyong.wan4cd62602009-02-23 23:21:55 +00003645#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003646
zhanyong.wan98efcc42009-04-28 00:28:09 +00003647#ifdef __BORLANDC__
3648// Silences warnings: "Condition is always true", "Unreachable code"
3649#pragma option push -w-ccc -w-rch
3650#endif
3651
shiqian4b6829f2008-07-03 22:38:12 +00003652// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003653TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
shiqian4b6829f2008-07-03 22:38:12 +00003654 if (false)
3655 ASSERT_TRUE(false) << "This should never be executed; "
3656 "It's a compilation test only.";
3657
3658 if (true)
3659 EXPECT_FALSE(false);
3660 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003661 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003662
3663 if (false)
3664 ASSERT_LT(1, 3);
3665
3666 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003667 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003668 else
3669 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00003670}
shiqian9204c8e2008-09-12 20:57:22 +00003671
3672#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00003673// Tests that the compiler will not complain about unreachable code in the
3674// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3675TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3676 int n = 0;
3677
3678 EXPECT_THROW(throw 1, int);
3679 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3680 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3681 EXPECT_NO_THROW(n++);
3682 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3683 EXPECT_ANY_THROW(throw 1);
3684 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3685}
3686
shiqiane44602e2008-10-11 07:20:02 +00003687TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
shiqian9204c8e2008-09-12 20:57:22 +00003688 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003689 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00003690
3691 if (true)
3692 EXPECT_THROW(ThrowAnInteger(), int);
3693 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003694 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003695
3696 if (false)
3697 EXPECT_NO_THROW(ThrowAnInteger());
3698
3699 if (true)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003700 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003701 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003702 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003703
3704 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003705 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003706
3707 if (true)
3708 EXPECT_ANY_THROW(ThrowAnInteger());
3709 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003710 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003711}
shiqian9204c8e2008-09-12 20:57:22 +00003712#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00003713
3714TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
3715 if (false)
3716 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
3717 << "It's a compilation test only.";
3718 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003719 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003720
3721 if (false)
3722 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
3723 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003724 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003725
3726 if (true)
3727 EXPECT_NO_FATAL_FAILURE(SUCCEED());
3728 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003729 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003730
3731 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003732 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003733 else
3734 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00003735}
3736
3737// Tests that the assertion macros work well with switch statements.
3738TEST(AssertionSyntaxTest, WorksWithSwitch) {
3739 switch (0) {
3740 case 1:
3741 break;
3742 default:
3743 ASSERT_TRUE(true);
3744 }
3745
3746 switch (0)
3747 case 0:
3748 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
3749
3750 // Binary assertions are implemented using a different code path
3751 // than the Boolean assertions. Hence we test them separately.
3752 switch (0) {
3753 case 1:
3754 default:
3755 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
3756 }
3757
3758 switch (0)
3759 case 0:
3760 EXPECT_NE(1, 2);
3761}
3762
shiqian9204c8e2008-09-12 20:57:22 +00003763#if GTEST_HAS_EXCEPTIONS
3764
3765void ThrowAString() {
3766 throw "String";
3767}
3768
3769// Test that the exception assertion macros compile and work with const
3770// type qualifier.
3771TEST(AssertionSyntaxTest, WorksWithConst) {
3772 ASSERT_THROW(ThrowAString(), const char*);
3773
3774 EXPECT_THROW(ThrowAString(), const char*);
3775}
3776
3777#endif // GTEST_HAS_EXCEPTIONS
3778
shiqian4b6829f2008-07-03 22:38:12 +00003779} // namespace
3780
3781// Returns the number of successful parts in the current test.
3782static size_t GetSuccessfulPartCount() {
zhanyong.wana80f23f2009-06-25 20:49:23 +00003783 return GetUnitTestImpl()->current_test_result()->successful_part_count();
shiqian4b6829f2008-07-03 22:38:12 +00003784}
3785
3786namespace testing {
3787
3788// Tests that Google Test tracks SUCCEED*.
3789TEST(SuccessfulAssertionTest, SUCCEED) {
3790 SUCCEED();
3791 SUCCEED() << "OK";
zhanyong.wan449f84d2009-07-01 22:55:05 +00003792 EXPECT_EQ(2, GetSuccessfulPartCount());
shiqian4b6829f2008-07-03 22:38:12 +00003793}
3794
3795// Tests that Google Test doesn't track successful EXPECT_*.
3796TEST(SuccessfulAssertionTest, EXPECT) {
3797 EXPECT_TRUE(true);
zhanyong.wan449f84d2009-07-01 22:55:05 +00003798 EXPECT_EQ(0, GetSuccessfulPartCount());
shiqian4b6829f2008-07-03 22:38:12 +00003799}
3800
3801// Tests that Google Test doesn't track successful EXPECT_STR*.
3802TEST(SuccessfulAssertionTest, EXPECT_STR) {
3803 EXPECT_STREQ("", "");
zhanyong.wan449f84d2009-07-01 22:55:05 +00003804 EXPECT_EQ(0, GetSuccessfulPartCount());
shiqian4b6829f2008-07-03 22:38:12 +00003805}
3806
3807// Tests that Google Test doesn't track successful ASSERT_*.
3808TEST(SuccessfulAssertionTest, ASSERT) {
3809 ASSERT_TRUE(true);
zhanyong.wan449f84d2009-07-01 22:55:05 +00003810 EXPECT_EQ(0, GetSuccessfulPartCount());
shiqian4b6829f2008-07-03 22:38:12 +00003811}
3812
3813// Tests that Google Test doesn't track successful ASSERT_STR*.
3814TEST(SuccessfulAssertionTest, ASSERT_STR) {
3815 ASSERT_STREQ("", "");
zhanyong.wan449f84d2009-07-01 22:55:05 +00003816 EXPECT_EQ(0, GetSuccessfulPartCount());
shiqian4b6829f2008-07-03 22:38:12 +00003817}
3818
3819} // namespace testing
3820
3821namespace {
3822
3823// Tests EXPECT_TRUE.
3824TEST(ExpectTest, EXPECT_TRUE) {
3825 EXPECT_TRUE(2 > 1); // NOLINT
3826 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
3827 "Value of: 2 < 1\n"
3828 " Actual: false\n"
3829 "Expected: true");
3830 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
3831 "2 > 3");
3832}
3833
3834// Tests EXPECT_FALSE.
3835TEST(ExpectTest, EXPECT_FALSE) {
3836 EXPECT_FALSE(2 < 1); // NOLINT
3837 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
3838 "Value of: 2 > 1\n"
3839 " Actual: true\n"
3840 "Expected: false");
3841 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
3842 "2 < 3");
3843}
3844
zhanyong.wan98efcc42009-04-28 00:28:09 +00003845#ifdef __BORLANDC__
3846// Restores warnings after previous "#pragma option push" supressed them
3847#pragma option pop
3848#endif
3849
shiqian4b6829f2008-07-03 22:38:12 +00003850// Tests EXPECT_EQ.
3851TEST(ExpectTest, EXPECT_EQ) {
3852 EXPECT_EQ(5, 2 + 3);
3853 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
3854 "Value of: 2*3\n"
3855 " Actual: 6\n"
3856 "Expected: 5");
3857 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
3858 "2 - 3");
3859}
3860
3861// Tests using EXPECT_EQ on double values. The purpose is to make
3862// sure that the specialization we did for integer and anonymous enums
3863// isn't used for double arguments.
3864TEST(ExpectTest, EXPECT_EQ_Double) {
3865 // A success.
3866 EXPECT_EQ(5.6, 5.6);
3867
3868 // A failure.
3869 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
3870 "5.1");
3871}
3872
zhanyong.wan4cd62602009-02-23 23:21:55 +00003873#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003874// Tests EXPECT_EQ(NULL, pointer).
3875TEST(ExpectTest, EXPECT_EQ_NULL) {
3876 // A success.
3877 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003878 // Some older GCC versions may issue a spurious waring in this or the next
3879 // assertion statement. This warning should not be suppressed with
3880 // static_cast since the test verifies the ability to use bare NULL as the
3881 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003882 EXPECT_EQ(NULL, p);
3883
3884 // A failure.
3885 int n = 0;
3886 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
3887 "Value of: &n\n");
3888}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003889#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003890
3891// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
3892// treated as a null pointer by the compiler, we need to make sure
3893// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
3894// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
3895TEST(ExpectTest, EXPECT_EQ_0) {
3896 int n = 0;
3897
3898 // A success.
3899 EXPECT_EQ(0, n);
3900
3901 // A failure.
3902 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
3903 "Expected: 0");
3904}
3905
3906// Tests EXPECT_NE.
3907TEST(ExpectTest, EXPECT_NE) {
3908 EXPECT_NE(6, 7);
3909
3910 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
3911 "Expected: ('a') != ('a'), "
3912 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3913 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
3914 "2");
3915 char* const p0 = NULL;
3916 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
3917 "p0");
3918 // Only way to get the Nokia compiler to compile the cast
3919 // is to have a separate void* variable first. Putting
3920 // the two casts on the same line doesn't work, neither does
3921 // a direct C-style to char*.
3922 void* pv1 = (void*)0x1234; // NOLINT
3923 char* const p1 = reinterpret_cast<char*>(pv1);
3924 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
3925 "p1");
3926}
3927
3928// Tests EXPECT_LE.
3929TEST(ExpectTest, EXPECT_LE) {
3930 EXPECT_LE(2, 3);
3931 EXPECT_LE(2, 2);
3932 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
3933 "Expected: (2) <= (0), actual: 2 vs 0");
3934 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
3935 "(1.1) <= (0.9)");
3936}
3937
3938// Tests EXPECT_LT.
3939TEST(ExpectTest, EXPECT_LT) {
3940 EXPECT_LT(2, 3);
3941 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
3942 "Expected: (2) < (2), actual: 2 vs 2");
3943 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
3944 "(2) < (1)");
3945}
3946
3947// Tests EXPECT_GE.
3948TEST(ExpectTest, EXPECT_GE) {
3949 EXPECT_GE(2, 1);
3950 EXPECT_GE(2, 2);
3951 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
3952 "Expected: (2) >= (3), actual: 2 vs 3");
3953 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
3954 "(0.9) >= (1.1)");
3955}
3956
3957// Tests EXPECT_GT.
3958TEST(ExpectTest, EXPECT_GT) {
3959 EXPECT_GT(2, 1);
3960 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
3961 "Expected: (2) > (2), actual: 2 vs 2");
3962 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
3963 "(2) > (3)");
3964}
3965
shiqian9204c8e2008-09-12 20:57:22 +00003966#if GTEST_HAS_EXCEPTIONS
3967
3968// Tests EXPECT_THROW.
3969TEST(ExpectTest, EXPECT_THROW) {
3970 EXPECT_THROW(ThrowAnInteger(), int);
3971 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003972 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00003973 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00003974 EXPECT_NONFATAL_FAILURE(
3975 EXPECT_THROW(ThrowNothing(), bool),
3976 "Expected: ThrowNothing() throws an exception of type bool.\n"
3977 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003978}
3979
3980// Tests EXPECT_NO_THROW.
3981TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003982 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003983 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003984 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00003985 "exception.\n Actual: it throws.");
3986}
3987
3988// Tests EXPECT_ANY_THROW.
3989TEST(ExpectTest, EXPECT_ANY_THROW) {
3990 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003991 EXPECT_NONFATAL_FAILURE(
3992 EXPECT_ANY_THROW(ThrowNothing()),
3993 "Expected: ThrowNothing() throws an exception.\n"
3994 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003995}
3996
3997#endif // GTEST_HAS_EXCEPTIONS
3998
shiqian4b6829f2008-07-03 22:38:12 +00003999// Make sure we deal with the precedence of <<.
4000TEST(ExpectTest, ExpectPrecedence) {
4001 EXPECT_EQ(1 < 2, true);
4002 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4003 "Value of: true && false");
4004}
4005
4006
4007// Tests the StreamableToString() function.
4008
4009// Tests using StreamableToString() on a scalar.
4010TEST(StreamableToStringTest, Scalar) {
4011 EXPECT_STREQ("5", StreamableToString(5).c_str());
4012}
4013
4014// Tests using StreamableToString() on a non-char pointer.
4015TEST(StreamableToStringTest, Pointer) {
4016 int n = 0;
4017 int* p = &n;
4018 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4019}
4020
4021// Tests using StreamableToString() on a NULL non-char pointer.
4022TEST(StreamableToStringTest, NullPointer) {
4023 int* p = NULL;
4024 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4025}
4026
4027// Tests using StreamableToString() on a C string.
4028TEST(StreamableToStringTest, CString) {
4029 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4030}
4031
4032// Tests using StreamableToString() on a NULL C string.
4033TEST(StreamableToStringTest, NullCString) {
4034 char* p = NULL;
4035 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4036}
4037
4038// Tests using streamable values as assertion messages.
4039
4040#if GTEST_HAS_STD_STRING
4041// Tests using std::string as an assertion message.
4042TEST(StreamableTest, string) {
4043 static const std::string str(
4044 "This failure message is a std::string, and is expected.");
4045 EXPECT_FATAL_FAILURE(FAIL() << str,
4046 str.c_str());
4047}
4048
4049// Tests that we can output strings containing embedded NULs.
4050// Limited to Linux because we can only do this with std::string's.
4051TEST(StreamableTest, stringWithEmbeddedNUL) {
4052 static const char char_array_with_nul[] =
4053 "Here's a NUL\0 and some more string";
4054 static const std::string string_with_nul(char_array_with_nul,
4055 sizeof(char_array_with_nul)
4056 - 1); // drops the trailing NUL
4057 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4058 "Here's a NUL\\0 and some more string");
4059}
4060
4061#endif // GTEST_HAS_STD_STRING
4062
4063// Tests that we can output a NUL char.
4064TEST(StreamableTest, NULChar) {
4065 EXPECT_FATAL_FAILURE({ // NOLINT
4066 FAIL() << "A NUL" << '\0' << " and some more string";
4067 }, "A NUL\\0 and some more string");
4068}
4069
4070// Tests using int as an assertion message.
4071TEST(StreamableTest, int) {
4072 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4073 "900913");
4074}
4075
4076// Tests using NULL char pointer as an assertion message.
4077//
4078// In MSVC, streaming a NULL char * causes access violation. Google Test
4079// implemented a workaround (substituting "(null)" for NULL). This
4080// tests whether the workaround works.
4081TEST(StreamableTest, NullCharPtr) {
4082 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4083 "(null)");
4084}
4085
4086// Tests that basic IO manipulators (endl, ends, and flush) can be
4087// streamed to testing::Message.
4088TEST(StreamableTest, BasicIoManip) {
4089 EXPECT_FATAL_FAILURE({ // NOLINT
4090 FAIL() << "Line 1." << std::endl
4091 << "A NUL char " << std::ends << std::flush << " in line 2.";
4092 }, "Line 1.\nA NUL char \\0 in line 2.");
4093}
4094
shiqian4b6829f2008-07-03 22:38:12 +00004095// Tests the macros that haven't been covered so far.
4096
4097void AddFailureHelper(bool* aborted) {
4098 *aborted = true;
4099 ADD_FAILURE() << "Failure";
4100 *aborted = false;
4101}
4102
4103// Tests ADD_FAILURE.
4104TEST(MacroTest, ADD_FAILURE) {
4105 bool aborted = true;
4106 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4107 "Failure");
4108 EXPECT_FALSE(aborted);
4109}
4110
4111// Tests FAIL.
4112TEST(MacroTest, FAIL) {
4113 EXPECT_FATAL_FAILURE(FAIL(),
4114 "Failed");
4115 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4116 "Intentional failure.");
4117}
4118
4119// Tests SUCCEED
4120TEST(MacroTest, SUCCEED) {
4121 SUCCEED();
4122 SUCCEED() << "Explicit success.";
4123}
4124
4125
4126// Tests for EXPECT_EQ() and ASSERT_EQ().
4127//
4128// These tests fail *intentionally*, s.t. the failure messages can be
4129// generated and tested.
4130//
4131// We have different tests for different argument types.
4132
4133// Tests using bool values in {EXPECT|ASSERT}_EQ.
4134TEST(EqAssertionTest, Bool) {
4135 EXPECT_EQ(true, true);
4136 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4137 "Value of: true");
4138}
4139
4140// Tests using int values in {EXPECT|ASSERT}_EQ.
4141TEST(EqAssertionTest, Int) {
4142 ASSERT_EQ(32, 32);
4143 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4144 "33");
4145}
4146
4147// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4148TEST(EqAssertionTest, Time_T) {
4149 EXPECT_EQ(static_cast<time_t>(0),
4150 static_cast<time_t>(0));
4151 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4152 static_cast<time_t>(1234)),
4153 "1234");
4154}
4155
4156// Tests using char values in {EXPECT|ASSERT}_EQ.
4157TEST(EqAssertionTest, Char) {
4158 ASSERT_EQ('z', 'z');
4159 const char ch = 'b';
4160 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4161 "ch");
4162 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4163 "ch");
4164}
4165
4166// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4167TEST(EqAssertionTest, WideChar) {
4168 EXPECT_EQ(L'b', L'b');
4169
4170 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4171 "Value of: L'x'\n"
4172 " Actual: L'x' (120, 0x78)\n"
4173 "Expected: L'\0'\n"
4174 "Which is: L'\0' (0, 0x0)");
4175
4176 static wchar_t wchar;
4177 wchar = L'b';
4178 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4179 "wchar");
4180 wchar = L'\x8119';
4181 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4182 "Value of: wchar");
4183}
4184
4185#if GTEST_HAS_STD_STRING
4186// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4187TEST(EqAssertionTest, StdString) {
4188 // Compares a const char* to an std::string that has identical
4189 // content.
4190 ASSERT_EQ("Test", ::std::string("Test"));
4191
4192 // Compares two identical std::strings.
4193 static const ::std::string str1("A * in the middle");
4194 static const ::std::string str2(str1);
4195 EXPECT_EQ(str1, str2);
4196
4197 // Compares a const char* to an std::string that has different
4198 // content
4199 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4200 "::std::string(\"test\")");
4201
4202 // Compares an std::string to a char* that has different content.
4203 char* const p1 = const_cast<char*>("foo");
4204 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4205 "p1");
4206
4207 // Compares two std::strings that have different contents, one of
4208 // which having a NUL character in the middle. This should fail.
4209 static ::std::string str3(str1);
4210 str3.at(2) = '\0';
4211 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4212 "Value of: str3\n"
4213 " Actual: \"A \\0 in the middle\"");
4214}
4215
4216#endif // GTEST_HAS_STD_STRING
4217
4218#if GTEST_HAS_STD_WSTRING
4219
4220// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4221TEST(EqAssertionTest, StdWideString) {
4222 // Compares an std::wstring to a const wchar_t* that has identical
4223 // content.
4224 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4225
4226 // Compares two identical std::wstrings.
4227 const ::std::wstring wstr1(L"A * in the middle");
4228 const ::std::wstring wstr2(wstr1);
4229 ASSERT_EQ(wstr1, wstr2);
4230
4231 // Compares an std::wstring to a const wchar_t* that has different
4232 // content.
4233 EXPECT_NONFATAL_FAILURE({ // NOLINT
4234 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4235 }, "L\"Test\\x8120\"");
4236
4237 // Compares two std::wstrings that have different contents, one of
4238 // which having a NUL character in the middle.
4239 ::std::wstring wstr3(wstr1);
4240 wstr3.at(2) = L'\0';
4241 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4242 "wstr3");
4243
4244 // Compares a wchar_t* to an std::wstring that has different
4245 // content.
4246 EXPECT_FATAL_FAILURE({ // NOLINT
4247 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4248 }, "");
4249}
4250
4251#endif // GTEST_HAS_STD_WSTRING
4252
4253#if GTEST_HAS_GLOBAL_STRING
4254// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4255TEST(EqAssertionTest, GlobalString) {
4256 // Compares a const char* to a ::string that has identical content.
4257 EXPECT_EQ("Test", ::string("Test"));
4258
4259 // Compares two identical ::strings.
4260 const ::string str1("A * in the middle");
4261 const ::string str2(str1);
4262 ASSERT_EQ(str1, str2);
4263
4264 // Compares a ::string to a const char* that has different content.
4265 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4266 "test");
4267
4268 // Compares two ::strings that have different contents, one of which
4269 // having a NUL character in the middle.
4270 ::string str3(str1);
4271 str3.at(2) = '\0';
4272 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4273 "str3");
4274
4275 // Compares a ::string to a char* that has different content.
4276 EXPECT_FATAL_FAILURE({ // NOLINT
4277 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4278 }, "");
4279}
4280
4281#endif // GTEST_HAS_GLOBAL_STRING
4282
4283#if GTEST_HAS_GLOBAL_WSTRING
4284
4285// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4286TEST(EqAssertionTest, GlobalWideString) {
4287 // Compares a const wchar_t* to a ::wstring that has identical content.
4288 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4289
4290 // Compares two identical ::wstrings.
4291 static const ::wstring wstr1(L"A * in the middle");
4292 static const ::wstring wstr2(wstr1);
4293 EXPECT_EQ(wstr1, wstr2);
4294
4295 // Compares a const wchar_t* to a ::wstring that has different
4296 // content.
4297 EXPECT_NONFATAL_FAILURE({ // NOLINT
4298 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4299 }, "Test\\x8119");
4300
4301 // Compares a wchar_t* to a ::wstring that has different content.
4302 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4303 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4304 "bar");
4305
4306 // Compares two ::wstrings that have different contents, one of which
4307 // having a NUL character in the middle.
4308 static ::wstring wstr3;
4309 wstr3 = wstr1;
4310 wstr3.at(2) = L'\0';
4311 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4312 "wstr3");
4313}
4314
4315#endif // GTEST_HAS_GLOBAL_WSTRING
4316
4317// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4318TEST(EqAssertionTest, CharPointer) {
4319 char* const p0 = NULL;
4320 // Only way to get the Nokia compiler to compile the cast
4321 // is to have a separate void* variable first. Putting
4322 // the two casts on the same line doesn't work, neither does
4323 // a direct C-style to char*.
4324 void* pv1 = (void*)0x1234; // NOLINT
4325 void* pv2 = (void*)0xABC0; // NOLINT
4326 char* const p1 = reinterpret_cast<char*>(pv1);
4327 char* const p2 = reinterpret_cast<char*>(pv2);
4328 ASSERT_EQ(p1, p1);
4329
4330 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4331 "Value of: p2");
4332 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4333 "p2");
4334 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4335 reinterpret_cast<char*>(0xABC0)),
4336 "ABC0");
4337}
4338
4339// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4340TEST(EqAssertionTest, WideCharPointer) {
4341 wchar_t* const p0 = NULL;
4342 // Only way to get the Nokia compiler to compile the cast
4343 // is to have a separate void* variable first. Putting
4344 // the two casts on the same line doesn't work, neither does
4345 // a direct C-style to char*.
4346 void* pv1 = (void*)0x1234; // NOLINT
4347 void* pv2 = (void*)0xABC0; // NOLINT
4348 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4349 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4350 EXPECT_EQ(p0, p0);
4351
4352 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4353 "Value of: p2");
4354 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4355 "p2");
4356 void* pv3 = (void*)0x1234; // NOLINT
4357 void* pv4 = (void*)0xABC0; // NOLINT
4358 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4359 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4360 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4361 "p4");
4362}
4363
4364// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4365TEST(EqAssertionTest, OtherPointer) {
4366 ASSERT_EQ(static_cast<const int*>(NULL),
4367 static_cast<const int*>(NULL));
4368 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4369 reinterpret_cast<const int*>(0x1234)),
4370 "0x1234");
4371}
4372
4373// Tests the FRIEND_TEST macro.
4374
4375// This class has a private member we want to test. We will test it
4376// both in a TEST and in a TEST_F.
4377class Foo {
4378 public:
4379 Foo() {}
4380
4381 private:
4382 int Bar() const { return 1; }
4383
4384 // Declares the friend tests that can access the private member
4385 // Bar().
4386 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4387 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4388};
4389
4390// Tests that the FRIEND_TEST declaration allows a TEST to access a
4391// class's private members. This should compile.
4392TEST(FRIEND_TEST_Test, TEST) {
4393 ASSERT_EQ(1, Foo().Bar());
4394}
4395
4396// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004397class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004398 protected:
4399 Foo foo;
4400};
4401
4402// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4403// class's private members. This should compile.
4404TEST_F(FRIEND_TEST_Test2, TEST_F) {
4405 ASSERT_EQ(1, foo.Bar());
4406}
4407
4408// Tests the life cycle of Test objects.
4409
4410// The test fixture for testing the life cycle of Test objects.
4411//
4412// This class counts the number of live test objects that uses this
4413// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004414class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004415 protected:
4416 // Constructor. Increments the number of test objects that uses
4417 // this fixture.
4418 TestLifeCycleTest() { count_++; }
4419
4420 // Destructor. Decrements the number of test objects that uses this
4421 // fixture.
4422 ~TestLifeCycleTest() { count_--; }
4423
4424 // Returns the number of live test objects that uses this fixture.
4425 int count() const { return count_; }
4426
4427 private:
4428 static int count_;
4429};
4430
4431int TestLifeCycleTest::count_ = 0;
4432
4433// Tests the life cycle of test objects.
4434TEST_F(TestLifeCycleTest, Test1) {
4435 // There should be only one test object in this test case that's
4436 // currently alive.
4437 ASSERT_EQ(1, count());
4438}
4439
4440// Tests the life cycle of test objects.
4441TEST_F(TestLifeCycleTest, Test2) {
4442 // After Test1 is done and Test2 is started, there should still be
4443 // only one live test object, as the object for Test1 should've been
4444 // deleted.
4445 ASSERT_EQ(1, count());
4446}
4447
4448} // namespace
4449
4450// Tests streaming a user type whose definition and operator << are
4451// both in the global namespace.
4452class Base {
4453 public:
4454 explicit Base(int x) : x_(x) {}
4455 int x() const { return x_; }
4456 private:
4457 int x_;
4458};
4459std::ostream& operator<<(std::ostream& os,
4460 const Base& val) {
4461 return os << val.x();
4462}
4463std::ostream& operator<<(std::ostream& os,
4464 const Base* pointer) {
4465 return os << "(" << pointer->x() << ")";
4466}
4467
4468TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004469 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004470 Base a(1);
4471
4472 msg << a << &a; // Uses ::operator<<.
4473 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4474}
4475
4476// Tests streaming a user type whose definition and operator<< are
4477// both in an unnamed namespace.
4478namespace {
4479class MyTypeInUnnamedNameSpace : public Base {
4480 public:
4481 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {}
4482};
4483std::ostream& operator<<(std::ostream& os,
4484 const MyTypeInUnnamedNameSpace& val) {
4485 return os << val.x();
4486}
4487std::ostream& operator<<(std::ostream& os,
4488 const MyTypeInUnnamedNameSpace* pointer) {
4489 return os << "(" << pointer->x() << ")";
4490}
4491} // namespace
4492
4493TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004494 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004495 MyTypeInUnnamedNameSpace a(1);
4496
4497 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4498 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4499}
4500
4501// Tests streaming a user type whose definition and operator<< are
4502// both in a user namespace.
4503namespace namespace1 {
4504class MyTypeInNameSpace1 : public Base {
4505 public:
4506 explicit MyTypeInNameSpace1(int x): Base(x) {}
4507};
4508std::ostream& operator<<(std::ostream& os,
4509 const MyTypeInNameSpace1& val) {
4510 return os << val.x();
4511}
4512std::ostream& operator<<(std::ostream& os,
4513 const MyTypeInNameSpace1* pointer) {
4514 return os << "(" << pointer->x() << ")";
4515}
4516} // namespace namespace1
4517
4518TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004519 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004520 namespace1::MyTypeInNameSpace1 a(1);
4521
4522 msg << a << &a; // Uses namespace1::operator<<.
4523 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4524}
4525
4526// Tests streaming a user type whose definition is in a user namespace
4527// but whose operator<< is in the global namespace.
4528namespace namespace2 {
4529class MyTypeInNameSpace2 : public ::Base {
4530 public:
4531 explicit MyTypeInNameSpace2(int x): Base(x) {}
4532};
4533} // namespace namespace2
4534std::ostream& operator<<(std::ostream& os,
4535 const namespace2::MyTypeInNameSpace2& val) {
4536 return os << val.x();
4537}
4538std::ostream& operator<<(std::ostream& os,
4539 const namespace2::MyTypeInNameSpace2* pointer) {
4540 return os << "(" << pointer->x() << ")";
4541}
4542
4543TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00004544 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004545 namespace2::MyTypeInNameSpace2 a(1);
4546
4547 msg << a << &a; // Uses ::operator<<.
4548 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4549}
4550
4551// Tests streaming NULL pointers to testing::Message.
4552TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00004553 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004554 char* const p1 = NULL;
4555 unsigned char* const p2 = NULL;
4556 int* p3 = NULL;
4557 double* p4 = NULL;
4558 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00004559 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004560
4561 msg << p1 << p2 << p3 << p4 << p5 << p6;
4562 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4563 msg.GetString().c_str());
4564}
4565
4566// Tests streaming wide strings to testing::Message.
4567TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00004568 // Streams a NULL of type const wchar_t*.
4569 const wchar_t* const_wstr = NULL;
4570 EXPECT_STREQ("(null)",
4571 (Message() << const_wstr).GetString().c_str());
4572
4573 // Streams a NULL of type wchar_t*.
4574 wchar_t* wstr = NULL;
4575 EXPECT_STREQ("(null)",
4576 (Message() << wstr).GetString().c_str());
4577
4578 // Streams a non-NULL of type const wchar_t*.
4579 const_wstr = L"abc\x8119";
4580 EXPECT_STREQ("abc\xe8\x84\x99",
4581 (Message() << const_wstr).GetString().c_str());
4582
4583 // Streams a non-NULL of type wchar_t*.
4584 wstr = const_cast<wchar_t*>(const_wstr);
4585 EXPECT_STREQ("abc\xe8\x84\x99",
4586 (Message() << wstr).GetString().c_str());
4587}
4588
4589
4590// This line tests that we can define tests in the testing namespace.
4591namespace testing {
4592
4593// Tests the TestInfo class.
4594
shiqian760af5c2008-08-06 21:43:15 +00004595class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004596 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004597 static const TestInfo* GetTestInfo(const char* test_name) {
4598 const TestCase* const test_case = GetUnitTestImpl()->
4599 GetTestCase("TestInfoTest", "", NULL, NULL);
4600
4601 for (int i = 0; i < test_case->total_test_count(); ++i) {
4602 const TestInfo* const test_info = test_case->GetTestInfo(i);
4603 if (strcmp(test_name, test_info->name()) == 0)
4604 return test_info;
4605 }
4606 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004607 }
4608
4609 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00004610 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00004611 return test_info->result();
4612 }
4613};
4614
4615// Tests TestInfo::test_case_name() and TestInfo::name().
4616TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004617 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00004618
4619 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
4620 ASSERT_STREQ("Names", test_info->name());
4621}
4622
4623// Tests TestInfo::result().
4624TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004625 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00004626
4627 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004628 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004629
4630 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004631 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004632}
4633
4634// Tests setting up and tearing down a test case.
4635
shiqian760af5c2008-08-06 21:43:15 +00004636class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004637 protected:
4638 // This will be called once before the first test in this test case
4639 // is run.
4640 static void SetUpTestCase() {
4641 printf("Setting up the test case . . .\n");
4642
4643 // Initializes some shared resource. In this simple example, we
4644 // just create a C string. More complex stuff can be done if
4645 // desired.
4646 shared_resource_ = "123";
4647
4648 // Increments the number of test cases that have been set up.
4649 counter_++;
4650
4651 // SetUpTestCase() should be called only once.
4652 EXPECT_EQ(1, counter_);
4653 }
4654
4655 // This will be called once after the last test in this test case is
4656 // run.
4657 static void TearDownTestCase() {
4658 printf("Tearing down the test case . . .\n");
4659
4660 // Decrements the number of test cases that have been set up.
4661 counter_--;
4662
4663 // TearDownTestCase() should be called only once.
4664 EXPECT_EQ(0, counter_);
4665
4666 // Cleans up the shared resource.
4667 shared_resource_ = NULL;
4668 }
4669
4670 // This will be called before each test in this test case.
4671 virtual void SetUp() {
4672 // SetUpTestCase() should be called only once, so counter_ should
4673 // always be 1.
4674 EXPECT_EQ(1, counter_);
4675 }
4676
4677 // Number of test cases that have been set up.
4678 static int counter_;
4679
4680 // Some resource to be shared by all tests in this test case.
4681 static const char* shared_resource_;
4682};
4683
4684int SetUpTestCaseTest::counter_ = 0;
4685const char* SetUpTestCaseTest::shared_resource_ = NULL;
4686
4687// A test that uses the shared resource.
4688TEST_F(SetUpTestCaseTest, Test1) {
4689 EXPECT_STRNE(NULL, shared_resource_);
4690}
4691
4692// Another test that uses the shared resource.
4693TEST_F(SetUpTestCaseTest, Test2) {
4694 EXPECT_STREQ("123", shared_resource_);
4695}
4696
4697// The InitGoogleTestTest test case tests testing::InitGoogleTest().
4698
4699// The Flags struct stores a copy of all Google Test flags.
4700struct Flags {
4701 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00004702 Flags() : also_run_disabled_tests(false),
4703 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00004704 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00004705 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00004706 filter(""),
4707 list_tests(false),
4708 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00004709 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004710 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004711 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004712 shuffle(false),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004713 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00004714
4715 // Factory methods.
4716
shiqianca6949f2009-01-10 01:16:33 +00004717 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
4718 // the given value.
4719 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
4720 Flags flags;
4721 flags.also_run_disabled_tests = also_run_disabled_tests;
4722 return flags;
4723 }
4724
shiqian4b6829f2008-07-03 22:38:12 +00004725 // Creates a Flags struct where the gtest_break_on_failure flag has
4726 // the given value.
4727 static Flags BreakOnFailure(bool break_on_failure) {
4728 Flags flags;
4729 flags.break_on_failure = break_on_failure;
4730 return flags;
4731 }
4732
4733 // Creates a Flags struct where the gtest_catch_exceptions flag has
4734 // the given value.
4735 static Flags CatchExceptions(bool catch_exceptions) {
4736 Flags flags;
4737 flags.catch_exceptions = catch_exceptions;
4738 return flags;
4739 }
4740
shiqian21d43d12009-01-08 01:10:31 +00004741 // Creates a Flags struct where the gtest_death_test_use_fork flag has
4742 // the given value.
4743 static Flags DeathTestUseFork(bool death_test_use_fork) {
4744 Flags flags;
4745 flags.death_test_use_fork = death_test_use_fork;
4746 return flags;
4747 }
4748
shiqian4b6829f2008-07-03 22:38:12 +00004749 // Creates a Flags struct where the gtest_filter flag has the given
4750 // value.
4751 static Flags Filter(const char* filter) {
4752 Flags flags;
4753 flags.filter = filter;
4754 return flags;
4755 }
4756
4757 // Creates a Flags struct where the gtest_list_tests flag has the
4758 // given value.
4759 static Flags ListTests(bool list_tests) {
4760 Flags flags;
4761 flags.list_tests = list_tests;
4762 return flags;
4763 }
4764
4765 // Creates a Flags struct where the gtest_output flag has the given
4766 // value.
4767 static Flags Output(const char* output) {
4768 Flags flags;
4769 flags.output = output;
4770 return flags;
4771 }
4772
shiqiand981cee2008-07-25 04:06:16 +00004773 // Creates a Flags struct where the gtest_print_time flag has the given
4774 // value.
4775 static Flags PrintTime(bool print_time) {
4776 Flags flags;
4777 flags.print_time = print_time;
4778 return flags;
4779 }
4780
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004781 // Creates a Flags struct where the gtest_random_seed flag has
4782 // the given value.
4783 static Flags RandomSeed(Int32 random_seed) {
4784 Flags flags;
4785 flags.random_seed = random_seed;
4786 return flags;
4787 }
4788
shiqian4b6829f2008-07-03 22:38:12 +00004789 // Creates a Flags struct where the gtest_repeat flag has the given
4790 // value.
4791 static Flags Repeat(Int32 repeat) {
4792 Flags flags;
4793 flags.repeat = repeat;
4794 return flags;
4795 }
4796
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004797 // Creates a Flags struct where the gtest_shuffle flag has
4798 // the given value.
4799 static Flags Shuffle(bool shuffle) {
4800 Flags flags;
4801 flags.shuffle = shuffle;
4802 return flags;
4803 }
4804
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004805 // Creates a Flags struct where the gtest_throw_on_failure flag has
4806 // the given value.
4807 static Flags ThrowOnFailure(bool throw_on_failure) {
4808 Flags flags;
4809 flags.throw_on_failure = throw_on_failure;
4810 return flags;
4811 }
4812
shiqian4b6829f2008-07-03 22:38:12 +00004813 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00004814 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00004815 bool break_on_failure;
4816 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00004817 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00004818 const char* filter;
4819 bool list_tests;
4820 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00004821 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004822 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00004823 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004824 bool shuffle;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004825 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00004826};
4827
4828// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00004829class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004830 protected:
4831 // Clears the flags before each test.
4832 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00004833 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004834 GTEST_FLAG(break_on_failure) = false;
4835 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00004836 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004837 GTEST_FLAG(filter) = "";
4838 GTEST_FLAG(list_tests) = false;
4839 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00004840 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004841 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00004842 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004843 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004844 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004845 }
4846
4847 // Asserts that two narrow or wide string arrays are equal.
4848 template <typename CharType>
4849 static void AssertStringArrayEq(size_t size1, CharType** array1,
4850 size_t size2, CharType** array2) {
4851 ASSERT_EQ(size1, size2) << " Array sizes different.";
4852
4853 for (size_t i = 0; i != size1; i++) {
4854 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
4855 }
4856 }
4857
4858 // Verifies that the flag values match the expected values.
4859 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00004860 EXPECT_EQ(expected.also_run_disabled_tests,
4861 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00004862 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
4863 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00004864 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00004865 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
4866 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
4867 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00004868 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004869 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00004870 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004871 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004872 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00004873 }
4874
4875 // Parses a command line (specified by argc1 and argv1), then
4876 // verifies that the flag values are expected and that the
4877 // recognized flags are removed from the command line.
4878 template <typename CharType>
4879 static void TestParsingFlags(int argc1, const CharType** argv1,
4880 int argc2, const CharType** argv2,
4881 const Flags& expected) {
4882 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00004883 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00004884
4885 // Verifies the flag values.
4886 CheckFlags(expected);
4887
4888 // Verifies that the recognized flags are removed from the command
4889 // line.
4890 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
4891 }
4892
4893 // This macro wraps TestParsingFlags s.t. the user doesn't need
4894 // to specify the array sizes.
zhanyong.wan4cd62602009-02-23 23:21:55 +00004895#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected) \
shiqian4b6829f2008-07-03 22:38:12 +00004896 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
4897 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected)
4898};
4899
4900// Tests parsing an empty command line.
4901TEST_F(InitGoogleTestTest, Empty) {
4902 const char* argv[] = {
4903 NULL
4904 };
4905
4906 const char* argv2[] = {
4907 NULL
4908 };
4909
zhanyong.wan4cd62602009-02-23 23:21:55 +00004910 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00004911}
4912
4913// Tests parsing a command line that has no flag.
4914TEST_F(InitGoogleTestTest, NoFlag) {
4915 const char* argv[] = {
4916 "foo.exe",
4917 NULL
4918 };
4919
4920 const char* argv2[] = {
4921 "foo.exe",
4922 NULL
4923 };
4924
zhanyong.wan4cd62602009-02-23 23:21:55 +00004925 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00004926}
4927
4928// Tests parsing a bad --gtest_filter flag.
4929TEST_F(InitGoogleTestTest, FilterBad) {
4930 const char* argv[] = {
4931 "foo.exe",
4932 "--gtest_filter",
4933 NULL
4934 };
4935
4936 const char* argv2[] = {
4937 "foo.exe",
4938 "--gtest_filter",
4939 NULL
4940 };
4941
zhanyong.wan4cd62602009-02-23 23:21:55 +00004942 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00004943}
4944
4945// Tests parsing an empty --gtest_filter flag.
4946TEST_F(InitGoogleTestTest, FilterEmpty) {
4947 const char* argv[] = {
4948 "foo.exe",
4949 "--gtest_filter=",
4950 NULL
4951 };
4952
4953 const char* argv2[] = {
4954 "foo.exe",
4955 NULL
4956 };
4957
zhanyong.wan4cd62602009-02-23 23:21:55 +00004958 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00004959}
4960
4961// Tests parsing a non-empty --gtest_filter flag.
4962TEST_F(InitGoogleTestTest, FilterNonEmpty) {
4963 const char* argv[] = {
4964 "foo.exe",
4965 "--gtest_filter=abc",
4966 NULL
4967 };
4968
4969 const char* argv2[] = {
4970 "foo.exe",
4971 NULL
4972 };
4973
zhanyong.wan4cd62602009-02-23 23:21:55 +00004974 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"));
shiqian4b6829f2008-07-03 22:38:12 +00004975}
4976
4977// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004978TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00004979 const char* argv[] = {
4980 "foo.exe",
4981 "--gtest_break_on_failure",
4982 NULL
4983};
4984
4985 const char* argv2[] = {
4986 "foo.exe",
4987 NULL
4988 };
4989
zhanyong.wan4cd62602009-02-23 23:21:55 +00004990 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00004991}
4992
4993// Tests parsing --gtest_break_on_failure=0.
4994TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
4995 const char* argv[] = {
4996 "foo.exe",
4997 "--gtest_break_on_failure=0",
4998 NULL
4999 };
5000
5001 const char* argv2[] = {
5002 "foo.exe",
5003 NULL
5004 };
5005
zhanyong.wan4cd62602009-02-23 23:21:55 +00005006 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005007}
5008
5009// Tests parsing --gtest_break_on_failure=f.
5010TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5011 const char* argv[] = {
5012 "foo.exe",
5013 "--gtest_break_on_failure=f",
5014 NULL
5015 };
5016
5017 const char* argv2[] = {
5018 "foo.exe",
5019 NULL
5020 };
5021
zhanyong.wan4cd62602009-02-23 23:21:55 +00005022 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005023}
5024
5025// Tests parsing --gtest_break_on_failure=F.
5026TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5027 const char* argv[] = {
5028 "foo.exe",
5029 "--gtest_break_on_failure=F",
5030 NULL
5031 };
5032
5033 const char* argv2[] = {
5034 "foo.exe",
5035 NULL
5036 };
5037
zhanyong.wan4cd62602009-02-23 23:21:55 +00005038 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005039}
5040
5041// Tests parsing a --gtest_break_on_failure flag that has a "true"
5042// definition.
5043TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5044 const char* argv[] = {
5045 "foo.exe",
5046 "--gtest_break_on_failure=1",
5047 NULL
5048 };
5049
5050 const char* argv2[] = {
5051 "foo.exe",
5052 NULL
5053 };
5054
zhanyong.wan4cd62602009-02-23 23:21:55 +00005055 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00005056}
5057
5058// Tests parsing --gtest_catch_exceptions.
5059TEST_F(InitGoogleTestTest, CatchExceptions) {
5060 const char* argv[] = {
5061 "foo.exe",
5062 "--gtest_catch_exceptions",
5063 NULL
5064 };
5065
5066 const char* argv2[] = {
5067 "foo.exe",
5068 NULL
5069 };
5070
zhanyong.wan4cd62602009-02-23 23:21:55 +00005071 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true));
shiqian4b6829f2008-07-03 22:38:12 +00005072}
5073
shiqian21d43d12009-01-08 01:10:31 +00005074// Tests parsing --gtest_death_test_use_fork.
5075TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5076 const char* argv[] = {
5077 "foo.exe",
5078 "--gtest_death_test_use_fork",
5079 NULL
5080 };
5081
5082 const char* argv2[] = {
5083 "foo.exe",
5084 NULL
5085 };
5086
zhanyong.wan4cd62602009-02-23 23:21:55 +00005087 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true));
shiqian21d43d12009-01-08 01:10:31 +00005088}
5089
shiqian4b6829f2008-07-03 22:38:12 +00005090// Tests having the same flag twice with different values. The
5091// expected behavior is that the one coming last takes precedence.
5092TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5093 const char* argv[] = {
5094 "foo.exe",
5095 "--gtest_filter=a",
5096 "--gtest_filter=b",
5097 NULL
5098 };
5099
5100 const char* argv2[] = {
5101 "foo.exe",
5102 NULL
5103 };
5104
zhanyong.wan4cd62602009-02-23 23:21:55 +00005105 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"));
shiqian4b6829f2008-07-03 22:38:12 +00005106}
5107
5108// Tests having an unrecognized flag on the command line.
5109TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5110 const char* argv[] = {
5111 "foo.exe",
5112 "--gtest_break_on_failure",
5113 "bar", // Unrecognized by Google Test.
5114 "--gtest_filter=b",
5115 NULL
5116 };
5117
5118 const char* argv2[] = {
5119 "foo.exe",
5120 "bar",
5121 NULL
5122 };
5123
5124 Flags flags;
5125 flags.break_on_failure = true;
5126 flags.filter = "b";
zhanyong.wan4cd62602009-02-23 23:21:55 +00005127 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags);
shiqian4b6829f2008-07-03 22:38:12 +00005128}
5129
5130// Tests having a --gtest_list_tests flag
5131TEST_F(InitGoogleTestTest, ListTestsFlag) {
5132 const char* argv[] = {
5133 "foo.exe",
5134 "--gtest_list_tests",
5135 NULL
5136 };
5137
5138 const char* argv2[] = {
5139 "foo.exe",
5140 NULL
5141 };
5142
zhanyong.wan4cd62602009-02-23 23:21:55 +00005143 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005144}
5145
5146// Tests having a --gtest_list_tests flag with a "true" value
5147TEST_F(InitGoogleTestTest, ListTestsTrue) {
5148 const char* argv[] = {
5149 "foo.exe",
5150 "--gtest_list_tests=1",
5151 NULL
5152 };
5153
5154 const char* argv2[] = {
5155 "foo.exe",
5156 NULL
5157 };
5158
zhanyong.wan4cd62602009-02-23 23:21:55 +00005159 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005160}
5161
5162// Tests having a --gtest_list_tests flag with a "false" value
5163TEST_F(InitGoogleTestTest, ListTestsFalse) {
5164 const char* argv[] = {
5165 "foo.exe",
5166 "--gtest_list_tests=0",
5167 NULL
5168 };
5169
5170 const char* argv2[] = {
5171 "foo.exe",
5172 NULL
5173 };
5174
zhanyong.wan4cd62602009-02-23 23:21:55 +00005175 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005176}
5177
5178// Tests parsing --gtest_list_tests=f.
5179TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5180 const char* argv[] = {
5181 "foo.exe",
5182 "--gtest_list_tests=f",
5183 NULL
5184 };
5185
5186 const char* argv2[] = {
5187 "foo.exe",
5188 NULL
5189 };
5190
zhanyong.wan4cd62602009-02-23 23:21:55 +00005191 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005192}
5193
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005194// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005195TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5196 const char* argv[] = {
5197 "foo.exe",
5198 "--gtest_list_tests=F",
5199 NULL
5200 };
5201
5202 const char* argv2[] = {
5203 "foo.exe",
5204 NULL
5205 };
5206
zhanyong.wan4cd62602009-02-23 23:21:55 +00005207 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005208}
5209
5210// Tests parsing --gtest_output (invalid).
5211TEST_F(InitGoogleTestTest, OutputEmpty) {
5212 const char* argv[] = {
5213 "foo.exe",
5214 "--gtest_output",
5215 NULL
5216 };
5217
5218 const char* argv2[] = {
5219 "foo.exe",
5220 "--gtest_output",
5221 NULL
5222 };
5223
zhanyong.wan4cd62602009-02-23 23:21:55 +00005224 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00005225}
5226
5227// Tests parsing --gtest_output=xml
5228TEST_F(InitGoogleTestTest, OutputXml) {
5229 const char* argv[] = {
5230 "foo.exe",
5231 "--gtest_output=xml",
5232 NULL
5233 };
5234
5235 const char* argv2[] = {
5236 "foo.exe",
5237 NULL
5238 };
5239
zhanyong.wan4cd62602009-02-23 23:21:55 +00005240 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"));
shiqian4b6829f2008-07-03 22:38:12 +00005241}
5242
5243// Tests parsing --gtest_output=xml:file
5244TEST_F(InitGoogleTestTest, OutputXmlFile) {
5245 const char* argv[] = {
5246 "foo.exe",
5247 "--gtest_output=xml:file",
5248 NULL
5249 };
5250
5251 const char* argv2[] = {
5252 "foo.exe",
5253 NULL
5254 };
5255
zhanyong.wan4cd62602009-02-23 23:21:55 +00005256 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"));
shiqian4b6829f2008-07-03 22:38:12 +00005257}
5258
5259// Tests parsing --gtest_output=xml:directory/path/
5260TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5261 const char* argv[] = {
5262 "foo.exe",
5263 "--gtest_output=xml:directory/path/",
5264 NULL
5265 };
5266
5267 const char* argv2[] = {
5268 "foo.exe",
5269 NULL
5270 };
5271
zhanyong.wan4cd62602009-02-23 23:21:55 +00005272 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"));
shiqian4b6829f2008-07-03 22:38:12 +00005273}
5274
shiqiand981cee2008-07-25 04:06:16 +00005275// Tests having a --gtest_print_time flag
5276TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5277 const char* argv[] = {
5278 "foo.exe",
5279 "--gtest_print_time",
5280 NULL
5281 };
5282
5283 const char* argv2[] = {
5284 "foo.exe",
5285 NULL
5286 };
5287
zhanyong.wan4cd62602009-02-23 23:21:55 +00005288 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005289}
5290
5291// Tests having a --gtest_print_time flag with a "true" value
5292TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5293 const char* argv[] = {
5294 "foo.exe",
5295 "--gtest_print_time=1",
5296 NULL
5297 };
5298
5299 const char* argv2[] = {
5300 "foo.exe",
5301 NULL
5302 };
5303
zhanyong.wan4cd62602009-02-23 23:21:55 +00005304 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005305}
5306
5307// Tests having a --gtest_print_time flag with a "false" value
5308TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5309 const char* argv[] = {
5310 "foo.exe",
5311 "--gtest_print_time=0",
5312 NULL
5313 };
5314
5315 const char* argv2[] = {
5316 "foo.exe",
5317 NULL
5318 };
5319
zhanyong.wan4cd62602009-02-23 23:21:55 +00005320 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005321}
5322
5323// Tests parsing --gtest_print_time=f.
5324TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5325 const char* argv[] = {
5326 "foo.exe",
5327 "--gtest_print_time=f",
5328 NULL
5329 };
5330
5331 const char* argv2[] = {
5332 "foo.exe",
5333 NULL
5334 };
5335
zhanyong.wan4cd62602009-02-23 23:21:55 +00005336 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005337}
5338
5339// Tests parsing --gtest_print_time=F.
5340TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5341 const char* argv[] = {
5342 "foo.exe",
5343 "--gtest_print_time=F",
5344 NULL
5345 };
5346
5347 const char* argv2[] = {
5348 "foo.exe",
5349 NULL
5350 };
5351
zhanyong.wan4cd62602009-02-23 23:21:55 +00005352 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005353}
5354
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005355// Tests parsing --gtest_random_seed=number
5356TEST_F(InitGoogleTestTest, RandomSeed) {
5357 const char* argv[] = {
5358 "foo.exe",
5359 "--gtest_random_seed=1000",
5360 NULL
5361 };
5362
5363 const char* argv2[] = {
5364 "foo.exe",
5365 NULL
5366 };
5367
5368 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000));
5369}
5370
shiqian4b6829f2008-07-03 22:38:12 +00005371// Tests parsing --gtest_repeat=number
5372TEST_F(InitGoogleTestTest, Repeat) {
5373 const char* argv[] = {
5374 "foo.exe",
5375 "--gtest_repeat=1000",
5376 NULL
5377 };
5378
5379 const char* argv2[] = {
5380 "foo.exe",
5381 NULL
5382 };
5383
zhanyong.wan4cd62602009-02-23 23:21:55 +00005384 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000));
shiqian4b6829f2008-07-03 22:38:12 +00005385}
5386
shiqianca6949f2009-01-10 01:16:33 +00005387// Tests having a --gtest_also_run_disabled_tests flag
5388TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5389 const char* argv[] = {
5390 "foo.exe",
5391 "--gtest_also_run_disabled_tests",
5392 NULL
5393 };
5394
5395 const char* argv2[] = {
5396 "foo.exe",
5397 NULL
5398 };
5399
zhanyong.wan4cd62602009-02-23 23:21:55 +00005400 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005401}
5402
5403// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5404TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5405 const char* argv[] = {
5406 "foo.exe",
5407 "--gtest_also_run_disabled_tests=1",
5408 NULL
5409 };
5410
5411 const char* argv2[] = {
5412 "foo.exe",
5413 NULL
5414 };
5415
zhanyong.wan4cd62602009-02-23 23:21:55 +00005416 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005417}
5418
5419// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5420TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5421 const char* argv[] = {
5422 "foo.exe",
5423 "--gtest_also_run_disabled_tests=0",
5424 NULL
5425 };
5426
5427 const char* argv2[] = {
5428 "foo.exe",
5429 NULL
5430 };
5431
zhanyong.wan4cd62602009-02-23 23:21:55 +00005432 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false));
shiqianca6949f2009-01-10 01:16:33 +00005433}
5434
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005435// Tests parsing --gtest_shuffle.
5436TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
5437 const char* argv[] = {
5438 "foo.exe",
5439 "--gtest_shuffle",
5440 NULL
5441};
5442
5443 const char* argv2[] = {
5444 "foo.exe",
5445 NULL
5446 };
5447
5448 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5449}
5450
5451// Tests parsing --gtest_shuffle=0.
5452TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
5453 const char* argv[] = {
5454 "foo.exe",
5455 "--gtest_shuffle=0",
5456 NULL
5457 };
5458
5459 const char* argv2[] = {
5460 "foo.exe",
5461 NULL
5462 };
5463
5464 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false));
5465}
5466
5467// Tests parsing a --gtest_shuffle flag that has a "true"
5468// definition.
5469TEST_F(InitGoogleTestTest, ShuffleTrue) {
5470 const char* argv[] = {
5471 "foo.exe",
5472 "--gtest_shuffle=1",
5473 NULL
5474 };
5475
5476 const char* argv2[] = {
5477 "foo.exe",
5478 NULL
5479 };
5480
5481 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5482}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005483
5484// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005485TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005486 const char* argv[] = {
5487 "foo.exe",
5488 "--gtest_throw_on_failure",
5489 NULL
5490};
5491
5492 const char* argv2[] = {
5493 "foo.exe",
5494 NULL
5495 };
5496
5497 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5498}
5499
5500// Tests parsing --gtest_throw_on_failure=0.
5501TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5502 const char* argv[] = {
5503 "foo.exe",
5504 "--gtest_throw_on_failure=0",
5505 NULL
5506 };
5507
5508 const char* argv2[] = {
5509 "foo.exe",
5510 NULL
5511 };
5512
5513 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false));
5514}
5515
5516// Tests parsing a --gtest_throw_on_failure flag that has a "true"
5517// definition.
5518TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
5519 const char* argv[] = {
5520 "foo.exe",
5521 "--gtest_throw_on_failure=1",
5522 NULL
5523 };
5524
5525 const char* argv2[] = {
5526 "foo.exe",
5527 NULL
5528 };
5529
5530 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5531}
5532
zhanyong.wan4cd62602009-02-23 23:21:55 +00005533#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00005534// Tests parsing wide strings.
5535TEST_F(InitGoogleTestTest, WideStrings) {
5536 const wchar_t* argv[] = {
5537 L"foo.exe",
5538 L"--gtest_filter=Foo*",
5539 L"--gtest_list_tests=1",
5540 L"--gtest_break_on_failure",
5541 L"--non_gtest_flag",
5542 NULL
5543 };
5544
5545 const wchar_t* argv2[] = {
5546 L"foo.exe",
5547 L"--non_gtest_flag",
5548 NULL
5549 };
5550
5551 Flags expected_flags;
5552 expected_flags.break_on_failure = true;
5553 expected_flags.filter = "Foo*";
5554 expected_flags.list_tests = true;
5555
zhanyong.wan4cd62602009-02-23 23:21:55 +00005556 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags);
shiqian4b6829f2008-07-03 22:38:12 +00005557}
5558#endif // GTEST_OS_WINDOWS
5559
5560// Tests current_test_info() in UnitTest.
5561class CurrentTestInfoTest : public Test {
5562 protected:
5563 // Tests that current_test_info() returns NULL before the first test in
5564 // the test case is run.
5565 static void SetUpTestCase() {
5566 // There should be no tests running at this point.
5567 const TestInfo* test_info =
5568 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005569 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005570 << "There should be no tests running at this point.";
5571 }
5572
5573 // Tests that current_test_info() returns NULL after the last test in
5574 // the test case has run.
5575 static void TearDownTestCase() {
5576 const TestInfo* test_info =
5577 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005578 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005579 << "There should be no tests running at this point.";
5580 }
5581};
5582
5583// Tests that current_test_info() returns TestInfo for currently running
5584// test by checking the expected test name against the actual one.
5585TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
5586 const TestInfo* test_info =
5587 UnitTest::GetInstance()->current_test_info();
5588 ASSERT_TRUE(NULL != test_info)
5589 << "There is a test running so we should have a valid TestInfo.";
5590 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5591 << "Expected the name of the currently running test case.";
5592 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
5593 << "Expected the name of the currently running test.";
5594}
5595
5596// Tests that current_test_info() returns TestInfo for currently running
5597// test by checking the expected test name against the actual one. We
5598// use this test to see that the TestInfo object actually changed from
5599// the previous invocation.
5600TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
5601 const TestInfo* test_info =
5602 UnitTest::GetInstance()->current_test_info();
5603 ASSERT_TRUE(NULL != test_info)
5604 << "There is a test running so we should have a valid TestInfo.";
5605 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5606 << "Expected the name of the currently running test case.";
5607 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
5608 << "Expected the name of the currently running test.";
5609}
5610
5611} // namespace testing
5612
5613// These two lines test that we can define tests in a namespace that
5614// has the name "testing" and is nested in another namespace.
5615namespace my_namespace {
5616namespace testing {
5617
5618// Makes sure that TEST knows to use ::testing::Test instead of
5619// ::my_namespace::testing::Test.
5620class Test {};
5621
5622// Makes sure that an assertion knows to use ::testing::Message instead of
5623// ::my_namespace::testing::Message.
5624class Message {};
5625
5626// Makes sure that an assertion knows to use
5627// ::testing::AssertionResult instead of
5628// ::my_namespace::testing::AssertionResult.
5629class AssertionResult {};
5630
5631// Tests that an assertion that should succeed works as expected.
5632TEST(NestedTestingNamespaceTest, Success) {
5633 EXPECT_EQ(1, 1) << "This shouldn't fail.";
5634}
5635
5636// Tests that an assertion that should fail works as expected.
5637TEST(NestedTestingNamespaceTest, Failure) {
5638 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
5639 "This failure is expected.");
5640}
5641
5642} // namespace testing
5643} // namespace my_namespace
5644
5645// Tests that one can call superclass SetUp and TearDown methods--
5646// that is, that they are not private.
5647// No tests are based on this fixture; the test "passes" if it compiles
5648// successfully.
shiqian760af5c2008-08-06 21:43:15 +00005649class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005650 protected:
5651 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00005652 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00005653 }
5654 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00005655 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00005656 }
5657};
5658
5659// StreamingAssertionsTest tests the streaming versions of a representative
5660// sample of assertions.
5661TEST(StreamingAssertionsTest, Unconditional) {
5662 SUCCEED() << "expected success";
5663 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
5664 "expected failure");
5665 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
5666 "expected failure");
5667}
5668
zhanyong.wan98efcc42009-04-28 00:28:09 +00005669#ifdef __BORLANDC__
5670// Silences warnings: "Condition is always true", "Unreachable code"
5671#pragma option push -w-ccc -w-rch
5672#endif
5673
shiqian4b6829f2008-07-03 22:38:12 +00005674TEST(StreamingAssertionsTest, Truth) {
5675 EXPECT_TRUE(true) << "unexpected failure";
5676 ASSERT_TRUE(true) << "unexpected failure";
5677 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
5678 "expected failure");
5679 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
5680 "expected failure");
5681}
5682
5683TEST(StreamingAssertionsTest, Truth2) {
5684 EXPECT_FALSE(false) << "unexpected failure";
5685 ASSERT_FALSE(false) << "unexpected failure";
5686 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
5687 "expected failure");
5688 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
5689 "expected failure");
5690}
5691
zhanyong.wan98efcc42009-04-28 00:28:09 +00005692#ifdef __BORLANDC__
5693// Restores warnings after previous "#pragma option push" supressed them
5694#pragma option pop
5695#endif
5696
shiqian4b6829f2008-07-03 22:38:12 +00005697TEST(StreamingAssertionsTest, IntegerEquals) {
5698 EXPECT_EQ(1, 1) << "unexpected failure";
5699 ASSERT_EQ(1, 1) << "unexpected failure";
5700 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
5701 "expected failure");
5702 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
5703 "expected failure");
5704}
5705
5706TEST(StreamingAssertionsTest, IntegerLessThan) {
5707 EXPECT_LT(1, 2) << "unexpected failure";
5708 ASSERT_LT(1, 2) << "unexpected failure";
5709 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
5710 "expected failure");
5711 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
5712 "expected failure");
5713}
5714
5715TEST(StreamingAssertionsTest, StringsEqual) {
5716 EXPECT_STREQ("foo", "foo") << "unexpected failure";
5717 ASSERT_STREQ("foo", "foo") << "unexpected failure";
5718 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
5719 "expected failure");
5720 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
5721 "expected failure");
5722}
5723
5724TEST(StreamingAssertionsTest, StringsNotEqual) {
5725 EXPECT_STRNE("foo", "bar") << "unexpected failure";
5726 ASSERT_STRNE("foo", "bar") << "unexpected failure";
5727 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
5728 "expected failure");
5729 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
5730 "expected failure");
5731}
5732
5733TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
5734 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5735 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5736 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
5737 "expected failure");
5738 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
5739 "expected failure");
5740}
5741
5742TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
5743 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
5744 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
5745 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
5746 "expected failure");
5747 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
5748 "expected failure");
5749}
5750
5751TEST(StreamingAssertionsTest, FloatingPointEquals) {
5752 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5753 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5754 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5755 "expected failure");
5756 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5757 "expected failure");
5758}
5759
shiqian9204c8e2008-09-12 20:57:22 +00005760#if GTEST_HAS_EXCEPTIONS
5761
5762TEST(StreamingAssertionsTest, Throw) {
5763 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5764 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5765 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
5766 "expected failure", "expected failure");
5767 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
5768 "expected failure", "expected failure");
5769}
5770
5771TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00005772 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
5773 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00005774 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
5775 "expected failure", "expected failure");
5776 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
5777 "expected failure", "expected failure");
5778}
5779
5780TEST(StreamingAssertionsTest, AnyThrow) {
5781 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
5782 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00005783 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005784 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00005785 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005786 "expected failure", "expected failure");
5787}
5788
5789#endif // GTEST_HAS_EXCEPTIONS
5790
shiqian4b6829f2008-07-03 22:38:12 +00005791// Tests that Google Test correctly decides whether to use colors in the output.
5792
5793TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
5794 GTEST_FLAG(color) = "yes";
5795
5796 SetEnv("TERM", "xterm"); // TERM supports colors.
5797 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5798 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5799
5800 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5801 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5802 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5803}
5804
5805TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
5806 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5807
5808 GTEST_FLAG(color) = "True";
5809 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5810
5811 GTEST_FLAG(color) = "t";
5812 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5813
5814 GTEST_FLAG(color) = "1";
5815 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5816}
5817
5818TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
5819 GTEST_FLAG(color) = "no";
5820
5821 SetEnv("TERM", "xterm"); // TERM supports colors.
5822 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5823 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5824
5825 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5826 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5827 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5828}
5829
5830TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
5831 SetEnv("TERM", "xterm"); // TERM supports colors.
5832
5833 GTEST_FLAG(color) = "F";
5834 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5835
5836 GTEST_FLAG(color) = "0";
5837 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5838
5839 GTEST_FLAG(color) = "unknown";
5840 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5841}
5842
5843TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
5844 GTEST_FLAG(color) = "auto";
5845
5846 SetEnv("TERM", "xterm"); // TERM supports colors.
5847 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5848 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5849}
5850
5851TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
5852 GTEST_FLAG(color) = "auto";
5853
zhanyong.wan4cd62602009-02-23 23:21:55 +00005854#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00005855 // On Windows, we ignore the TERM variable as it's usually not set.
5856
5857 SetEnv("TERM", "dumb");
5858 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5859
5860 SetEnv("TERM", "");
5861 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5862
5863 SetEnv("TERM", "xterm");
5864 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5865#else
5866 // On non-Windows platforms, we rely on TERM to determine if the
5867 // terminal supports colors.
5868
5869 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5870 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5871
5872 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
5873 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5874
5875 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
5876 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5877
5878 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
5879 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5880
5881 SetEnv("TERM", "xterm"); // TERM supports colors.
5882 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5883
5884 SetEnv("TERM", "xterm-color"); // TERM supports colors.
5885 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00005886
5887 SetEnv("TERM", "linux"); // TERM supports colors.
5888 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00005889#endif // GTEST_OS_WINDOWS
5890}
5891
shiqian21d43d12009-01-08 01:10:31 +00005892// Verifies that StaticAssertTypeEq works in a namespace scope.
5893
5894static bool dummy1 = StaticAssertTypeEq<bool, bool>();
5895static bool dummy2 = StaticAssertTypeEq<const int, const int>();
5896
5897// Verifies that StaticAssertTypeEq works in a class.
5898
5899template <typename T>
5900class StaticAssertTypeEqTestHelper {
5901 public:
5902 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
5903};
5904
5905TEST(StaticAssertTypeEqTest, WorksInClass) {
5906 StaticAssertTypeEqTestHelper<bool>();
5907}
5908
5909// Verifies that StaticAssertTypeEq works inside a function.
5910
5911typedef int IntAlias;
5912
5913TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
5914 StaticAssertTypeEq<int, IntAlias>();
5915 StaticAssertTypeEq<int*, IntAlias*>();
5916}
5917
shiqiane44602e2008-10-11 07:20:02 +00005918TEST(ThreadLocalTest, DefaultConstructor) {
5919 ThreadLocal<int> t1;
5920 EXPECT_EQ(0, t1.get());
5921
5922 ThreadLocal<void*> t2;
5923 EXPECT_TRUE(t2.get() == NULL);
5924}
5925
5926TEST(ThreadLocalTest, Init) {
5927 ThreadLocal<int> t1(123);
5928 EXPECT_EQ(123, t1.get());
5929
5930 int i = 0;
5931 ThreadLocal<int*> t2(&i);
5932 EXPECT_EQ(&i, t2.get());
5933}
5934
vladlosevf904a612008-11-20 01:40:35 +00005935TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
5936 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
5937
5938 // We don't have a stack walker in Google Test yet.
5939 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
5940 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
5941}
zhanyong.wan1b171102009-04-07 21:03:22 +00005942
5943TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
5944 EXPECT_FALSE(HasNonfatalFailure());
5945}
5946
5947static void FailFatally() { FAIL(); }
5948
5949TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
5950 FailFatally();
5951 const bool has_nonfatal_failure = HasNonfatalFailure();
5952 ClearCurrentTestPartResults();
5953 EXPECT_FALSE(has_nonfatal_failure);
5954}
5955
5956TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
5957 ADD_FAILURE();
5958 const bool has_nonfatal_failure = HasNonfatalFailure();
5959 ClearCurrentTestPartResults();
5960 EXPECT_TRUE(has_nonfatal_failure);
5961}
5962
5963TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
5964 FailFatally();
5965 ADD_FAILURE();
5966 const bool has_nonfatal_failure = HasNonfatalFailure();
5967 ClearCurrentTestPartResults();
5968 EXPECT_TRUE(has_nonfatal_failure);
5969}
5970
5971// A wrapper for calling HasNonfatalFailure outside of a test body.
5972static bool HasNonfatalFailureHelper() {
5973 return testing::Test::HasNonfatalFailure();
5974}
5975
5976TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
5977 EXPECT_FALSE(HasNonfatalFailureHelper());
5978}
5979
5980TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
5981 ADD_FAILURE();
5982 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
5983 ClearCurrentTestPartResults();
5984 EXPECT_TRUE(has_nonfatal_failure);
5985}
5986
5987TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
5988 EXPECT_FALSE(HasFailure());
5989}
5990
5991TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
5992 FailFatally();
5993 const bool has_failure = HasFailure();
5994 ClearCurrentTestPartResults();
5995 EXPECT_TRUE(has_failure);
5996}
5997
5998TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
5999 ADD_FAILURE();
6000 const bool has_failure = HasFailure();
6001 ClearCurrentTestPartResults();
6002 EXPECT_TRUE(has_failure);
6003}
6004
6005TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6006 FailFatally();
6007 ADD_FAILURE();
6008 const bool has_failure = HasFailure();
6009 ClearCurrentTestPartResults();
6010 EXPECT_TRUE(has_failure);
6011}
6012
6013// A wrapper for calling HasFailure outside of a test body.
6014static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6015
6016TEST(HasFailureTest, WorksOutsideOfTestBody) {
6017 EXPECT_FALSE(HasFailureHelper());
6018}
6019
6020TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6021 ADD_FAILURE();
6022 const bool has_failure = HasFailureHelper();
6023 ClearCurrentTestPartResults();
6024 EXPECT_TRUE(has_failure);
6025}