blob: a593494631b6faac4e6298b1620da7ca6d2d7293 [file] [log] [blame]
shiqian4b6829f2008-07-03 22:38:12 +00001// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google Test itself. This verifies that the basic constructs of
33// Google Test work.
34
35#include <gtest/gtest.h>
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000036
37// Verifies that the command line flag variables can be accessed
38// in code once <gtest/gtest.h> has been #included.
39// Do not move it after other #includes.
40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000049 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000050 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000052 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000053 || testing::GTEST_FLAG(stack_trace_depth) > 0
54 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000055 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
56}
57
shiqian4b6829f2008-07-03 22:38:12 +000058#include <gtest/gtest-spi.h>
59
60// Indicates that this translation unit is part of Google Test's
61// implementation. It must come before gtest-internal-inl.h is
62// included, or there will be a compiler error. This trick is to
63// prevent a user from accidentally including gtest-internal-inl.h in
64// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000065#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000066#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000067#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000068
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +000069#include <limits.h> // For INT_MAX.
shiqian4b6829f2008-07-03 22:38:12 +000070#include <stdlib.h>
zhanyong.wan98efcc42009-04-28 00:28:09 +000071#include <time.h>
shiqian4b6829f2008-07-03 22:38:12 +000072
shiqiane44602e2008-10-11 07:20:02 +000073#if GTEST_HAS_PTHREAD
74#include <pthread.h>
75#endif // GTEST_HAS_PTHREAD
76
zhanyong.wan98efcc42009-04-28 00:28:09 +000077#ifdef __BORLANDC__
78#include <map>
79#endif
80
shiqian4b6829f2008-07-03 22:38:12 +000081namespace testing {
82namespace internal {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000083
zhanyong.wanf6d087b2009-09-30 20:23:50 +000084bool ShouldUseColor(bool stdout_is_tty);
zhanyong.wan65de7e02010-01-08 00:23:45 +000085::std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
shiqian4b6829f2008-07-03 22:38:12 +000086bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000087
vladlosevba015a92009-11-17 22:43:15 +000088// Used for testing the flag parsing.
89extern bool g_help_flag;
90
zhanyong.wanf6d087b2009-09-30 20:23:50 +000091// Provides access to otherwise private parts of the TestEventListeners class
zhanyong.wanf39160b2009-09-04 18:30:25 +000092// that are needed to test it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +000093class TestEventListenersAccessor {
zhanyong.wanf39160b2009-09-04 18:30:25 +000094 public:
zhanyong.wanf6d087b2009-09-30 20:23:50 +000095 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
zhanyong.wanfff03342009-09-24 21:15:59 +000096 return listeners->repeater();
97 }
zhanyong.wanf39160b2009-09-04 18:30:25 +000098
zhanyong.wanf6d087b2009-09-30 20:23:50 +000099 static void SetDefaultResultPrinter(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +0000100 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000101 listeners->SetDefaultResultPrinter(listener);
102 }
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000103 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +0000104 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000105 listeners->SetDefaultXmlGenerator(listener);
106 }
107
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000108 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000109 return listeners.EventForwardingEnabled();
110 }
111
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000112 static void SuppressEventForwarding(TestEventListeners* listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000113 listeners->SuppressEventForwarding();
114 }
115};
116
shiqian4b6829f2008-07-03 22:38:12 +0000117} // namespace internal
118} // namespace testing
119
shiqian760af5c2008-08-06 21:43:15 +0000120using testing::AssertionFailure;
121using testing::AssertionResult;
122using testing::AssertionSuccess;
123using testing::DoubleLE;
zhanyong.wanfff03342009-09-24 21:15:59 +0000124using testing::EmptyTestEventListener;
shiqian760af5c2008-08-06 21:43:15 +0000125using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000126using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000127using testing::GTEST_FLAG(break_on_failure);
128using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000129using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000130using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000131using testing::GTEST_FLAG(filter);
132using testing::GTEST_FLAG(list_tests);
133using testing::GTEST_FLAG(output);
134using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000135using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000136using testing::GTEST_FLAG(repeat);
137using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000138using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000139using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000140using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000141using testing::IsNotSubstring;
142using testing::IsSubstring;
143using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000144using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000145using testing::StaticAssertTypeEq;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000146using testing::Test;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000147using testing::TestEventListeners;
zhanyong.wanfff03342009-09-24 21:15:59 +0000148using testing::TestCase;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000149using testing::TestPartResult;
150using testing::TestPartResultArray;
zhanyong.wanfff03342009-09-24 21:15:59 +0000151using testing::TestProperty;
152using testing::TestResult;
shiqian4b6829f2008-07-03 22:38:12 +0000153using testing::UnitTest;
vladlosevba015a92009-11-17 22:43:15 +0000154using testing::kMaxStackTraceDepth;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000155using testing::internal::AlwaysFalse;
156using testing::internal::AlwaysTrue;
shiqian4b6829f2008-07-03 22:38:12 +0000157using testing::internal::AppendUserMessage;
vladloseve006e682008-08-25 23:11:54 +0000158using testing::internal::CodePointToUtf8;
shiqian4b6829f2008-07-03 22:38:12 +0000159using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000160using testing::internal::FloatingPoint;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000161using testing::internal::FormatTimeInMillisAsSeconds;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000162using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000163using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000164using testing::internal::GetNextRandomSeed;
165using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000166using testing::internal::GetTestTypeId;
167using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000168using testing::internal::GetUnitTestImpl;
shiqian4b6829f2008-07-03 22:38:12 +0000169using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000170using testing::internal::Int32FromEnvOrDie;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000171using testing::internal::ParseInt32Flag;
zhanyong.wan905074c2009-02-09 18:05:21 +0000172using testing::internal::ShouldRunTestOnShard;
173using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000174using testing::internal::ShouldUseColor;
175using testing::internal::StreamableToString;
176using testing::internal::String;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000177using testing::internal::TestEventListenersAccessor;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000178using testing::internal::TestResultAccessor;
shiqiane44602e2008-10-11 07:20:02 +0000179using testing::internal::ThreadLocal;
zhanyong.wan85f555a2009-09-21 19:42:03 +0000180using testing::internal::UInt32;
zhanyong.wana8a582f2009-07-13 19:25:02 +0000181using testing::internal::Vector;
vladloseve006e682008-08-25 23:11:54 +0000182using testing::internal::WideStringToUtf8;
zhanyong.wanfff03342009-09-24 21:15:59 +0000183using testing::internal::kMaxRandomSeed;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000184using testing::internal::kTestTypeIdInGoogleTest;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000185using testing::internal::scoped_ptr;
shiqian4b6829f2008-07-03 22:38:12 +0000186
zhanyong.wancf8a5842010-01-28 21:50:29 +0000187#if GTEST_HAS_STREAM_REDIRECTION_
188using testing::internal::CaptureStdout;
189using testing::internal::GetCapturedStdout;
190#endif // GTEST_HAS_STREAM_REDIRECTION_
191
zhanyong.wanf19450f2009-09-30 23:46:28 +0000192class TestingVector : public Vector<int> {
193};
194
195::std::ostream& operator<<(::std::ostream& os,
196 const TestingVector& vector) {
197 os << "{ ";
198 for (int i = 0; i < vector.size(); i++) {
199 os << vector.GetElement(i) << " ";
200 }
201 os << "}";
202 return os;
203}
204
shiqian4b6829f2008-07-03 22:38:12 +0000205// This line tests that we can define tests in an unnamed namespace.
206namespace {
207
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000208TEST(GetRandomSeedFromFlagTest, HandlesZero) {
209 const int seed = GetRandomSeedFromFlag(0);
210 EXPECT_LE(1, seed);
211 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
212}
213
214TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
215 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
216 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
217 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
218 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
219 GetRandomSeedFromFlag(kMaxRandomSeed));
220}
221
222TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
223 const int seed1 = GetRandomSeedFromFlag(-1);
224 EXPECT_LE(1, seed1);
225 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
226
227 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
228 EXPECT_LE(1, seed2);
229 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
230}
231
232TEST(GetNextRandomSeedTest, WorksForValidInput) {
233 EXPECT_EQ(2, GetNextRandomSeed(1));
234 EXPECT_EQ(3, GetNextRandomSeed(2));
235 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
236 GetNextRandomSeed(kMaxRandomSeed - 1));
237 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
238
239 // We deliberately don't test GetNextRandomSeed() with invalid
240 // inputs, as that requires death tests, which are expensive. This
241 // is fine as GetNextRandomSeed() is internal and has a
242 // straightforward definition.
243}
244
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000245static void ClearCurrentTestPartResults() {
246 TestResultAccessor::ClearTestPartResults(
247 GetUnitTestImpl()->current_test_result());
248}
249
shiqianfe6a9a42008-11-24 20:13:22 +0000250// Tests GetTypeId.
251
252TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
253 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
254 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
255}
256
257class SubClassOfTest : public Test {};
258class AnotherSubClassOfTest : public Test {};
259
260TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
261 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
262 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
263 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
264 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
265 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
266 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
267}
268
269// Verifies that GetTestTypeId() returns the same value, no matter it
270// is called from inside Google Test or outside of it.
271TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
272 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
273}
274
shiqianf0e809a2008-09-26 16:08:30 +0000275// Tests FormatTimeInMillisAsSeconds().
276
277TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000278 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
shiqianf0e809a2008-09-26 16:08:30 +0000279}
280
281TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000282 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
283 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
284 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
285 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
286 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
shiqianf0e809a2008-09-26 16:08:30 +0000287}
288
289TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000290 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
291 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
292 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
293 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
294 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
shiqianf0e809a2008-09-26 16:08:30 +0000295}
296
zhanyong.wan4cd62602009-02-23 23:21:55 +0000297#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +0000298// NULL testing does not work with Symbian compilers.
299
zhanyong.wan98efcc42009-04-28 00:28:09 +0000300#ifdef __BORLANDC__
301// Silences warnings: "Condition is always true", "Unreachable code"
302#pragma option push -w-ccc -w-rch
303#endif
304
shiqiane44602e2008-10-11 07:20:02 +0000305// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000306// pointer literal.
307TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000308 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
309 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000310 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
311 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
312 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000313#ifndef __BORLANDC__
314 // Some compilers may fail to detect some null pointer literals;
315 // as long as users of the framework don't use such literals, this
316 // is harmless.
317 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
shiqiane44602e2008-10-11 07:20:02 +0000318 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000319#endif
shiqian4b6829f2008-07-03 22:38:12 +0000320}
321
shiqiane44602e2008-10-11 07:20:02 +0000322// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
shiqian4b6829f2008-07-03 22:38:12 +0000323// pointer literal.
324TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000325 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
326 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
327 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
328 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
shiqian4b6829f2008-07-03 22:38:12 +0000329}
330
zhanyong.wan98efcc42009-04-28 00:28:09 +0000331#ifdef __BORLANDC__
332// Restores warnings after previous "#pragma option push" supressed them
333#pragma option pop
334#endif
335
zhanyong.wan4cd62602009-02-23 23:21:55 +0000336#endif // !GTEST_OS_SYMBIAN
vladloseve006e682008-08-25 23:11:54 +0000337//
338// Tests CodePointToUtf8().
shiqian4b6829f2008-07-03 22:38:12 +0000339
340// Tests that the NUL character L'\0' is encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000341TEST(CodePointToUtf8Test, CanEncodeNul) {
342 char buffer[32];
343 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000344}
345
346// Tests that ASCII characters are encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000347TEST(CodePointToUtf8Test, CanEncodeAscii) {
348 char buffer[32];
349 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
350 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
351 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
352 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000353}
354
355// Tests that Unicode code-points that have 8 to 11 bits are encoded
356// as 110xxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000357TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
358 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000359 // 000 1101 0011 => 110-00011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000360 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000361
362 // 101 0111 0110 => 110-10101 10-110110
vladloseve006e682008-08-25 23:11:54 +0000363 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000364}
365
366// Tests that Unicode code-points that have 12 to 16 bits are encoded
367// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000368TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
369 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000370 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000371 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000372
373 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
vladloseve006e682008-08-25 23:11:54 +0000374 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000375}
376
zhanyong.wan4cd62602009-02-23 23:21:55 +0000377#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000378// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000379// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000380// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000381
382// Tests that Unicode code-points that have 17 to 21 bits are encoded
383// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000384TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
385 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000386 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000387 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000388
vladloseve006e682008-08-25 23:11:54 +0000389 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
390 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
391
392 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
393 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000394}
395
396// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000397TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
398 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000399 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
vladloseve006e682008-08-25 23:11:54 +0000400 CodePointToUtf8(L'\x1234ABCD', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000401}
402
zhanyong.wan4cd62602009-02-23 23:21:55 +0000403#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000404
405// Tests WideStringToUtf8().
406
407// Tests that the NUL character L'\0' is encoded correctly.
408TEST(WideStringToUtf8Test, CanEncodeNul) {
409 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
410 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
411}
412
413// Tests that ASCII strings are encoded correctly.
414TEST(WideStringToUtf8Test, CanEncodeAscii) {
415 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
416 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
417 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
418 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
419}
420
421// Tests that Unicode code-points that have 8 to 11 bits are encoded
422// as 110xxxxx 10xxxxxx.
423TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
424 // 000 1101 0011 => 110-00011 10-010011
425 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
426 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
427
428 // 101 0111 0110 => 110-10101 10-110110
429 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
430 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
431}
432
433// Tests that Unicode code-points that have 12 to 16 bits are encoded
434// as 1110xxxx 10xxxxxx 10xxxxxx.
435TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
436 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
437 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
438 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
439
440 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
441 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
442 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
443}
444
445// Tests that the conversion stops when the function encounters \0 character.
446TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
447 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
448}
449
450// Tests that the conversion stops when the function reaches the limit
451// specified by the 'length' parameter.
452TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
453 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
454}
455
456
zhanyong.wan4cd62602009-02-23 23:21:55 +0000457#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000458// Tests that Unicode code-points that have 17 to 21 bits are encoded
459// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
460// on the systems using UTF-16 encoding.
461TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
462 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
463 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
464 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
465
466 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
467 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
468 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
469}
470
471// Tests that encoding an invalid code-point generates the expected result.
472TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
473 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
474 WideStringToUtf8(L"\xABCDFF", -1).c_str());
475}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000476#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000477// Tests that surrogate pairs are encoded correctly on the systems using
478// UTF-16 encoding in the wide strings.
479TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
480 EXPECT_STREQ("\xF0\x90\x90\x80",
481 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
482}
483
484// Tests that encoding an invalid UTF-16 surrogate pair
485// generates the expected result.
486TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
487 // Leading surrogate is at the end of the string.
488 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
489 // Leading surrogate is not followed by the trailing surrogate.
490 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
491 // Trailing surrogate appearas without a leading surrogate.
492 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
493}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000494#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000495
496// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000497#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000498TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
499 EXPECT_STREQ(
500 "\xF4\x88\x98\xB4"
501 "\xEC\x9D\x8D"
502 "\n"
503 "\xD5\xB6"
504 "\xE0\xA3\x93"
505 "\xF4\x88\x98\xB4",
506 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
507}
508#else
509TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
510 EXPECT_STREQ(
511 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
512 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
513}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000514#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000515
zhanyong.wan85f555a2009-09-21 19:42:03 +0000516// Tests the Random class.
517
518TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
519 testing::internal::Random random(42);
520 EXPECT_DEATH_IF_SUPPORTED(
521 random.Generate(0),
522 "Cannot generate a number in the range \\[0, 0\\)");
523 EXPECT_DEATH_IF_SUPPORTED(
524 random.Generate(testing::internal::Random::kMaxRange + 1),
525 "Generation of a number in \\[0, 2147483649\\) was requested, "
526 "but this can only generate numbers in \\[0, 2147483648\\)");
527}
528
529TEST(RandomTest, GeneratesNumbersWithinRange) {
530 const UInt32 kRange = 10000;
531 testing::internal::Random random(12345);
532 for (int i = 0; i < 10; i++) {
533 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
534 }
535
536 testing::internal::Random random2(testing::internal::Random::kMaxRange);
537 for (int i = 0; i < 10; i++) {
538 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
539 }
540}
541
542TEST(RandomTest, RepeatsWhenReseeded) {
543 const int kSeed = 123;
544 const int kArraySize = 10;
545 const UInt32 kRange = 10000;
546 UInt32 values[kArraySize];
547
548 testing::internal::Random random(kSeed);
549 for (int i = 0; i < kArraySize; i++) {
550 values[i] = random.Generate(kRange);
551 }
552
553 random.Reseed(kSeed);
554 for (int i = 0; i < kArraySize; i++) {
555 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
556 }
557}
558
zhanyong.wana8a582f2009-07-13 19:25:02 +0000559// Tests the Vector class template.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000560
zhanyong.wana8a582f2009-07-13 19:25:02 +0000561// Tests Vector::Clear().
562TEST(VectorTest, Clear) {
563 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000564 a.PushBack(1);
565 a.Clear();
566 EXPECT_EQ(0, a.size());
567
568 a.PushBack(2);
569 a.PushBack(3);
570 a.Clear();
571 EXPECT_EQ(0, a.size());
572}
573
zhanyong.wana8a582f2009-07-13 19:25:02 +0000574// Tests Vector::PushBack().
575TEST(VectorTest, PushBack) {
576 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000577 a.PushBack('a');
578 ASSERT_EQ(1, a.size());
579 EXPECT_EQ('a', a.GetElement(0));
580
581 a.PushBack('b');
582 ASSERT_EQ(2, a.size());
583 EXPECT_EQ('a', a.GetElement(0));
584 EXPECT_EQ('b', a.GetElement(1));
585}
shiqian4b6829f2008-07-03 22:38:12 +0000586
zhanyong.wana8a582f2009-07-13 19:25:02 +0000587// Tests Vector::PushFront().
588TEST(VectorTest, PushFront) {
589 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000590 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000591
zhanyong.wana8a582f2009-07-13 19:25:02 +0000592 // Calls PushFront() on an empty Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000593 a.PushFront(1);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000594 ASSERT_EQ(1, a.size());
595 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000596
zhanyong.wana8a582f2009-07-13 19:25:02 +0000597 // Calls PushFront() on a singleton Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000598 a.PushFront(2);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000599 ASSERT_EQ(2, a.size());
600 EXPECT_EQ(2, a.GetElement(0));
601 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000602
zhanyong.wana8a582f2009-07-13 19:25:02 +0000603 // Calls PushFront() on a Vector with more than one elements.
shiqian4b6829f2008-07-03 22:38:12 +0000604 a.PushFront(3);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000605 ASSERT_EQ(3, a.size());
606 EXPECT_EQ(3, a.GetElement(0));
607 EXPECT_EQ(2, a.GetElement(1));
608 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000609}
610
zhanyong.wana8a582f2009-07-13 19:25:02 +0000611// Tests Vector::PopFront().
612TEST(VectorTest, PopFront) {
613 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000614
zhanyong.wana8a582f2009-07-13 19:25:02 +0000615 // Popping on an empty Vector should fail.
shiqian4b6829f2008-07-03 22:38:12 +0000616 EXPECT_FALSE(a.PopFront(NULL));
617
zhanyong.wana8a582f2009-07-13 19:25:02 +0000618 // Popping again on an empty Vector should fail, and the result element
shiqian4b6829f2008-07-03 22:38:12 +0000619 // shouldn't be overwritten.
620 int element = 1;
621 EXPECT_FALSE(a.PopFront(&element));
622 EXPECT_EQ(1, element);
623
624 a.PushFront(2);
625 a.PushFront(3);
626
zhanyong.wana8a582f2009-07-13 19:25:02 +0000627 // PopFront() should pop the element in the front of the Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000628 EXPECT_TRUE(a.PopFront(&element));
629 EXPECT_EQ(3, element);
630
zhanyong.wana8a582f2009-07-13 19:25:02 +0000631 // After popping the last element, the Vector should be empty.
shiqian4b6829f2008-07-03 22:38:12 +0000632 EXPECT_TRUE(a.PopFront(NULL));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000633 EXPECT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000634}
635
zhanyong.wana8a582f2009-07-13 19:25:02 +0000636// Tests inserting at the beginning using Vector::Insert().
637TEST(VectorTest, InsertAtBeginning) {
638 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000639 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000640
zhanyong.wana8a582f2009-07-13 19:25:02 +0000641 // Inserts into an empty Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000642 a.Insert(1, 0);
643 ASSERT_EQ(1, a.size());
644 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000645
zhanyong.wana8a582f2009-07-13 19:25:02 +0000646 // Inserts at the beginning of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000647 a.Insert(2, 0);
648 ASSERT_EQ(2, a.size());
649 EXPECT_EQ(2, a.GetElement(0));
650 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000651
zhanyong.wana8a582f2009-07-13 19:25:02 +0000652 // Inserts at the beginning of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000653 a.Insert(3, 0);
654 ASSERT_EQ(3, a.size());
655 EXPECT_EQ(3, a.GetElement(0));
656 EXPECT_EQ(2, a.GetElement(1));
657 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000658}
659
660// Tests inserting at a location other than the beginning using
zhanyong.wana8a582f2009-07-13 19:25:02 +0000661// Vector::Insert().
662TEST(VectorTest, InsertNotAtBeginning) {
663 // Prepares a singleton Vector.
664 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000665 a.PushBack(1);
666
zhanyong.wana8a582f2009-07-13 19:25:02 +0000667 // Inserts at the end of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000668 a.Insert(2, a.size());
669 ASSERT_EQ(2, a.size());
670 EXPECT_EQ(1, a.GetElement(0));
671 EXPECT_EQ(2, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000672
zhanyong.wana8a582f2009-07-13 19:25:02 +0000673 // Inserts at the end of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000674 a.Insert(3, a.size());
675 ASSERT_EQ(3, a.size());
676 EXPECT_EQ(1, a.GetElement(0));
677 EXPECT_EQ(2, a.GetElement(1));
678 EXPECT_EQ(3, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000679
zhanyong.wana8a582f2009-07-13 19:25:02 +0000680 // Inserts in the middle of a Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000681 a.Insert(4, 1);
682 ASSERT_EQ(4, a.size());
683 EXPECT_EQ(1, a.GetElement(0));
684 EXPECT_EQ(4, a.GetElement(1));
685 EXPECT_EQ(2, a.GetElement(2));
686 EXPECT_EQ(3, a.GetElement(3));
687}
688
zhanyong.wana8a582f2009-07-13 19:25:02 +0000689// Tests Vector::GetElementOr().
690TEST(VectorTest, GetElementOr) {
691 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000692 EXPECT_EQ('x', a.GetElementOr(0, 'x'));
693
694 a.PushBack('a');
695 a.PushBack('b');
696 EXPECT_EQ('a', a.GetElementOr(0, 'x'));
697 EXPECT_EQ('b', a.GetElementOr(1, 'x'));
698 EXPECT_EQ('x', a.GetElementOr(-2, 'x'));
699 EXPECT_EQ('x', a.GetElementOr(2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000700}
701
zhanyong.wanf19450f2009-09-30 23:46:28 +0000702TEST(VectorTest, Swap) {
703 Vector<int> a;
704 a.PushBack(0);
705 a.PushBack(1);
706 a.PushBack(2);
707
708 // Swaps an element with itself.
709 a.Swap(0, 0);
710 ASSERT_EQ(0, a.GetElement(0));
711 ASSERT_EQ(1, a.GetElement(1));
712 ASSERT_EQ(2, a.GetElement(2));
713
714 // Swaps two different elements where the indices go up.
715 a.Swap(0, 1);
716 ASSERT_EQ(1, a.GetElement(0));
717 ASSERT_EQ(0, a.GetElement(1));
718 ASSERT_EQ(2, a.GetElement(2));
719
720 // Swaps two different elements where the indices go down.
721 a.Swap(2, 0);
722 ASSERT_EQ(2, a.GetElement(0));
723 ASSERT_EQ(0, a.GetElement(1));
724 ASSERT_EQ(1, a.GetElement(2));
725}
726
727TEST(VectorTest, Clone) {
728 // Clones an empty Vector.
729 Vector<int> a;
730 scoped_ptr<Vector<int> > empty(a.Clone());
731 EXPECT_EQ(0, empty->size());
732
733 // Clones a singleton.
734 a.PushBack(42);
735 scoped_ptr<Vector<int> > singleton(a.Clone());
736 ASSERT_EQ(1, singleton->size());
737 EXPECT_EQ(42, singleton->GetElement(0));
738
739 // Clones a Vector with more elements.
740 a.PushBack(43);
741 a.PushBack(44);
742 scoped_ptr<Vector<int> > big(a.Clone());
743 ASSERT_EQ(3, big->size());
744 EXPECT_EQ(42, big->GetElement(0));
745 EXPECT_EQ(43, big->GetElement(1));
746 EXPECT_EQ(44, big->GetElement(2));
747}
748
zhanyong.wana8a582f2009-07-13 19:25:02 +0000749// Tests Vector::Erase().
750TEST(VectorDeathTest, Erase) {
751 Vector<int> a;
752
753 // Tests erasing from an empty vector.
zhanyong.wan535de532009-08-07 06:47:47 +0000754 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000755 a.Erase(0),
756 "Invalid Vector index 0: must be in range \\[0, -1\\]\\.");
757
758 // Tests erasing from a singleton vector.
759 a.PushBack(0);
760
761 a.Erase(0);
762 EXPECT_EQ(0, a.size());
763
764 // Tests Erase parameters beyond the bounds of the vector.
765 Vector<int> a1;
766 a1.PushBack(0);
767 a1.PushBack(1);
768 a1.PushBack(2);
769
zhanyong.wan535de532009-08-07 06:47:47 +0000770 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000771 a1.Erase(3),
772 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +0000773 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wana8a582f2009-07-13 19:25:02 +0000774 a1.Erase(-1),
775 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
776
777 // Tests erasing at the end of the vector.
778 Vector<int> a2;
779 a2.PushBack(0);
780 a2.PushBack(1);
781 a2.PushBack(2);
782
783 a2.Erase(2);
784 ASSERT_EQ(2, a2.size());
785 EXPECT_EQ(0, a2.GetElement(0));
786 EXPECT_EQ(1, a2.GetElement(1));
787
788 // Tests erasing in the middle of the vector.
789 Vector<int> a3;
790 a3.PushBack(0);
791 a3.PushBack(1);
792 a3.PushBack(2);
793
794 a3.Erase(1);
795 ASSERT_EQ(2, a3.size());
796 EXPECT_EQ(0, a3.GetElement(0));
797 EXPECT_EQ(2, a3.GetElement(1));
798
799 // Tests erasing at the beginning of the vector.
800 Vector<int> a4;
801 a4.PushBack(0);
802 a4.PushBack(1);
803 a4.PushBack(2);
804
805 a4.Erase(0);
806 ASSERT_EQ(2, a4.size());
807 EXPECT_EQ(1, a4.GetElement(0));
808 EXPECT_EQ(2, a4.GetElement(1));
809}
810
zhanyong.wan9644db82009-06-24 23:02:50 +0000811// Tests the GetElement accessor.
zhanyong.wanf19450f2009-09-30 23:46:28 +0000812TEST(VectorDeathTest, GetElement) {
813 Vector<int> a;
814 a.PushBack(0);
815 a.PushBack(1);
816 a.PushBack(2);
817 const Vector<int>& b = a;
818
819 EXPECT_EQ(0, b.GetElement(0));
820 EXPECT_EQ(1, b.GetElement(1));
821 EXPECT_EQ(2, b.GetElement(2));
822 EXPECT_DEATH_IF_SUPPORTED(
823 b.GetElement(3),
824 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
825 EXPECT_DEATH_IF_SUPPORTED(
826 b.GetElement(-1),
827 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
828}
829
830// Tests the GetMutableElement accessor.
831TEST(VectorDeathTest, GetMutableElement) {
zhanyong.wana8a582f2009-07-13 19:25:02 +0000832 Vector<int> a;
zhanyong.wan9644db82009-06-24 23:02:50 +0000833 a.PushBack(0);
834 a.PushBack(1);
835 a.PushBack(2);
836
zhanyong.wanf19450f2009-09-30 23:46:28 +0000837 EXPECT_EQ(0, a.GetMutableElement(0));
838 EXPECT_EQ(1, a.GetMutableElement(1));
839 EXPECT_EQ(2, a.GetMutableElement(2));
840
841 a.GetMutableElement(0) = 42;
842 EXPECT_EQ(42, a.GetMutableElement(0));
843 EXPECT_EQ(1, a.GetMutableElement(1));
844 EXPECT_EQ(2, a.GetMutableElement(2));
845
zhanyong.wan535de532009-08-07 06:47:47 +0000846 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wanf19450f2009-09-30 23:46:28 +0000847 a.GetMutableElement(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000848 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +0000849 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wanf19450f2009-09-30 23:46:28 +0000850 a.GetMutableElement(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000851 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +0000852}
shiqian4b6829f2008-07-03 22:38:12 +0000853
zhanyong.wanf19450f2009-09-30 23:46:28 +0000854TEST(VectorDeathTest, Swap) {
855 Vector<int> a;
856 a.PushBack(0);
857 a.PushBack(1);
858 a.PushBack(2);
859
860 EXPECT_DEATH_IF_SUPPORTED(
861 a.Swap(-1, 1),
862 "Invalid first swap element -1: must be in range \\[0, 2\\]");
863 EXPECT_DEATH_IF_SUPPORTED(
864 a.Swap(3, 1),
865 "Invalid first swap element 3: must be in range \\[0, 2\\]");
866 EXPECT_DEATH_IF_SUPPORTED(
867 a.Swap(1, -1),
868 "Invalid second swap element -1: must be in range \\[0, 2\\]");
869 EXPECT_DEATH_IF_SUPPORTED(
870 a.Swap(1, 3),
871 "Invalid second swap element 3: must be in range \\[0, 2\\]");
872}
873
874TEST(VectorDeathTest, ShuffleRange) {
875 Vector<int> a;
876 a.PushBack(0);
877 a.PushBack(1);
878 a.PushBack(2);
879 testing::internal::Random random(1);
880
881 EXPECT_DEATH_IF_SUPPORTED(
882 a.ShuffleRange(&random, -1, 1),
883 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
884 EXPECT_DEATH_IF_SUPPORTED(
885 a.ShuffleRange(&random, 4, 4),
886 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
887 EXPECT_DEATH_IF_SUPPORTED(
888 a.ShuffleRange(&random, 3, 2),
889 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
890 EXPECT_DEATH_IF_SUPPORTED(
891 a.ShuffleRange(&random, 3, 4),
892 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
893}
894
895class VectorShuffleTest : public Test {
896 protected:
897 static const int kVectorSize = 20;
898
899 VectorShuffleTest() : random_(1) {
900 for (int i = 0; i < kVectorSize; i++) {
901 vector_.PushBack(i);
902 }
903 }
904
905 static bool VectorIsCorrupt(const TestingVector& vector) {
906 if (kVectorSize != vector.size()) {
907 return true;
908 }
909
910 bool found_in_vector[kVectorSize] = { false };
911 for (int i = 0; i < vector.size(); i++) {
912 const int e = vector.GetElement(i);
913 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
914 return true;
915 }
916 found_in_vector[e] = true;
917 }
918
919 // Vector size is correct, elements' range is correct, no
920 // duplicate elements. Therefore no corruption has occurred.
921 return false;
922 }
923
924 static bool VectorIsNotCorrupt(const TestingVector& vector) {
925 return !VectorIsCorrupt(vector);
926 }
927
928 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
929 for (int i = begin; i < end; i++) {
930 if (i != vector.GetElement(i)) {
931 return true;
932 }
933 }
934 return false;
935 }
936
937 static bool RangeIsUnshuffled(
938 const TestingVector& vector, int begin, int end) {
939 return !RangeIsShuffled(vector, begin, end);
940 }
941
942 static bool VectorIsShuffled(const TestingVector& vector) {
943 return RangeIsShuffled(vector, 0, vector.size());
944 }
945
946 static bool VectorIsUnshuffled(const TestingVector& vector) {
947 return !VectorIsShuffled(vector);
948 }
949
950 testing::internal::Random random_;
951 TestingVector vector_;
952}; // class VectorShuffleTest
953
954const int VectorShuffleTest::kVectorSize;
955
956TEST_F(VectorShuffleTest, HandlesEmptyRange) {
957 // Tests an empty range at the beginning...
958 vector_.ShuffleRange(&random_, 0, 0);
959 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
960 ASSERT_PRED1(VectorIsUnshuffled, vector_);
961
962 // ...in the middle...
963 vector_.ShuffleRange(&random_, kVectorSize/2, kVectorSize/2);
964 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
965 ASSERT_PRED1(VectorIsUnshuffled, vector_);
966
967 // ...at the end...
968 vector_.ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1);
969 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
970 ASSERT_PRED1(VectorIsUnshuffled, vector_);
971
972 // ...and past the end.
973 vector_.ShuffleRange(&random_, kVectorSize, kVectorSize);
974 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
975 ASSERT_PRED1(VectorIsUnshuffled, vector_);
976}
977
978TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
979 // Tests a size one range at the beginning...
980 vector_.ShuffleRange(&random_, 0, 1);
981 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
982 ASSERT_PRED1(VectorIsUnshuffled, vector_);
983
984 // ...in the middle...
985 vector_.ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1);
986 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
987 ASSERT_PRED1(VectorIsUnshuffled, vector_);
988
989 // ...and at the end.
990 vector_.ShuffleRange(&random_, kVectorSize - 1, kVectorSize);
991 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
992 ASSERT_PRED1(VectorIsUnshuffled, vector_);
993}
994
995// Because we use our own random number generator and a fixed seed,
996// we can guarantee that the following "random" tests will succeed.
997
998TEST_F(VectorShuffleTest, ShufflesEntireVector) {
999 vector_.Shuffle(&random_);
1000 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1001 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
1002
1003 // Tests the first and last elements in particular to ensure that
1004 // there are no off-by-one problems in our shuffle algorithm.
1005 EXPECT_NE(0, vector_.GetElement(0));
1006 EXPECT_NE(kVectorSize - 1, vector_.GetElement(kVectorSize - 1));
1007}
1008
1009TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
1010 const int kRangeSize = kVectorSize/2;
1011
1012 vector_.ShuffleRange(&random_, 0, kRangeSize);
1013
1014 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1015 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1016 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
1017}
1018
1019TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1020 const int kRangeSize = kVectorSize / 2;
1021 vector_.ShuffleRange(&random_, kRangeSize, kVectorSize);
1022
1023 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1024 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1025 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
1026}
1027
1028TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1029 int kRangeSize = kVectorSize/3;
1030 vector_.ShuffleRange(&random_, kRangeSize, 2*kRangeSize);
1031
1032 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1033 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1034 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
1035 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
1036}
1037
1038TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1039 TestingVector vector2;
1040 for (int i = 0; i < kVectorSize; i++) {
1041 vector2.PushBack(i);
1042 }
1043
1044 random_.Reseed(1234);
1045 vector_.Shuffle(&random_);
1046 random_.Reseed(1234);
1047 vector2.Shuffle(&random_);
1048
1049 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1050 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1051
1052 for (int i = 0; i < kVectorSize; i++) {
1053 EXPECT_EQ(vector_.GetElement(i), vector2.GetElement(i))
1054 << " where i is " << i;
1055 }
1056}
1057
zhanyong.wanf39160b2009-09-04 18:30:25 +00001058// Tests the size of the AssertHelper class.
shiqian4b6829f2008-07-03 22:38:12 +00001059
zhanyong.wanf39160b2009-09-04 18:30:25 +00001060TEST(AssertHelperTest, AssertHelperIsSmall) {
zhanyong.wan89be5762009-09-01 18:53:56 +00001061 // To avoid breaking clients that use lots of assertions in one
zhanyong.wanf39160b2009-09-04 18:30:25 +00001062 // function, we cannot grow the size of AssertHelper.
1063 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
zhanyong.wan89be5762009-09-01 18:53:56 +00001064}
1065
zhanyong.wanf39160b2009-09-04 18:30:25 +00001066// Tests the String class.
1067
shiqian4b6829f2008-07-03 22:38:12 +00001068// Tests String's constructors.
1069TEST(StringTest, Constructors) {
1070 // Default ctor.
1071 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +00001072 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
1073 // pointers with NULL isn't supported on all platforms.
zhanyong.wan89be5762009-09-01 18:53:56 +00001074 EXPECT_EQ(0U, s1.length());
shiqiandd4a17b2008-07-31 18:34:08 +00001075 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001076
1077 // Implicitly constructs from a C-string.
1078 String s2 = "Hi";
zhanyong.wan89be5762009-09-01 18:53:56 +00001079 EXPECT_EQ(2U, s2.length());
shiqian4b6829f2008-07-03 22:38:12 +00001080 EXPECT_STREQ("Hi", s2.c_str());
1081
1082 // Constructs from a C-string and a length.
1083 String s3("hello", 3);
zhanyong.wan89be5762009-09-01 18:53:56 +00001084 EXPECT_EQ(3U, s3.length());
shiqian4b6829f2008-07-03 22:38:12 +00001085 EXPECT_STREQ("hel", s3.c_str());
1086
zhanyong.wan89be5762009-09-01 18:53:56 +00001087 // The empty String should be created when String is constructed with
1088 // a NULL pointer and length 0.
1089 EXPECT_EQ(0U, String(NULL, 0).length());
1090 EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
1091
1092 // Constructs a String that contains '\0'.
1093 String s4("a\0bcd", 4);
1094 EXPECT_EQ(4U, s4.length());
1095 EXPECT_EQ('a', s4.c_str()[0]);
1096 EXPECT_EQ('\0', s4.c_str()[1]);
1097 EXPECT_EQ('b', s4.c_str()[2]);
1098 EXPECT_EQ('c', s4.c_str()[3]);
1099
1100 // Copy ctor where the source is NULL.
1101 const String null_str;
1102 String s5 = null_str;
1103 EXPECT_TRUE(s5.c_str() == NULL);
1104
1105 // Copy ctor where the source isn't NULL.
1106 String s6 = s3;
1107 EXPECT_EQ(3U, s6.length());
1108 EXPECT_STREQ("hel", s6.c_str());
1109
1110 // Copy ctor where the source contains '\0'.
1111 String s7 = s4;
1112 EXPECT_EQ(4U, s7.length());
1113 EXPECT_EQ('a', s7.c_str()[0]);
1114 EXPECT_EQ('\0', s7.c_str()[1]);
1115 EXPECT_EQ('b', s7.c_str()[2]);
1116 EXPECT_EQ('c', s7.c_str()[3]);
shiqian4b6829f2008-07-03 22:38:12 +00001117}
1118
vladlosevf179f4e2008-11-26 20:48:45 +00001119TEST(StringTest, ConvertsFromStdString) {
1120 // An empty std::string.
1121 const std::string src1("");
1122 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +00001123 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +00001124 EXPECT_STREQ("", dest1.c_str());
1125
1126 // A normal std::string.
1127 const std::string src2("Hi");
1128 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +00001129 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +00001130 EXPECT_STREQ("Hi", dest2.c_str());
1131
1132 // An std::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +00001133 const char src3[] = "a\0b";
vladlosevf179f4e2008-11-26 20:48:45 +00001134 const String dest3 = std::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +00001135 EXPECT_EQ(sizeof(src3), dest3.length());
1136 EXPECT_EQ('a', dest3.c_str()[0]);
1137 EXPECT_EQ('\0', dest3.c_str()[1]);
1138 EXPECT_EQ('b', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +00001139}
1140
1141TEST(StringTest, ConvertsToStdString) {
1142 // An empty String.
1143 const String src1("");
1144 const std::string dest1 = src1;
1145 EXPECT_EQ("", dest1);
1146
1147 // A normal String.
1148 const String src2("Hi");
1149 const std::string dest2 = src2;
1150 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +00001151
1152 // A String containing a '\0'.
1153 const String src3("x\0y", 3);
1154 const std::string dest3 = src3;
1155 EXPECT_EQ(std::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +00001156}
1157
vladlosevf179f4e2008-11-26 20:48:45 +00001158#if GTEST_HAS_GLOBAL_STRING
1159
1160TEST(StringTest, ConvertsFromGlobalString) {
1161 // An empty ::string.
1162 const ::string src1("");
1163 const String dest1 = src1;
zhanyong.wan89be5762009-09-01 18:53:56 +00001164 EXPECT_EQ(0U, dest1.length());
vladlosevf179f4e2008-11-26 20:48:45 +00001165 EXPECT_STREQ("", dest1.c_str());
1166
1167 // A normal ::string.
1168 const ::string src2("Hi");
1169 const String dest2 = src2;
zhanyong.wan89be5762009-09-01 18:53:56 +00001170 EXPECT_EQ(2U, dest2.length());
vladlosevf179f4e2008-11-26 20:48:45 +00001171 EXPECT_STREQ("Hi", dest2.c_str());
1172
1173 // An ::string with an embedded NUL character.
zhanyong.wan89be5762009-09-01 18:53:56 +00001174 const char src3[] = "x\0y";
vladlosevf179f4e2008-11-26 20:48:45 +00001175 const String dest3 = ::string(src3, sizeof(src3));
zhanyong.wan89be5762009-09-01 18:53:56 +00001176 EXPECT_EQ(sizeof(src3), dest3.length());
1177 EXPECT_EQ('x', dest3.c_str()[0]);
1178 EXPECT_EQ('\0', dest3.c_str()[1]);
1179 EXPECT_EQ('y', dest3.c_str()[2]);
vladlosevf179f4e2008-11-26 20:48:45 +00001180}
1181
1182TEST(StringTest, ConvertsToGlobalString) {
1183 // An empty String.
1184 const String src1("");
1185 const ::string dest1 = src1;
1186 EXPECT_EQ("", dest1);
1187
1188 // A normal String.
1189 const String src2("Hi");
1190 const ::string dest2 = src2;
1191 EXPECT_EQ("Hi", dest2);
zhanyong.wan89be5762009-09-01 18:53:56 +00001192
1193 const String src3("x\0y", 3);
1194 const ::string dest3 = src3;
1195 EXPECT_EQ(::string("x\0y", 3), dest3);
vladlosevf179f4e2008-11-26 20:48:45 +00001196}
1197
1198#endif // GTEST_HAS_GLOBAL_STRING
1199
shiqian4b6829f2008-07-03 22:38:12 +00001200// Tests String::ShowCStringQuoted().
1201TEST(StringTest, ShowCStringQuoted) {
1202 EXPECT_STREQ("(null)",
1203 String::ShowCStringQuoted(NULL).c_str());
1204 EXPECT_STREQ("\"\"",
1205 String::ShowCStringQuoted("").c_str());
1206 EXPECT_STREQ("\"foo\"",
1207 String::ShowCStringQuoted("foo").c_str());
1208}
1209
zhanyong.wan89be5762009-09-01 18:53:56 +00001210// Tests String::empty().
1211TEST(StringTest, Empty) {
1212 EXPECT_TRUE(String("").empty());
1213 EXPECT_FALSE(String().empty());
1214 EXPECT_FALSE(String(NULL).empty());
1215 EXPECT_FALSE(String("a").empty());
1216 EXPECT_FALSE(String("\0", 1).empty());
1217}
1218
1219// Tests String::Compare().
1220TEST(StringTest, Compare) {
1221 // NULL vs NULL.
1222 EXPECT_EQ(0, String().Compare(String()));
1223
1224 // NULL vs non-NULL.
1225 EXPECT_EQ(-1, String().Compare(String("")));
1226
1227 // Non-NULL vs NULL.
1228 EXPECT_EQ(1, String("").Compare(String()));
1229
1230 // The following covers non-NULL vs non-NULL.
1231
1232 // "" vs "".
1233 EXPECT_EQ(0, String("").Compare(String("")));
1234
1235 // "" vs non-"".
1236 EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
1237 EXPECT_EQ(-1, String("").Compare(" "));
1238
1239 // Non-"" vs "".
1240 EXPECT_EQ(1, String("a").Compare(String("")));
1241
1242 // The following covers non-"" vs non-"".
1243
1244 // Same length and equal.
1245 EXPECT_EQ(0, String("a").Compare(String("a")));
1246
1247 // Same length and different.
1248 EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
1249 EXPECT_EQ(1, String("b").Compare(String("a")));
1250
1251 // Different lengths.
1252 EXPECT_EQ(-1, String("a").Compare(String("ab")));
1253 EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
1254 EXPECT_EQ(1, String("abc").Compare(String("aacd")));
1255}
1256
shiqian4b6829f2008-07-03 22:38:12 +00001257// Tests String::operator==().
1258TEST(StringTest, Equals) {
1259 const String null(NULL);
1260 EXPECT_TRUE(null == NULL); // NOLINT
1261 EXPECT_FALSE(null == ""); // NOLINT
1262 EXPECT_FALSE(null == "bar"); // NOLINT
1263
1264 const String empty("");
1265 EXPECT_FALSE(empty == NULL); // NOLINT
1266 EXPECT_TRUE(empty == ""); // NOLINT
1267 EXPECT_FALSE(empty == "bar"); // NOLINT
1268
1269 const String foo("foo");
1270 EXPECT_FALSE(foo == NULL); // NOLINT
1271 EXPECT_FALSE(foo == ""); // NOLINT
1272 EXPECT_FALSE(foo == "bar"); // NOLINT
1273 EXPECT_TRUE(foo == "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001274
1275 const String bar("x\0y", 3);
1276 EXPECT_FALSE(bar == "x");
shiqian4b6829f2008-07-03 22:38:12 +00001277}
1278
1279// Tests String::operator!=().
1280TEST(StringTest, NotEquals) {
1281 const String null(NULL);
1282 EXPECT_FALSE(null != NULL); // NOLINT
1283 EXPECT_TRUE(null != ""); // NOLINT
1284 EXPECT_TRUE(null != "bar"); // NOLINT
1285
1286 const String empty("");
1287 EXPECT_TRUE(empty != NULL); // NOLINT
1288 EXPECT_FALSE(empty != ""); // NOLINT
1289 EXPECT_TRUE(empty != "bar"); // NOLINT
1290
1291 const String foo("foo");
1292 EXPECT_TRUE(foo != NULL); // NOLINT
1293 EXPECT_TRUE(foo != ""); // NOLINT
1294 EXPECT_TRUE(foo != "bar"); // NOLINT
1295 EXPECT_FALSE(foo != "foo"); // NOLINT
zhanyong.wan89be5762009-09-01 18:53:56 +00001296
1297 const String bar("x\0y", 3);
1298 EXPECT_TRUE(bar != "x");
1299}
1300
1301// Tests String::length().
1302TEST(StringTest, Length) {
1303 EXPECT_EQ(0U, String().length());
1304 EXPECT_EQ(0U, String("").length());
1305 EXPECT_EQ(2U, String("ab").length());
1306 EXPECT_EQ(3U, String("a\0b", 3).length());
shiqian4b6829f2008-07-03 22:38:12 +00001307}
1308
1309// Tests String::EndsWith().
1310TEST(StringTest, EndsWith) {
1311 EXPECT_TRUE(String("foobar").EndsWith("bar"));
1312 EXPECT_TRUE(String("foobar").EndsWith(""));
1313 EXPECT_TRUE(String("").EndsWith(""));
1314
1315 EXPECT_FALSE(String("foobar").EndsWith("foo"));
1316 EXPECT_FALSE(String("").EndsWith("foo"));
1317}
1318
1319// Tests String::EndsWithCaseInsensitive().
1320TEST(StringTest, EndsWithCaseInsensitive) {
1321 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
1322 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
1323 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
1324 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
1325
1326 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
1327 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
1328 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
1329}
1330
zhanyong.wan98efcc42009-04-28 00:28:09 +00001331// C++Builder's preprocessor is buggy; it fails to expand macros that
1332// appear in macro parameters after wide char literals. Provide an alias
1333// for NULL as a workaround.
1334static const wchar_t* const kNull = NULL;
1335
shiqiane8ff1482008-09-08 17:55:52 +00001336// Tests String::CaseInsensitiveWideCStringEquals
1337TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1338 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001339 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1340 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1341 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1342 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +00001343 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1344 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1345 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1346}
1347
shiqian4b6829f2008-07-03 22:38:12 +00001348// Tests that NULL can be assigned to a String.
1349TEST(StringTest, CanBeAssignedNULL) {
1350 const String src(NULL);
1351 String dest;
1352
1353 dest = src;
1354 EXPECT_STREQ(NULL, dest.c_str());
1355}
1356
1357// Tests that the empty string "" can be assigned to a String.
1358TEST(StringTest, CanBeAssignedEmpty) {
1359 const String src("");
1360 String dest;
1361
1362 dest = src;
1363 EXPECT_STREQ("", dest.c_str());
1364}
1365
1366// Tests that a non-empty string can be assigned to a String.
1367TEST(StringTest, CanBeAssignedNonEmpty) {
1368 const String src("hello");
1369 String dest;
shiqian4b6829f2008-07-03 22:38:12 +00001370 dest = src;
zhanyong.wan89be5762009-09-01 18:53:56 +00001371 EXPECT_EQ(5U, dest.length());
shiqian4b6829f2008-07-03 22:38:12 +00001372 EXPECT_STREQ("hello", dest.c_str());
zhanyong.wan89be5762009-09-01 18:53:56 +00001373
1374 const String src2("x\0y", 3);
1375 String dest2;
1376 dest2 = src2;
1377 EXPECT_EQ(3U, dest2.length());
1378 EXPECT_EQ('x', dest2.c_str()[0]);
1379 EXPECT_EQ('\0', dest2.c_str()[1]);
1380 EXPECT_EQ('y', dest2.c_str()[2]);
shiqian4b6829f2008-07-03 22:38:12 +00001381}
1382
1383// Tests that a String can be assigned to itself.
1384TEST(StringTest, CanBeAssignedSelf) {
1385 String dest("hello");
1386
1387 dest = dest;
1388 EXPECT_STREQ("hello", dest.c_str());
1389}
1390
zhanyong.wan89be5762009-09-01 18:53:56 +00001391// Tests streaming a String.
1392TEST(StringTest, Streams) {
1393 EXPECT_EQ(StreamableToString(String()), "(null)");
1394 EXPECT_EQ(StreamableToString(String("")), "");
1395 EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
1396}
1397
zhanyong.wanf39160b2009-09-04 18:30:25 +00001398// Tests that String::Format() works.
1399TEST(StringTest, FormatWorks) {
1400 // Normal case: the format spec is valid, the arguments match the
1401 // spec, and the result is < 4095 characters.
1402 EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
1403
1404 // Edge case: the result is 4095 characters.
1405 char buffer[4096];
1406 const size_t kSize = sizeof(buffer);
1407 memset(buffer, 'a', kSize - 1);
1408 buffer[kSize - 1] = '\0';
1409 EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
1410
1411 // The result needs to be 4096 characters, exceeding Format()'s limit.
1412 EXPECT_STREQ("<formatting error or buffer exceeded>",
1413 String::Format("x%s", buffer).c_str());
1414
1415#if GTEST_OS_LINUX
1416 // On Linux, invalid format spec should lead to an error message.
1417 // In other environment (e.g. MSVC on Windows), String::Format() may
1418 // simply ignore a bad format spec, so this assertion is run on
1419 // Linux only.
1420 EXPECT_STREQ("<formatting error or buffer exceeded>",
1421 String::Format("%").c_str());
1422#endif
1423}
1424
zhanyong.wan4cd62602009-02-23 23:21:55 +00001425#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00001426
1427// Tests String::ShowWideCString().
1428TEST(StringTest, ShowWideCString) {
1429 EXPECT_STREQ("(null)",
1430 String::ShowWideCString(NULL).c_str());
1431 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1432 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1433}
1434
1435// Tests String::ShowWideCStringQuoted().
1436TEST(StringTest, ShowWideCStringQuoted) {
1437 EXPECT_STREQ("(null)",
1438 String::ShowWideCStringQuoted(NULL).c_str());
1439 EXPECT_STREQ("L\"\"",
1440 String::ShowWideCStringQuoted(L"").c_str());
1441 EXPECT_STREQ("L\"foo\"",
1442 String::ShowWideCStringQuoted(L"foo").c_str());
1443}
1444
zhanyong.wanfff03342009-09-24 21:15:59 +00001445#if GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001446TEST(StringTest, AnsiAndUtf16Null) {
1447 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1448 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1449}
1450
1451TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1452 const char* ansi = String::Utf16ToAnsi(L"str");
1453 EXPECT_STREQ("str", ansi);
1454 delete [] ansi;
1455 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001456 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001457 delete [] utf16;
1458}
1459
1460TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1461 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1462 EXPECT_STREQ(".:\\ \"*?", ansi);
1463 delete [] ansi;
1464 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001465 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001466 delete [] utf16;
1467}
zhanyong.wanfff03342009-09-24 21:15:59 +00001468#endif // GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001469
shiqian4b6829f2008-07-03 22:38:12 +00001470#endif // GTEST_OS_WINDOWS
1471
1472// Tests TestProperty construction.
1473TEST(TestPropertyTest, StringValue) {
1474 TestProperty property("key", "1");
1475 EXPECT_STREQ("key", property.key());
1476 EXPECT_STREQ("1", property.value());
1477}
1478
1479// Tests TestProperty replacing a value.
1480TEST(TestPropertyTest, ReplaceStringValue) {
1481 TestProperty property("key", "1");
1482 EXPECT_STREQ("1", property.value());
1483 property.SetValue("2");
1484 EXPECT_STREQ("2", property.value());
1485}
1486
zhanyong.wan98efcc42009-04-28 00:28:09 +00001487// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1488// functions (i.e. their definitions cannot be inlined at the call
1489// sites), or C++Builder won't compile the code.
1490static void AddFatalFailure() {
1491 FAIL() << "Expected fatal failure.";
1492}
1493
1494static void AddNonfatalFailure() {
1495 ADD_FAILURE() << "Expected non-fatal failure.";
1496}
1497
shiqiane44602e2008-10-11 07:20:02 +00001498class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001499 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001500 enum FailureMode {
1501 FATAL_FAILURE,
1502 NONFATAL_FAILURE
1503 };
1504 static void AddFailure(FailureMode failure) {
1505 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001506 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001507 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001508 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001509 }
1510 }
shiqian4b6829f2008-07-03 22:38:12 +00001511};
1512
shiqian4b6829f2008-07-03 22:38:12 +00001513// Tests that ScopedFakeTestPartResultReporter intercepts test
1514// failures.
shiqiane44602e2008-10-11 07:20:02 +00001515TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001516 TestPartResultArray results;
1517 {
shiqiane44602e2008-10-11 07:20:02 +00001518 ScopedFakeTestPartResultReporter reporter(
1519 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1520 &results);
1521 AddFailure(NONFATAL_FAILURE);
1522 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001523 }
1524
1525 EXPECT_EQ(2, results.size());
1526 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1527 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1528}
1529
shiqiane44602e2008-10-11 07:20:02 +00001530TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1531 TestPartResultArray results;
1532 {
1533 // Tests, that the deprecated constructor still works.
1534 ScopedFakeTestPartResultReporter reporter(&results);
1535 AddFailure(NONFATAL_FAILURE);
1536 }
1537 EXPECT_EQ(1, results.size());
1538}
1539
1540#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1541
1542class ScopedFakeTestPartResultReporterWithThreadsTest
1543 : public ScopedFakeTestPartResultReporterTest {
1544 protected:
1545 static void AddFailureInOtherThread(FailureMode failure) {
1546 pthread_t tid;
1547 pthread_create(&tid,
1548 NULL,
1549 ScopedFakeTestPartResultReporterWithThreadsTest::
1550 FailureThread,
1551 &failure);
1552 pthread_join(tid, NULL);
1553 }
1554 private:
1555 static void* FailureThread(void* attr) {
1556 FailureMode* failure = static_cast<FailureMode*>(attr);
1557 AddFailure(*failure);
1558 return NULL;
1559 }
1560};
1561
1562TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1563 InterceptsTestFailuresInAllThreads) {
1564 TestPartResultArray results;
1565 {
1566 ScopedFakeTestPartResultReporter reporter(
1567 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1568 AddFailure(NONFATAL_FAILURE);
1569 AddFailure(FATAL_FAILURE);
1570 AddFailureInOtherThread(NONFATAL_FAILURE);
1571 AddFailureInOtherThread(FATAL_FAILURE);
1572 }
1573
1574 EXPECT_EQ(4, results.size());
1575 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1576 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1577 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1578 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1579}
1580
1581#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1582
zhanyong.wan98efcc42009-04-28 00:28:09 +00001583// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1584// work even if the failure is generated in a called function rather than
1585// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001586
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001587typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001588
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001589TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001590 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001591}
1592
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001593TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1594 // We have another test below to verify that the macro catches fatal
1595 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001596 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001597 "Expected fatal failure.");
1598}
1599
zhanyong.wan98efcc42009-04-28 00:28:09 +00001600#ifdef __BORLANDC__
1601// Silences warnings: "Condition is always true"
1602#pragma option push -w-ccc
1603#endif
1604
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001605// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1606// function even when the statement in it contains ASSERT_*.
1607
1608int NonVoidFunction() {
1609 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1610 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1611 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001612}
1613
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001614TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1615 NonVoidFunction();
1616}
1617
1618// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1619// current function even though 'statement' generates a fatal failure.
1620
1621void DoesNotAbortHelper(bool* aborted) {
1622 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1623 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1624
1625 *aborted = false;
1626}
1627
zhanyong.wan98efcc42009-04-28 00:28:09 +00001628#ifdef __BORLANDC__
1629// Restores warnings after previous "#pragma option push" supressed them
1630#pragma option pop
1631#endif
1632
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001633TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1634 bool aborted = true;
1635 DoesNotAbortHelper(&aborted);
1636 EXPECT_FALSE(aborted);
1637}
1638
1639// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1640// statement that contains a macro which expands to code containing an
1641// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001642
1643static int global_var = 0;
1644#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1645
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001646TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001647#ifndef __BORLANDC__
1648 // ICE's in C++Builder 2007.
shiqiane44602e2008-10-11 07:20:02 +00001649 EXPECT_FATAL_FAILURE({
1650 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001651 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001652 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001653#endif
shiqiane44602e2008-10-11 07:20:02 +00001654
1655 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1656 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001657 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001658 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001659}
shiqiane44602e2008-10-11 07:20:02 +00001660
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001661// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1662
1663typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1664
1665TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001666 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001667 "Expected non-fatal failure.");
1668}
1669
1670TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1671 // We have another test below to verify that the macro catches
1672 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001673 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001674 "Expected non-fatal failure.");
1675}
1676
1677// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1678// statement that contains a macro which expands to code containing an
1679// unprotected comma.
1680TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001681 EXPECT_NONFATAL_FAILURE({
1682 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001683 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001684 }, "");
1685
1686 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1687 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001688 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001689 }, "");
1690}
1691
1692#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1693
1694typedef ScopedFakeTestPartResultReporterWithThreadsTest
1695 ExpectFailureWithThreadsTest;
1696
1697TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1698 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1699 "Expected fatal failure.");
1700}
1701
1702TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1703 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1704 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1705}
1706
1707#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1708
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001709// Tests the TestProperty class.
1710
1711TEST(TestPropertyTest, ConstructorWorks) {
1712 const TestProperty property("key", "value");
1713 EXPECT_STREQ("key", property.key());
1714 EXPECT_STREQ("value", property.value());
1715}
1716
1717TEST(TestPropertyTest, SetValue) {
1718 TestProperty property("key", "value_1");
1719 EXPECT_STREQ("key", property.key());
1720 property.SetValue("value_2");
1721 EXPECT_STREQ("key", property.key());
1722 EXPECT_STREQ("value_2", property.value());
1723}
1724
shiqian4b6829f2008-07-03 22:38:12 +00001725// Tests the TestResult class
1726
1727// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001728class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001729 protected:
zhanyong.wana8a582f2009-07-13 19:25:02 +00001730 typedef Vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001731
1732 // We make use of 2 TestPartResult objects,
1733 TestPartResult * pr1, * pr2;
1734
1735 // ... and 3 TestResult objects.
1736 TestResult * r0, * r1, * r2;
1737
1738 virtual void SetUp() {
1739 // pr1 is for success.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001740 pr1 = new TestPartResult(TestPartResult::kSuccess,
1741 "foo/bar.cc",
1742 10,
1743 "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001744
1745 // pr2 is for fatal failure.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001746 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1747 "foo/bar.cc",
shiqian760af5c2008-08-06 21:43:15 +00001748 -1, // This line number means "unknown"
1749 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001750
1751 // Creates the TestResult objects.
1752 r0 = new TestResult();
1753 r1 = new TestResult();
1754 r2 = new TestResult();
1755
1756 // In order to test TestResult, we need to modify its internal
zhanyong.wana8a582f2009-07-13 19:25:02 +00001757 // state, in particular the TestPartResult Vector it holds.
1758 // test_part_results() returns a const reference to this Vector.
shiqian4b6829f2008-07-03 22:38:12 +00001759 // We cast it to a non-const object s.t. it can be modified (yes,
1760 // this is a hack).
zhanyong.wana8a582f2009-07-13 19:25:02 +00001761 TPRVector* results1 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001762 &TestResultAccessor::test_part_results(*r1));
zhanyong.wana8a582f2009-07-13 19:25:02 +00001763 TPRVector* results2 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001764 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001765
1766 // r0 is an empty TestResult.
1767
1768 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001769 results1->PushBack(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001770
1771 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001772 results2->PushBack(*pr1);
1773 results2->PushBack(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001774 }
1775
1776 virtual void TearDown() {
1777 delete pr1;
1778 delete pr2;
1779
1780 delete r0;
1781 delete r1;
1782 delete r2;
1783 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001784
1785 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001786 static void CompareTestPartResult(const TestPartResult& expected,
1787 const TestPartResult& actual) {
1788 EXPECT_EQ(expected.type(), actual.type());
1789 EXPECT_STREQ(expected.file_name(), actual.file_name());
1790 EXPECT_EQ(expected.line_number(), actual.line_number());
1791 EXPECT_STREQ(expected.summary(), actual.summary());
1792 EXPECT_STREQ(expected.message(), actual.message());
1793 EXPECT_EQ(expected.passed(), actual.passed());
1794 EXPECT_EQ(expected.failed(), actual.failed());
1795 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1796 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001797 }
shiqian4b6829f2008-07-03 22:38:12 +00001798};
1799
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001800// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001801TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001802 ASSERT_EQ(0, r0->total_part_count());
1803 ASSERT_EQ(1, r1->total_part_count());
1804 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001805}
1806
zhanyong.wan9644db82009-06-24 23:02:50 +00001807// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001808TEST_F(TestResultTest, Passed) {
1809 ASSERT_TRUE(r0->Passed());
1810 ASSERT_TRUE(r1->Passed());
1811 ASSERT_FALSE(r2->Passed());
1812}
1813
zhanyong.wan9644db82009-06-24 23:02:50 +00001814// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001815TEST_F(TestResultTest, Failed) {
1816 ASSERT_FALSE(r0->Failed());
1817 ASSERT_FALSE(r1->Failed());
1818 ASSERT_TRUE(r2->Failed());
1819}
1820
zhanyong.wan9644db82009-06-24 23:02:50 +00001821// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001822
1823typedef TestResultTest TestResultDeathTest;
1824
1825TEST_F(TestResultDeathTest, GetTestPartResult) {
1826 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1827 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
zhanyong.wan535de532009-08-07 06:47:47 +00001828 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001829 r2->GetTestPartResult(2),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001830 "Invalid Vector index 2: must be in range \\[0, 1\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +00001831 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001832 r2->GetTestPartResult(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001833 "Invalid Vector index -1: must be in range \\[0, 1\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001834}
1835
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001836// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001837TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1838 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001839 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001840}
1841
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001842// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001843TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1844 TestResult test_result;
1845 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001846 TestResultAccessor::RecordProperty(&test_result, property);
1847 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001848 const TestProperty& actual_property = test_result.GetTestProperty(0);
1849 EXPECT_STREQ("key_1", actual_property.key());
1850 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001851}
1852
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001853// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001854TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1855 TestResult test_result;
1856 TestProperty property_1("key_1", "1");
1857 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001858 TestResultAccessor::RecordProperty(&test_result, property_1);
1859 TestResultAccessor::RecordProperty(&test_result, property_2);
1860 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001861 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1862 EXPECT_STREQ("key_1", actual_property_1.key());
1863 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001864
zhanyong.wan449f84d2009-07-01 22:55:05 +00001865 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1866 EXPECT_STREQ("key_2", actual_property_2.key());
1867 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001868}
1869
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001870// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001871TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1872 TestResult test_result;
1873 TestProperty property_1_1("key_1", "1");
1874 TestProperty property_2_1("key_2", "2");
1875 TestProperty property_1_2("key_1", "12");
1876 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001877 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1878 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1879 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1880 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001881
zhanyong.wan9644db82009-06-24 23:02:50 +00001882 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001883 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1884 EXPECT_STREQ("key_1", actual_property_1.key());
1885 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001886
zhanyong.wan449f84d2009-07-01 22:55:05 +00001887 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1888 EXPECT_STREQ("key_2", actual_property_2.key());
1889 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001890}
1891
1892// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001893TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001894 TestResult test_result;
1895 TestProperty property_1("key_1", "1");
1896 TestProperty property_2("key_2", "2");
1897 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001898 TestResultAccessor::RecordProperty(&test_result, property_1);
1899 TestResultAccessor::RecordProperty(&test_result, property_2);
1900 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001901
zhanyong.wan449f84d2009-07-01 22:55:05 +00001902 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1903 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1904 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001905
zhanyong.wan449f84d2009-07-01 22:55:05 +00001906 EXPECT_STREQ("key_1", fetched_property_1.key());
1907 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001908
zhanyong.wan449f84d2009-07-01 22:55:05 +00001909 EXPECT_STREQ("key_2", fetched_property_2.key());
1910 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001911
zhanyong.wan449f84d2009-07-01 22:55:05 +00001912 EXPECT_STREQ("key_3", fetched_property_3.key());
1913 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001914
zhanyong.wan535de532009-08-07 06:47:47 +00001915 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001916 test_result.GetTestProperty(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001917 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan535de532009-08-07 06:47:47 +00001918 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001919 test_result.GetTestProperty(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001920 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001921}
1922
shiqian4b6829f2008-07-03 22:38:12 +00001923// When a property using a reserved key is supplied to this function, it tests
1924// that a non-fatal failure is added, a fatal failure is not added, and that the
1925// property is not recorded.
1926void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1927 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001928 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001929 EXPECT_NONFATAL_FAILURE(
1930 TestResultAccessor::RecordProperty(&test_result, property),
1931 "Reserved key");
1932 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001933}
1934
1935// Attempting to recording a property with the Reserved literal "name"
1936// should add a non-fatal failure and the property should not be recorded.
1937TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1938 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1939}
1940
1941// Attempting to recording a property with the Reserved literal "status"
1942// should add a non-fatal failure and the property should not be recorded.
1943TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1944 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1945}
1946
1947// Attempting to recording a property with the Reserved literal "time"
1948// should add a non-fatal failure and the property should not be recorded.
1949TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1950 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1951}
1952
1953// Attempting to recording a property with the Reserved literal "classname"
1954// should add a non-fatal failure and the property should not be recorded.
1955TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1956 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1957}
1958
1959// Tests that GTestFlagSaver works on Windows and Mac.
1960
shiqian760af5c2008-08-06 21:43:15 +00001961class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001962 protected:
1963 // Saves the Google Test flags such that we can restore them later, and
1964 // then sets them to their default values. This will be called
1965 // before the first test in this test case is run.
1966 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001967 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001968
shiqianca6949f2009-01-10 01:16:33 +00001969 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001970 GTEST_FLAG(break_on_failure) = false;
1971 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001972 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001973 GTEST_FLAG(color) = "auto";
1974 GTEST_FLAG(filter) = "";
1975 GTEST_FLAG(list_tests) = false;
1976 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001977 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001978 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001979 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001980 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00001981 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001982 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001983 }
1984
1985 // Restores the Google Test flags that the tests have modified. This will
1986 // be called after the last test in this test case is run.
1987 static void TearDownTestCase() {
1988 delete saver_;
1989 saver_ = NULL;
1990 }
1991
1992 // Verifies that the Google Test flags have their default values, and then
1993 // modifies each of them.
1994 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001995 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001996 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1997 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1998 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001999 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00002000 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
2001 EXPECT_FALSE(GTEST_FLAG(list_tests));
2002 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00002003 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00002004 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00002005 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00002006 EXPECT_FALSE(GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00002007 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00002008 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00002009
shiqianca6949f2009-01-10 01:16:33 +00002010 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00002011 GTEST_FLAG(break_on_failure) = true;
2012 GTEST_FLAG(catch_exceptions) = true;
2013 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00002014 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00002015 GTEST_FLAG(filter) = "abc";
2016 GTEST_FLAG(list_tests) = true;
2017 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00002018 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00002019 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00002020 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00002021 GTEST_FLAG(shuffle) = true;
vladlosevba015a92009-11-17 22:43:15 +00002022 GTEST_FLAG(stack_trace_depth) = 1;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00002023 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00002024 }
2025 private:
2026 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00002027 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00002028};
2029
shiqian760af5c2008-08-06 21:43:15 +00002030GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00002031
2032// Google Test doesn't guarantee the order of tests. The following two
2033// tests are designed to work regardless of their order.
2034
2035// Modifies the Google Test flags in the test body.
2036TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
2037 VerifyAndModifyFlags();
2038}
2039
2040// Verifies that the Google Test flags in the body of the previous test were
2041// restored to their original values.
2042TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
2043 VerifyAndModifyFlags();
2044}
2045
2046// Sets an environment variable with the given name to the given
2047// value. If the value argument is "", unsets the environment
2048// variable. The caller must ensure that both arguments are not NULL.
2049static void SetEnv(const char* name, const char* value) {
zhanyong.wanfff03342009-09-24 21:15:59 +00002050#if GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00002051 // Environment variables are not supported on Windows CE.
2052 return;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002053#elif defined(__BORLANDC__)
2054 // C++Builder's putenv only stores a pointer to its parameter; we have to
2055 // ensure that the string remains valid as long as it might be needed.
2056 // We use an std::map to do so.
2057 static std::map<String, String*> added_env;
2058
2059 // Because putenv stores a pointer to the string buffer, we can't delete the
2060 // previous string (if present) until after it's replaced.
2061 String *prev_env = NULL;
2062 if (added_env.find(name) != added_env.end()) {
2063 prev_env = added_env[name];
2064 }
2065 added_env[name] = new String((Message() << name << "=" << value).GetString());
2066 putenv(added_env[name]->c_str());
2067 delete prev_env;
zhanyong.wan4cd62602009-02-23 23:21:55 +00002068#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00002069 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00002070#else
2071 if (*value == '\0') {
2072 unsetenv(name);
2073 } else {
2074 setenv(name, value, 1);
2075 }
zhanyong.wanfff03342009-09-24 21:15:59 +00002076#endif // GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00002077}
2078
zhanyong.wanfff03342009-09-24 21:15:59 +00002079#if !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00002080// Environment variables are not supported on Windows CE.
2081
shiqian760af5c2008-08-06 21:43:15 +00002082using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00002083
2084// Tests Int32FromGTestEnv().
2085
2086// Tests that Int32FromGTestEnv() returns the default value when the
2087// environment variable is not set.
2088TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002089 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00002090 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
2091}
2092
2093// Tests that Int32FromGTestEnv() returns the default value when the
2094// environment variable overflows as an Int32.
2095TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
2096 printf("(expecting 2 warnings)\n");
2097
zhanyong.wan4cd62602009-02-23 23:21:55 +00002098 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00002099 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
2100
zhanyong.wan4cd62602009-02-23 23:21:55 +00002101 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00002102 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
2103}
2104
2105// Tests that Int32FromGTestEnv() returns the default value when the
2106// environment variable does not represent a valid decimal integer.
2107TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
2108 printf("(expecting 2 warnings)\n");
2109
zhanyong.wan4cd62602009-02-23 23:21:55 +00002110 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00002111 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
2112
zhanyong.wan4cd62602009-02-23 23:21:55 +00002113 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00002114 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
2115}
2116
2117// Tests that Int32FromGTestEnv() parses and returns the value of the
2118// environment variable when it represents a valid decimal integer in
2119// the range of an Int32.
2120TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002121 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00002122 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
2123
zhanyong.wan4cd62602009-02-23 23:21:55 +00002124 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00002125 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
2126}
zhanyong.wanfff03342009-09-24 21:15:59 +00002127#endif // !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00002128
2129// Tests ParseInt32Flag().
2130
2131// Tests that ParseInt32Flag() returns false and doesn't change the
2132// output value when the flag has wrong format
2133TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
2134 Int32 value = 123;
2135 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
2136 EXPECT_EQ(123, value);
2137
2138 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
2139 EXPECT_EQ(123, value);
2140}
2141
2142// Tests that ParseInt32Flag() returns false and doesn't change the
2143// output value when the flag overflows as an Int32.
2144TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
2145 printf("(expecting 2 warnings)\n");
2146
2147 Int32 value = 123;
2148 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
2149 EXPECT_EQ(123, value);
2150
2151 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
2152 EXPECT_EQ(123, value);
2153}
2154
2155// Tests that ParseInt32Flag() returns false and doesn't change the
2156// output value when the flag does not represent a valid decimal
2157// integer.
2158TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
2159 printf("(expecting 2 warnings)\n");
2160
2161 Int32 value = 123;
2162 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
2163 EXPECT_EQ(123, value);
2164
2165 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
2166 EXPECT_EQ(123, value);
2167}
2168
2169// Tests that ParseInt32Flag() parses the value of the flag and
2170// returns true when the flag represents a valid decimal integer in
2171// the range of an Int32.
2172TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
2173 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00002174 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00002175 EXPECT_EQ(456, value);
2176
zhanyong.wan98efcc42009-04-28 00:28:09 +00002177 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
2178 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00002179 EXPECT_EQ(-789, value);
2180}
2181
zhanyong.wan905074c2009-02-09 18:05:21 +00002182// Tests that Int32FromEnvOrDie() parses the value of the var or
2183// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00002184// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00002185#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002186TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002187 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
2188 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
2189 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
2190 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
2191 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00002192}
zhanyong.wanfff03342009-09-24 21:15:59 +00002193#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002194
2195// Tests that Int32FromEnvOrDie() aborts with an error message
2196// if the variable is not an Int32.
2197TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002198 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan535de532009-08-07 06:47:47 +00002199 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00002200 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
2201 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002202}
2203
2204// Tests that Int32FromEnvOrDie() aborts with an error message
2205// if the variable cannot be represnted by an Int32.
2206TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002207 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan535de532009-08-07 06:47:47 +00002208 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00002209 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
2210 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002211}
2212
zhanyong.wan905074c2009-02-09 18:05:21 +00002213// Tests that ShouldRunTestOnShard() selects all tests
2214// where there is 1 shard.
2215TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
2216 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
2217 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
2218 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
2219 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
2220 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
2221}
2222
2223class ShouldShardTest : public testing::Test {
2224 protected:
2225 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002226 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
2227 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00002228 }
2229
2230 virtual void TearDown() {
2231 SetEnv(index_var_, "");
2232 SetEnv(total_var_, "");
2233 }
2234
2235 const char* index_var_;
2236 const char* total_var_;
2237};
2238
2239// Tests that sharding is disabled if neither of the environment variables
2240// are set.
2241TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
2242 SetEnv(index_var_, "");
2243 SetEnv(total_var_, "");
2244
2245 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
2246 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2247}
2248
2249// Tests that sharding is not enabled if total_shards == 1.
2250TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
2251 SetEnv(index_var_, "0");
2252 SetEnv(total_var_, "1");
2253 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
2254 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2255}
2256
2257// Tests that sharding is enabled if total_shards > 1 and
2258// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00002259// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00002260#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002261TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
2262 SetEnv(index_var_, "4");
2263 SetEnv(total_var_, "22");
2264 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2265 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2266
2267 SetEnv(index_var_, "8");
2268 SetEnv(total_var_, "9");
2269 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2270 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2271
2272 SetEnv(index_var_, "0");
2273 SetEnv(total_var_, "9");
2274 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
2275 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2276}
zhanyong.wanfff03342009-09-24 21:15:59 +00002277#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00002278
2279// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00002280
2281typedef ShouldShardTest ShouldShardDeathTest;
2282
2283TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00002284 SetEnv(index_var_, "4");
2285 SetEnv(total_var_, "4");
zhanyong.wan535de532009-08-07 06:47:47 +00002286 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002287
2288 SetEnv(index_var_, "4");
2289 SetEnv(total_var_, "-2");
zhanyong.wan535de532009-08-07 06:47:47 +00002290 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002291
2292 SetEnv(index_var_, "5");
2293 SetEnv(total_var_, "");
zhanyong.wan535de532009-08-07 06:47:47 +00002294 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002295
2296 SetEnv(index_var_, "");
2297 SetEnv(total_var_, "5");
zhanyong.wan535de532009-08-07 06:47:47 +00002298 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00002299}
2300
zhanyong.wan905074c2009-02-09 18:05:21 +00002301// Tests that ShouldRunTestOnShard is a partition when 5
2302// shards are used.
2303TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
2304 // Choose an arbitrary number of tests and shards.
2305 const int num_tests = 17;
2306 const int num_shards = 5;
2307
2308 // Check partitioning: each test should be on exactly 1 shard.
2309 for (int test_id = 0; test_id < num_tests; test_id++) {
2310 int prev_selected_shard_index = -1;
2311 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2312 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
2313 if (prev_selected_shard_index < 0) {
2314 prev_selected_shard_index = shard_index;
2315 } else {
2316 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
2317 << shard_index << " are both selected to run test " << test_id;
2318 }
2319 }
2320 }
2321 }
2322
2323 // Check balance: This is not required by the sharding protocol, but is a
2324 // desirable property for performance.
2325 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2326 int num_tests_on_shard = 0;
2327 for (int test_id = 0; test_id < num_tests; test_id++) {
2328 num_tests_on_shard +=
2329 ShouldRunTestOnShard(num_shards, shard_index, test_id);
2330 }
2331 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
2332 }
2333}
2334
shiqian4b6829f2008-07-03 22:38:12 +00002335// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00002336// Test class, there are no separate tests for the following classes
2337// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00002338//
2339// TestCase, UnitTest, UnitTestResultPrinter.
2340//
2341// Similarly, there are no separate tests for the following macros:
2342//
2343// TEST, TEST_F, RUN_ALL_TESTS
2344
shiqianc3b4de32008-09-12 04:01:37 +00002345TEST(UnitTestTest, CanGetOriginalWorkingDir) {
2346 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
2347 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2348}
2349
shiqian4b6829f2008-07-03 22:38:12 +00002350// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2351// of various arities. They do not attempt to be exhaustive. Rather,
2352// view them as smoke tests that can be easily reviewed and verified.
2353// A more complete set of tests for predicate assertions can be found
2354// in gtest_pred_impl_unittest.cc.
2355
2356// First, some predicates and predicate-formatters needed by the tests.
2357
2358// Returns true iff the argument is an even number.
2359bool IsEven(int n) {
2360 return (n % 2) == 0;
2361}
2362
2363// A functor that returns true iff the argument is an even number.
2364struct IsEvenFunctor {
2365 bool operator()(int n) { return IsEven(n); }
2366};
2367
2368// A predicate-formatter function that asserts the argument is an even
2369// number.
shiqian760af5c2008-08-06 21:43:15 +00002370AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002371 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00002372 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002373 }
2374
shiqian760af5c2008-08-06 21:43:15 +00002375 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002376 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002377 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002378}
2379
vladlosevfbd53a52009-10-20 21:03:10 +00002380// A predicate function that returns AssertionResult for use in
2381// EXPECT/ASSERT_TRUE/FALSE.
2382AssertionResult ResultIsEven(int n) {
2383 if (IsEven(n))
2384 return AssertionSuccess() << n << " is even";
2385 else
2386 return AssertionFailure() << n << " is odd";
2387}
2388
2389// A predicate function that returns AssertionResult but gives no
2390// explanation why it succeeds. Needed for testing that
2391// EXPECT/ASSERT_FALSE handles such functions correctly.
2392AssertionResult ResultIsEvenNoExplanation(int n) {
2393 if (IsEven(n))
2394 return AssertionSuccess();
2395 else
2396 return AssertionFailure() << n << " is odd";
2397}
2398
shiqian4b6829f2008-07-03 22:38:12 +00002399// A predicate-formatter functor that asserts the argument is an even
2400// number.
2401struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00002402 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002403 return AssertIsEven(expr, n);
2404 }
2405};
2406
2407// Returns true iff the sum of the arguments is an even number.
2408bool SumIsEven2(int n1, int n2) {
2409 return IsEven(n1 + n2);
2410}
2411
2412// A functor that returns true iff the sum of the arguments is an even
2413// number.
2414struct SumIsEven3Functor {
2415 bool operator()(int n1, int n2, int n3) {
2416 return IsEven(n1 + n2 + n3);
2417 }
2418};
2419
2420// A predicate-formatter function that asserts the sum of the
2421// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00002422AssertionResult AssertSumIsEven4(
2423 const char* e1, const char* e2, const char* e3, const char* e4,
2424 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00002425 const int sum = n1 + n2 + n3 + n4;
2426 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002427 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002428 }
2429
shiqian760af5c2008-08-06 21:43:15 +00002430 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002431 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2432 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2433 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002434 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002435}
2436
2437// A predicate-formatter functor that asserts the sum of the arguments
2438// is an even number.
2439struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00002440 AssertionResult operator()(
2441 const char* e1, const char* e2, const char* e3, const char* e4,
2442 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00002443 const int sum = n1 + n2 + n3 + n4 + n5;
2444 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002445 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002446 }
2447
shiqian760af5c2008-08-06 21:43:15 +00002448 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002449 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2450 << " ("
2451 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2452 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002453 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002454 }
2455};
2456
2457
2458// Tests unary predicate assertions.
2459
2460// Tests unary predicate assertions that don't use a custom formatter.
2461TEST(Pred1Test, WithoutFormat) {
2462 // Success cases.
2463 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2464 ASSERT_PRED1(IsEven, 4);
2465
2466 // Failure cases.
2467 EXPECT_NONFATAL_FAILURE({ // NOLINT
2468 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2469 }, "This failure is expected.");
2470 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2471 "evaluates to false");
2472}
2473
2474// Tests unary predicate assertions that use a custom formatter.
2475TEST(Pred1Test, WithFormat) {
2476 // Success cases.
2477 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2478 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2479 << "This failure is UNEXPECTED!";
2480
2481 // Failure cases.
2482 const int n = 5;
2483 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2484 "n evaluates to 5, which is not even.");
2485 EXPECT_FATAL_FAILURE({ // NOLINT
2486 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2487 }, "This failure is expected.");
2488}
2489
2490// Tests that unary predicate assertions evaluates their arguments
2491// exactly once.
2492TEST(Pred1Test, SingleEvaluationOnFailure) {
2493 // A success case.
2494 static int n = 0;
2495 EXPECT_PRED1(IsEven, n++);
2496 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2497
2498 // A failure case.
2499 EXPECT_FATAL_FAILURE({ // NOLINT
2500 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2501 << "This failure is expected.";
2502 }, "This failure is expected.");
2503 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2504}
2505
2506
2507// Tests predicate assertions whose arity is >= 2.
2508
2509// Tests predicate assertions that don't use a custom formatter.
2510TEST(PredTest, WithoutFormat) {
2511 // Success cases.
2512 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2513 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2514
2515 // Failure cases.
2516 const int n1 = 1;
2517 const int n2 = 2;
2518 EXPECT_NONFATAL_FAILURE({ // NOLINT
2519 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2520 }, "This failure is expected.");
2521 EXPECT_FATAL_FAILURE({ // NOLINT
2522 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2523 }, "evaluates to false");
2524}
2525
2526// Tests predicate assertions that use a custom formatter.
2527TEST(PredTest, WithFormat) {
2528 // Success cases.
2529 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2530 "This failure is UNEXPECTED!";
2531 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2532
2533 // Failure cases.
2534 const int n1 = 1;
2535 const int n2 = 2;
2536 const int n3 = 4;
2537 const int n4 = 6;
2538 EXPECT_NONFATAL_FAILURE({ // NOLINT
2539 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2540 }, "evaluates to 13, which is not even.");
2541 EXPECT_FATAL_FAILURE({ // NOLINT
2542 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2543 << "This failure is expected.";
2544 }, "This failure is expected.");
2545}
2546
2547// Tests that predicate assertions evaluates their arguments
2548// exactly once.
2549TEST(PredTest, SingleEvaluationOnFailure) {
2550 // A success case.
2551 int n1 = 0;
2552 int n2 = 0;
2553 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2554 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2555 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2556
2557 // Another success case.
2558 n1 = n2 = 0;
2559 int n3 = 0;
2560 int n4 = 0;
2561 int n5 = 0;
2562 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2563 n1++, n2++, n3++, n4++, n5++)
2564 << "This failure is UNEXPECTED!";
2565 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2566 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2567 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2568 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2569 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2570
2571 // A failure case.
2572 n1 = n2 = n3 = 0;
2573 EXPECT_NONFATAL_FAILURE({ // NOLINT
2574 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2575 << "This failure is expected.";
2576 }, "This failure is expected.");
2577 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2578 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2579 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2580
2581 // Another failure case.
2582 n1 = n2 = n3 = n4 = 0;
2583 EXPECT_NONFATAL_FAILURE({ // NOLINT
2584 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2585 }, "evaluates to 1, which is not even.");
2586 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2587 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2588 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2589 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2590}
2591
2592
2593// Some helper functions for testing using overloaded/template
2594// functions with ASSERT_PREDn and EXPECT_PREDn.
2595
2596bool IsPositive(int n) {
2597 return n > 0;
2598}
2599
2600bool IsPositive(double x) {
2601 return x > 0;
2602}
2603
2604template <typename T>
2605bool IsNegative(T x) {
2606 return x < 0;
2607}
2608
2609template <typename T1, typename T2>
2610bool GreaterThan(T1 x1, T2 x2) {
2611 return x1 > x2;
2612}
2613
2614// Tests that overloaded functions can be used in *_PRED* as long as
2615// their types are explicitly specified.
2616TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002617 // C++Builder requires C-style casts rather than static_cast.
2618 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2619 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002620}
2621
2622// Tests that template functions can be used in *_PRED* as long as
2623// their types are explicitly specified.
2624TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2625 EXPECT_PRED1(IsNegative<int>, -5);
2626 // Makes sure that we can handle templates with more than one
2627 // parameter.
2628 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2629}
2630
2631
2632// Some helper functions for testing using overloaded/template
2633// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2634
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002635AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002636 return n > 0 ? AssertionSuccess() :
2637 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002638}
2639
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002640AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002641 return x > 0 ? AssertionSuccess() :
2642 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002643}
2644
2645template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002646AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002647 return x < 0 ? AssertionSuccess() :
2648 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002649}
2650
2651template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002652AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002653 const T1& x1, const T2& x2) {
2654 return x1 == x2 ? AssertionSuccess() :
2655 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002656}
2657
2658// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002659// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002660TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2661 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2662 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2663}
2664
2665// Tests that template functions can be used in *_PRED_FORMAT* without
2666// explicitly specifying their types.
2667TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2668 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2669 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2670}
2671
2672
2673// Tests string assertions.
2674
2675// Tests ASSERT_STREQ with non-NULL arguments.
2676TEST(StringAssertionTest, ASSERT_STREQ) {
2677 const char * const p1 = "good";
2678 ASSERT_STREQ(p1, p1);
2679
2680 // Let p2 have the same content as p1, but be at a different address.
2681 const char p2[] = "good";
2682 ASSERT_STREQ(p1, p2);
2683
2684 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2685 "Expected: \"bad\"");
2686}
2687
2688// Tests ASSERT_STREQ with NULL arguments.
2689TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2690 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2691 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2692 "non-null");
2693}
2694
2695// Tests ASSERT_STREQ with NULL arguments.
2696TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2697 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2698 "non-null");
2699}
2700
2701// Tests ASSERT_STRNE.
2702TEST(StringAssertionTest, ASSERT_STRNE) {
2703 ASSERT_STRNE("hi", "Hi");
2704 ASSERT_STRNE("Hi", NULL);
2705 ASSERT_STRNE(NULL, "Hi");
2706 ASSERT_STRNE("", NULL);
2707 ASSERT_STRNE(NULL, "");
2708 ASSERT_STRNE("", "Hi");
2709 ASSERT_STRNE("Hi", "");
2710 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2711 "\"Hi\" vs \"Hi\"");
2712}
2713
2714// Tests ASSERT_STRCASEEQ.
2715TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2716 ASSERT_STRCASEEQ("hi", "Hi");
2717 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2718
2719 ASSERT_STRCASEEQ("", "");
2720 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2721 "(ignoring case)");
2722}
2723
2724// Tests ASSERT_STRCASENE.
2725TEST(StringAssertionTest, ASSERT_STRCASENE) {
2726 ASSERT_STRCASENE("hi1", "Hi2");
2727 ASSERT_STRCASENE("Hi", NULL);
2728 ASSERT_STRCASENE(NULL, "Hi");
2729 ASSERT_STRCASENE("", NULL);
2730 ASSERT_STRCASENE(NULL, "");
2731 ASSERT_STRCASENE("", "Hi");
2732 ASSERT_STRCASENE("Hi", "");
2733 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2734 "(ignoring case)");
2735}
2736
2737// Tests *_STREQ on wide strings.
2738TEST(StringAssertionTest, STREQ_Wide) {
2739 // NULL strings.
2740 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2741
2742 // Empty strings.
2743 ASSERT_STREQ(L"", L"");
2744
2745 // Non-null vs NULL.
2746 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2747 "non-null");
2748
2749 // Equal strings.
2750 EXPECT_STREQ(L"Hi", L"Hi");
2751
2752 // Unequal strings.
2753 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2754 "Abc");
2755
2756 // Strings containing wide characters.
2757 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2758 "abc");
2759}
2760
2761// Tests *_STRNE on wide strings.
2762TEST(StringAssertionTest, STRNE_Wide) {
2763 // NULL strings.
2764 EXPECT_NONFATAL_FAILURE({ // NOLINT
2765 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2766 }, "");
2767
2768 // Empty strings.
2769 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2770 "L\"\"");
2771
2772 // Non-null vs NULL.
2773 ASSERT_STRNE(L"non-null", NULL);
2774
2775 // Equal strings.
2776 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2777 "L\"Hi\"");
2778
2779 // Unequal strings.
2780 EXPECT_STRNE(L"abc", L"Abc");
2781
2782 // Strings containing wide characters.
2783 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2784 "abc");
2785}
2786
2787// Tests for ::testing::IsSubstring().
2788
2789// Tests that IsSubstring() returns the correct result when the input
2790// argument type is const char*.
2791TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002792 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2793 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2794 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2795
2796 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2797 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2798}
2799
2800// Tests that IsSubstring() returns the correct result when the input
2801// argument type is const wchar_t*.
2802TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002803 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2804 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002805 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2806
2807 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2808 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2809}
2810
2811// Tests that IsSubstring() generates the correct message when the input
2812// argument type is const char*.
2813TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2814 EXPECT_STREQ("Value of: needle_expr\n"
2815 " Actual: \"needle\"\n"
2816 "Expected: a substring of haystack_expr\n"
2817 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002818 IsSubstring("needle_expr", "haystack_expr",
2819 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002820}
2821
shiqian4b6829f2008-07-03 22:38:12 +00002822// Tests that IsSubstring returns the correct result when the input
2823// argument type is ::std::string.
2824TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002825 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2826 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002827}
2828
shiqian4b6829f2008-07-03 22:38:12 +00002829#if GTEST_HAS_STD_WSTRING
2830// Tests that IsSubstring returns the correct result when the input
2831// argument type is ::std::wstring.
2832TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002833 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2834 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2835}
2836
2837// Tests that IsSubstring() generates the correct message when the input
2838// argument type is ::std::wstring.
2839TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2840 EXPECT_STREQ("Value of: needle_expr\n"
2841 " Actual: L\"needle\"\n"
2842 "Expected: a substring of haystack_expr\n"
2843 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002844 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002845 "needle_expr", "haystack_expr",
2846 ::std::wstring(L"needle"), L"haystack").failure_message());
2847}
2848
2849#endif // GTEST_HAS_STD_WSTRING
2850
2851// Tests for ::testing::IsNotSubstring().
2852
2853// Tests that IsNotSubstring() returns the correct result when the input
2854// argument type is const char*.
2855TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002856 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2857 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2858}
2859
2860// Tests that IsNotSubstring() returns the correct result when the input
2861// argument type is const wchar_t*.
2862TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002863 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2864 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2865}
2866
2867// Tests that IsNotSubstring() generates the correct message when the input
2868// argument type is const wchar_t*.
2869TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2870 EXPECT_STREQ("Value of: needle_expr\n"
2871 " Actual: L\"needle\"\n"
2872 "Expected: not a substring of haystack_expr\n"
2873 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002874 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002875 "needle_expr", "haystack_expr",
2876 L"needle", L"two needles").failure_message());
2877}
2878
shiqian4b6829f2008-07-03 22:38:12 +00002879// Tests that IsNotSubstring returns the correct result when the input
2880// argument type is ::std::string.
2881TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002882 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2883 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2884}
2885
2886// Tests that IsNotSubstring() generates the correct message when the input
2887// argument type is ::std::string.
2888TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2889 EXPECT_STREQ("Value of: needle_expr\n"
2890 " Actual: \"needle\"\n"
2891 "Expected: not a substring of haystack_expr\n"
2892 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002893 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002894 "needle_expr", "haystack_expr",
2895 ::std::string("needle"), "two needles").failure_message());
2896}
2897
shiqian4b6829f2008-07-03 22:38:12 +00002898#if GTEST_HAS_STD_WSTRING
2899
2900// Tests that IsNotSubstring returns the correct result when the input
2901// argument type is ::std::wstring.
2902TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002903 EXPECT_FALSE(
2904 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2905 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2906}
2907
2908#endif // GTEST_HAS_STD_WSTRING
2909
2910// Tests floating-point assertions.
2911
2912template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002913class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002914 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002915
2916 // Pre-calculated numbers to be used by the tests.
2917 struct TestValues {
2918 RawType close_to_positive_zero;
2919 RawType close_to_negative_zero;
2920 RawType further_from_negative_zero;
2921
2922 RawType close_to_one;
2923 RawType further_from_one;
2924
2925 RawType infinity;
2926 RawType close_to_infinity;
2927 RawType further_from_infinity;
2928
2929 RawType nan1;
2930 RawType nan2;
2931 };
2932
shiqian4b6829f2008-07-03 22:38:12 +00002933 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2934 typedef typename Floating::Bits Bits;
2935
2936 virtual void SetUp() {
2937 const size_t max_ulps = Floating::kMaxUlps;
2938
2939 // The bits that represent 0.0.
2940 const Bits zero_bits = Floating(0).bits();
2941
2942 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002943 values_.close_to_positive_zero = Floating::ReinterpretBits(
2944 zero_bits + max_ulps/2);
2945 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002946 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002947 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002948 zero_bits + max_ulps + 1 - max_ulps/2);
2949
2950 // The bits that represent 1.0.
2951 const Bits one_bits = Floating(1).bits();
2952
2953 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002954 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2955 values_.further_from_one = Floating::ReinterpretBits(
2956 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002957
2958 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002959 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002960
2961 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002962 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002963
2964 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002965 values_.close_to_infinity = Floating::ReinterpretBits(
2966 infinity_bits - max_ulps);
2967 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002968 infinity_bits - max_ulps - 1);
2969
zhanyong.wan98efcc42009-04-28 00:28:09 +00002970 // Makes some NAN's. Sets the most significant bit of the fraction so that
2971 // our NaN's are quiet; trying to process a signaling NaN would raise an
2972 // exception if our environment enables floating point exceptions.
2973 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2974 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2975 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2976 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002977 }
2978
2979 void TestSize() {
2980 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2981 }
2982
zhanyong.wan98efcc42009-04-28 00:28:09 +00002983 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002984};
2985
2986template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002987typename FloatingPointTest<RawType>::TestValues
2988 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002989
2990// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2991typedef FloatingPointTest<float> FloatTest;
2992
2993// Tests that the size of Float::Bits matches the size of float.
2994TEST_F(FloatTest, Size) {
2995 TestSize();
2996}
2997
2998// Tests comparing with +0 and -0.
2999TEST_F(FloatTest, Zeros) {
3000 EXPECT_FLOAT_EQ(0.0, -0.0);
3001 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
3002 "1.0");
3003 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
3004 "1.5");
3005}
3006
3007// Tests comparing numbers close to 0.
3008//
3009// This ensures that *_FLOAT_EQ handles the sign correctly and no
3010// overflow occurs when comparing numbers whose absolute value is very
3011// small.
3012TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003013 // In C++Builder, names within local classes (such as used by
3014 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3015 // scoping class. Use a static local alias as a workaround.
3016 static const FloatTest::TestValues& v(this->values_);
3017
3018 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
3019 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
3020 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00003021
3022 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003023 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
3024 v.further_from_negative_zero);
3025 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00003026}
3027
3028// Tests comparing numbers close to each other.
3029TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003030 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
3031 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
3032 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00003033}
3034
3035// Tests comparing numbers far apart.
3036TEST_F(FloatTest, LargeDiff) {
3037 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
3038 "3.0");
3039}
3040
3041// Tests comparing with infinity.
3042//
3043// This ensures that no overflow occurs when comparing numbers whose
3044// absolute value is very large.
3045TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003046 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
3047 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003048#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003049 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003050 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
3051 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00003052
zhanyong.wan98efcc42009-04-28 00:28:09 +00003053 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00003054 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003055 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
3056 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003057#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003058}
3059
3060// Tests that comparing with NAN always returns false.
3061TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003062#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003063// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00003064
zhanyong.wan98efcc42009-04-28 00:28:09 +00003065 // In C++Builder, names within local classes (such as used by
3066 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3067 // scoping class. Use a static local alias as a workaround.
3068 static const FloatTest::TestValues& v(this->values_);
3069
3070 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
3071 "v.nan1");
3072 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
3073 "v.nan2");
3074 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
3075 "v.nan1");
3076
3077 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
3078 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003079#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003080}
3081
3082// Tests that *_FLOAT_EQ are reflexive.
3083TEST_F(FloatTest, Reflexive) {
3084 EXPECT_FLOAT_EQ(0.0, 0.0);
3085 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00003086 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00003087}
3088
3089// Tests that *_FLOAT_EQ are commutative.
3090TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003091 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
3092 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00003093
zhanyong.wan98efcc42009-04-28 00:28:09 +00003094 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
3095 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003096 "1.0");
3097}
3098
3099// Tests EXPECT_NEAR.
3100TEST_F(FloatTest, EXPECT_NEAR) {
3101 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
3102 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003103 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
3104 "The difference between 1.0f and 1.5f is 0.5, "
3105 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00003106 // To work around a bug in gcc 2.95.0, there is intentionally no
3107 // space after the first comma in the previous line.
3108}
3109
3110// Tests ASSERT_NEAR.
3111TEST_F(FloatTest, ASSERT_NEAR) {
3112 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
3113 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003114 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
3115 "The difference between 1.0f and 1.5f is 0.5, "
3116 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00003117 // To work around a bug in gcc 2.95.0, there is intentionally no
3118 // space after the first comma in the previous line.
3119}
3120
3121// Tests the cases where FloatLE() should succeed.
3122TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00003123 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
3124 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00003125
3126 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003127 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00003128}
3129
3130// Tests the cases where FloatLE() should fail.
3131TEST_F(FloatTest, FloatLEFails) {
3132 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003133 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00003134 "(2.0f) <= (1.0f)");
3135
3136 // or by a small yet non-negligible margin,
3137 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003138 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
3139 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00003140
zhanyong.wan98efcc42009-04-28 00:28:09 +00003141#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003142 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003143 // C++Builder gives bad results for ordered comparisons involving NaNs
3144 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003145 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003146 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
3147 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003148 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003149 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
3150 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003151 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003152 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
3153 }, "(values_.nan1) <= (values_.nan1)");
3154#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003155}
3156
3157// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
3158typedef FloatingPointTest<double> DoubleTest;
3159
3160// Tests that the size of Double::Bits matches the size of double.
3161TEST_F(DoubleTest, Size) {
3162 TestSize();
3163}
3164
3165// Tests comparing with +0 and -0.
3166TEST_F(DoubleTest, Zeros) {
3167 EXPECT_DOUBLE_EQ(0.0, -0.0);
3168 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
3169 "1.0");
3170 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
3171 "1.0");
3172}
3173
3174// Tests comparing numbers close to 0.
3175//
3176// This ensures that *_DOUBLE_EQ handles the sign correctly and no
3177// overflow occurs when comparing numbers whose absolute value is very
3178// small.
3179TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003180 // In C++Builder, names within local classes (such as used by
3181 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3182 // scoping class. Use a static local alias as a workaround.
3183 static const DoubleTest::TestValues& v(this->values_);
3184
3185 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
3186 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
3187 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00003188
3189 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003190 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
3191 v.further_from_negative_zero);
3192 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00003193}
3194
3195// Tests comparing numbers close to each other.
3196TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003197 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
3198 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
3199 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00003200}
3201
3202// Tests comparing numbers far apart.
3203TEST_F(DoubleTest, LargeDiff) {
3204 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
3205 "3.0");
3206}
3207
3208// Tests comparing with infinity.
3209//
3210// This ensures that no overflow occurs when comparing numbers whose
3211// absolute value is very large.
3212TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003213 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3214 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003215#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003216 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003217 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3218 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00003219
3220 // This is interesting as the representations of infinity_ and nan1_
3221 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003222 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3223 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003224#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003225}
3226
3227// Tests that comparing with NAN always returns false.
3228TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003229#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00003230 // In C++Builder, names within local classes (such as used by
3231 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3232 // scoping class. Use a static local alias as a workaround.
3233 static const DoubleTest::TestValues& v(this->values_);
3234
shiqiane44602e2008-10-11 07:20:02 +00003235 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003236 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3237 "v.nan1");
3238 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3239 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3240 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3241 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003242#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003243}
3244
3245// Tests that *_DOUBLE_EQ are reflexive.
3246TEST_F(DoubleTest, Reflexive) {
3247 EXPECT_DOUBLE_EQ(0.0, 0.0);
3248 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003249#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003250 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003251 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003252#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003253}
3254
3255// Tests that *_DOUBLE_EQ are commutative.
3256TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003257 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3258 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00003259
zhanyong.wan98efcc42009-04-28 00:28:09 +00003260 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3261 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3262 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00003263}
3264
3265// Tests EXPECT_NEAR.
3266TEST_F(DoubleTest, EXPECT_NEAR) {
3267 EXPECT_NEAR(-1.0, -1.1, 0.2);
3268 EXPECT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003269 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3270 "The difference between 1.0 and 1.5 is 0.5, "
3271 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003272 // To work around a bug in gcc 2.95.0, there is intentionally no
3273 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003274}
3275
3276// Tests ASSERT_NEAR.
3277TEST_F(DoubleTest, ASSERT_NEAR) {
3278 ASSERT_NEAR(-1.0, -1.1, 0.2);
3279 ASSERT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003280 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3281 "The difference between 1.0 and 1.5 is 0.5, "
3282 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003283 // To work around a bug in gcc 2.95.0, there is intentionally no
3284 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003285}
3286
3287// Tests the cases where DoubleLE() should succeed.
3288TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00003289 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3290 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00003291
3292 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003293 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00003294}
3295
3296// Tests the cases where DoubleLE() should fail.
3297TEST_F(DoubleTest, DoubleLEFails) {
3298 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003299 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003300 "(2.0) <= (1.0)");
3301
3302 // or by a small yet non-negligible margin,
3303 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003304 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3305 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00003306
zhanyong.wan98efcc42009-04-28 00:28:09 +00003307#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003308 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003309 // C++Builder gives bad results for ordered comparisons involving NaNs
3310 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003311 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003312 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3313 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003314 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003315 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3316 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003317 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003318 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3319 }, "(values_.nan1) <= (values_.nan1)");
3320#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003321}
3322
3323
3324// Verifies that a test or test case whose name starts with DISABLED_ is
3325// not run.
3326
3327// A test whose name starts with DISABLED_.
3328// Should not run.
3329TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3330 FAIL() << "Unexpected failure: Disabled test should not be run.";
3331}
3332
3333// A test whose name does not start with DISABLED_.
3334// Should run.
3335TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3336 EXPECT_EQ(1, 1);
3337}
3338
3339// A test case whose name starts with DISABLED_.
3340// Should not run.
3341TEST(DISABLED_TestCase, TestShouldNotRun) {
3342 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3343}
3344
3345// A test case and test whose names start with DISABLED_.
3346// Should not run.
3347TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3348 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3349}
3350
3351// Check that when all tests in a test case are disabled, SetupTestCase() and
3352// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00003353class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00003354 protected:
3355 static void SetUpTestCase() {
3356 FAIL() << "Unexpected failure: All tests disabled in test case. "
3357 "SetupTestCase() should not be called.";
3358 }
3359
3360 static void TearDownTestCase() {
3361 FAIL() << "Unexpected failure: All tests disabled in test case. "
3362 "TearDownTestCase() should not be called.";
3363 }
3364};
3365
3366TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3367 FAIL() << "Unexpected failure: Disabled test should not be run.";
3368}
3369
3370TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3371 FAIL() << "Unexpected failure: Disabled test should not be run.";
3372}
3373
shiqiane8ff1482008-09-08 17:55:52 +00003374// Tests that disabled typed tests aren't run.
3375
zhanyong.wan4cd62602009-02-23 23:21:55 +00003376#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00003377
3378template <typename T>
3379class TypedTest : public Test {
3380};
3381
3382typedef testing::Types<int, double> NumericTypes;
3383TYPED_TEST_CASE(TypedTest, NumericTypes);
3384
3385TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3386 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3387}
3388
3389template <typename T>
3390class DISABLED_TypedTest : public Test {
3391};
3392
3393TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3394
3395TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3396 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3397}
3398
3399#endif // GTEST_HAS_TYPED_TEST
3400
3401// Tests that disabled type-parameterized tests aren't run.
3402
zhanyong.wan4cd62602009-02-23 23:21:55 +00003403#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00003404
3405template <typename T>
3406class TypedTestP : public Test {
3407};
3408
3409TYPED_TEST_CASE_P(TypedTestP);
3410
3411TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3412 FAIL() << "Unexpected failure: "
3413 << "Disabled type-parameterized test should not run.";
3414}
3415
3416REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3417
3418INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3419
3420template <typename T>
3421class DISABLED_TypedTestP : public Test {
3422};
3423
3424TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3425
3426TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3427 FAIL() << "Unexpected failure: "
3428 << "Disabled type-parameterized test should not run.";
3429}
3430
3431REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3432
3433INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3434
3435#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00003436
3437// Tests that assertion macros evaluate their arguments exactly once.
3438
shiqian760af5c2008-08-06 21:43:15 +00003439class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00003440 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003441 // This helper function is needed by the FailedASSERT_STREQ test
3442 // below. It's public to work around C++Builder's bug with scoping local
3443 // classes.
3444 static void CompareAndIncrementCharPtrs() {
3445 ASSERT_STREQ(p1_++, p2_++);
3446 }
3447
3448 // This helper function is needed by the FailedASSERT_NE test below. It's
3449 // public to work around C++Builder's bug with scoping local classes.
3450 static void CompareAndIncrementInts() {
3451 ASSERT_NE(a_++, b_++);
3452 }
3453
shiqian4b6829f2008-07-03 22:38:12 +00003454 protected:
3455 SingleEvaluationTest() {
3456 p1_ = s1_;
3457 p2_ = s2_;
3458 a_ = 0;
3459 b_ = 0;
3460 }
3461
shiqian4b6829f2008-07-03 22:38:12 +00003462 static const char* const s1_;
3463 static const char* const s2_;
3464 static const char* p1_;
3465 static const char* p2_;
3466
3467 static int a_;
3468 static int b_;
3469};
3470
3471const char* const SingleEvaluationTest::s1_ = "01234";
3472const char* const SingleEvaluationTest::s2_ = "abcde";
3473const char* SingleEvaluationTest::p1_;
3474const char* SingleEvaluationTest::p2_;
3475int SingleEvaluationTest::a_;
3476int SingleEvaluationTest::b_;
3477
3478// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3479// exactly once.
3480TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003481 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003482 "p2_++");
3483 EXPECT_EQ(s1_ + 1, p1_);
3484 EXPECT_EQ(s2_ + 1, p2_);
3485}
3486
3487// Tests that string assertion arguments are evaluated exactly once.
3488TEST_F(SingleEvaluationTest, ASSERT_STR) {
3489 // successful EXPECT_STRNE
3490 EXPECT_STRNE(p1_++, p2_++);
3491 EXPECT_EQ(s1_ + 1, p1_);
3492 EXPECT_EQ(s2_ + 1, p2_);
3493
3494 // failed EXPECT_STRCASEEQ
3495 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3496 "ignoring case");
3497 EXPECT_EQ(s1_ + 2, p1_);
3498 EXPECT_EQ(s2_ + 2, p2_);
3499}
3500
3501// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3502// once.
3503TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003504 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3505 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003506 EXPECT_EQ(1, a_);
3507 EXPECT_EQ(1, b_);
3508}
3509
3510// Tests that assertion arguments are evaluated exactly once.
3511TEST_F(SingleEvaluationTest, OtherCases) {
3512 // successful EXPECT_TRUE
3513 EXPECT_TRUE(0 == a_++); // NOLINT
3514 EXPECT_EQ(1, a_);
3515
3516 // failed EXPECT_TRUE
3517 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3518 EXPECT_EQ(2, a_);
3519
3520 // successful EXPECT_GT
3521 EXPECT_GT(a_++, b_++);
3522 EXPECT_EQ(3, a_);
3523 EXPECT_EQ(1, b_);
3524
3525 // failed EXPECT_LT
3526 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3527 EXPECT_EQ(4, a_);
3528 EXPECT_EQ(2, b_);
3529
3530 // successful ASSERT_TRUE
3531 ASSERT_TRUE(0 < a_++); // NOLINT
3532 EXPECT_EQ(5, a_);
3533
3534 // successful ASSERT_GT
3535 ASSERT_GT(a_++, b_++);
3536 EXPECT_EQ(6, a_);
3537 EXPECT_EQ(3, b_);
3538}
3539
shiqian9204c8e2008-09-12 20:57:22 +00003540#if GTEST_HAS_EXCEPTIONS
3541
3542void ThrowAnInteger() {
3543 throw 1;
3544}
3545
3546// Tests that assertion arguments are evaluated exactly once.
3547TEST_F(SingleEvaluationTest, ExceptionTests) {
3548 // successful EXPECT_THROW
3549 EXPECT_THROW({ // NOLINT
3550 a_++;
3551 ThrowAnInteger();
3552 }, int);
3553 EXPECT_EQ(1, a_);
3554
3555 // failed EXPECT_THROW, throws different
3556 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3557 a_++;
3558 ThrowAnInteger();
3559 }, bool), "throws a different type");
3560 EXPECT_EQ(2, a_);
3561
3562 // failed EXPECT_THROW, throws nothing
3563 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3564 EXPECT_EQ(3, a_);
3565
3566 // successful EXPECT_NO_THROW
3567 EXPECT_NO_THROW(a_++);
3568 EXPECT_EQ(4, a_);
3569
3570 // failed EXPECT_NO_THROW
3571 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3572 a_++;
3573 ThrowAnInteger();
3574 }), "it throws");
3575 EXPECT_EQ(5, a_);
3576
3577 // successful EXPECT_ANY_THROW
3578 EXPECT_ANY_THROW({ // NOLINT
3579 a_++;
3580 ThrowAnInteger();
3581 });
3582 EXPECT_EQ(6, a_);
3583
3584 // failed EXPECT_ANY_THROW
3585 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3586 EXPECT_EQ(7, a_);
3587}
3588
3589#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003590
shiqiane44602e2008-10-11 07:20:02 +00003591// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3592class NoFatalFailureTest : public Test {
3593 protected:
3594 void Succeeds() {}
3595 void FailsNonFatal() {
3596 ADD_FAILURE() << "some non-fatal failure";
3597 }
3598 void Fails() {
3599 FAIL() << "some fatal failure";
3600 }
3601
3602 void DoAssertNoFatalFailureOnFails() {
3603 ASSERT_NO_FATAL_FAILURE(Fails());
3604 ADD_FAILURE() << "shold not reach here.";
3605 }
3606
3607 void DoExpectNoFatalFailureOnFails() {
3608 EXPECT_NO_FATAL_FAILURE(Fails());
3609 ADD_FAILURE() << "other failure";
3610 }
3611};
3612
3613TEST_F(NoFatalFailureTest, NoFailure) {
3614 EXPECT_NO_FATAL_FAILURE(Succeeds());
3615 ASSERT_NO_FATAL_FAILURE(Succeeds());
3616}
3617
3618TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3619 EXPECT_NONFATAL_FAILURE(
3620 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3621 "some non-fatal failure");
3622 EXPECT_NONFATAL_FAILURE(
3623 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3624 "some non-fatal failure");
3625}
3626
3627TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3628 TestPartResultArray gtest_failures;
3629 {
3630 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3631 DoAssertNoFatalFailureOnFails();
3632 }
3633 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003634 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003635 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003636 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003637 gtest_failures.GetTestPartResult(1).type());
3638 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3639 gtest_failures.GetTestPartResult(0).message());
3640 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3641 gtest_failures.GetTestPartResult(1).message());
3642}
3643
3644TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3645 TestPartResultArray gtest_failures;
3646 {
3647 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3648 DoExpectNoFatalFailureOnFails();
3649 }
3650 ASSERT_EQ(3, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003651 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003652 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003653 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003654 gtest_failures.GetTestPartResult(1).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003655 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003656 gtest_failures.GetTestPartResult(2).type());
3657 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3658 gtest_failures.GetTestPartResult(0).message());
3659 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3660 gtest_failures.GetTestPartResult(1).message());
3661 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3662 gtest_failures.GetTestPartResult(2).message());
3663}
3664
3665TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3666 TestPartResultArray gtest_failures;
3667 {
3668 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3669 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3670 }
3671 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003672 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003673 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003674 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003675 gtest_failures.GetTestPartResult(1).type());
3676 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3677 gtest_failures.GetTestPartResult(0).message());
3678 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3679 gtest_failures.GetTestPartResult(1).message());
3680}
3681
shiqian4b6829f2008-07-03 22:38:12 +00003682// Tests non-string assertions.
3683
3684// Tests EqFailure(), used for implementing *EQ* assertions.
3685TEST(AssertionTest, EqFailure) {
3686 const String foo_val("5"), bar_val("6");
3687 const String msg1(
3688 EqFailure("foo", "bar", foo_val, bar_val, false)
3689 .failure_message());
3690 EXPECT_STREQ(
3691 "Value of: bar\n"
3692 " Actual: 6\n"
3693 "Expected: foo\n"
3694 "Which is: 5",
3695 msg1.c_str());
3696
3697 const String msg2(
3698 EqFailure("foo", "6", foo_val, bar_val, false)
3699 .failure_message());
3700 EXPECT_STREQ(
3701 "Value of: 6\n"
3702 "Expected: foo\n"
3703 "Which is: 5",
3704 msg2.c_str());
3705
3706 const String msg3(
3707 EqFailure("5", "bar", foo_val, bar_val, false)
3708 .failure_message());
3709 EXPECT_STREQ(
3710 "Value of: bar\n"
3711 " Actual: 6\n"
3712 "Expected: 5",
3713 msg3.c_str());
3714
3715 const String msg4(
3716 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3717 EXPECT_STREQ(
3718 "Value of: 6\n"
3719 "Expected: 5",
3720 msg4.c_str());
3721
3722 const String msg5(
3723 EqFailure("foo", "bar",
3724 String("\"x\""), String("\"y\""),
3725 true).failure_message());
3726 EXPECT_STREQ(
3727 "Value of: bar\n"
3728 " Actual: \"y\"\n"
3729 "Expected: foo (ignoring case)\n"
3730 "Which is: \"x\"",
3731 msg5.c_str());
3732}
3733
3734// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3735TEST(AssertionTest, AppendUserMessage) {
3736 const String foo("foo");
3737
shiqian760af5c2008-08-06 21:43:15 +00003738 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003739 EXPECT_STREQ("foo",
3740 AppendUserMessage(foo, msg).c_str());
3741
3742 msg << "bar";
3743 EXPECT_STREQ("foo\nbar",
3744 AppendUserMessage(foo, msg).c_str());
3745}
3746
zhanyong.wan98efcc42009-04-28 00:28:09 +00003747#ifdef __BORLANDC__
3748// Silences warnings: "Condition is always true", "Unreachable code"
3749#pragma option push -w-ccc -w-rch
3750#endif
3751
shiqian4b6829f2008-07-03 22:38:12 +00003752// Tests ASSERT_TRUE.
3753TEST(AssertionTest, ASSERT_TRUE) {
3754 ASSERT_TRUE(2 > 1); // NOLINT
3755 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3756 "2 < 1");
3757}
3758
vladlosevfbd53a52009-10-20 21:03:10 +00003759// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3760TEST(AssertionTest, AssertTrueWithAssertionResult) {
3761 ASSERT_TRUE(ResultIsEven(2));
3762 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3763 "Value of: ResultIsEven(3)\n"
3764 " Actual: false (3 is odd)\n"
3765 "Expected: true");
3766 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3767 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3768 "Value of: ResultIsEvenNoExplanation(3)\n"
3769 " Actual: false (3 is odd)\n"
3770 "Expected: true");
3771}
3772
shiqian4b6829f2008-07-03 22:38:12 +00003773// Tests ASSERT_FALSE.
3774TEST(AssertionTest, ASSERT_FALSE) {
3775 ASSERT_FALSE(2 < 1); // NOLINT
3776 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3777 "Value of: 2 > 1\n"
3778 " Actual: true\n"
3779 "Expected: false");
3780}
3781
vladlosevfbd53a52009-10-20 21:03:10 +00003782// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3783TEST(AssertionTest, AssertFalseWithAssertionResult) {
3784 ASSERT_FALSE(ResultIsEven(3));
3785 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3786 "Value of: ResultIsEven(2)\n"
3787 " Actual: true (2 is even)\n"
3788 "Expected: false");
3789 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3790 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3791 "Value of: ResultIsEvenNoExplanation(2)\n"
3792 " Actual: true\n"
3793 "Expected: false");
3794}
3795
zhanyong.wan98efcc42009-04-28 00:28:09 +00003796#ifdef __BORLANDC__
3797// Restores warnings after previous "#pragma option push" supressed them
3798#pragma option pop
3799#endif
3800
shiqian4b6829f2008-07-03 22:38:12 +00003801// Tests using ASSERT_EQ on double values. The purpose is to make
3802// sure that the specialization we did for integer and anonymous enums
3803// isn't used for double arguments.
3804TEST(ExpectTest, ASSERT_EQ_Double) {
3805 // A success.
3806 ASSERT_EQ(5.6, 5.6);
3807
3808 // A failure.
3809 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3810 "5.1");
3811}
3812
3813// Tests ASSERT_EQ.
3814TEST(AssertionTest, ASSERT_EQ) {
3815 ASSERT_EQ(5, 2 + 3);
3816 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3817 "Value of: 2*3\n"
3818 " Actual: 6\n"
3819 "Expected: 5");
3820}
3821
3822// Tests ASSERT_EQ(NULL, pointer).
zhanyong.wan4cd62602009-02-23 23:21:55 +00003823#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003824// The NULL-detection template magic fails to compile with
3825// the Nokia compiler and crashes the ARM compiler, hence
3826// not testing on Symbian.
3827TEST(AssertionTest, ASSERT_EQ_NULL) {
3828 // A success.
3829 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003830 // Some older GCC versions may issue a spurious waring in this or the next
3831 // assertion statement. This warning should not be suppressed with
3832 // static_cast since the test verifies the ability to use bare NULL as the
3833 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003834 ASSERT_EQ(NULL, p);
3835
3836 // A failure.
3837 static int n = 0;
3838 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3839 "Value of: &n\n");
3840}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003841#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003842
3843// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3844// treated as a null pointer by the compiler, we need to make sure
3845// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3846// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3847TEST(ExpectTest, ASSERT_EQ_0) {
3848 int n = 0;
3849
3850 // A success.
3851 ASSERT_EQ(0, n);
3852
3853 // A failure.
3854 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3855 "Expected: 0");
3856}
3857
3858// Tests ASSERT_NE.
3859TEST(AssertionTest, ASSERT_NE) {
3860 ASSERT_NE(6, 7);
3861 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3862 "Expected: ('a') != ('a'), "
3863 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3864}
3865
3866// Tests ASSERT_LE.
3867TEST(AssertionTest, ASSERT_LE) {
3868 ASSERT_LE(2, 3);
3869 ASSERT_LE(2, 2);
3870 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3871 "Expected: (2) <= (0), actual: 2 vs 0");
3872}
3873
3874// Tests ASSERT_LT.
3875TEST(AssertionTest, ASSERT_LT) {
3876 ASSERT_LT(2, 3);
3877 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3878 "Expected: (2) < (2), actual: 2 vs 2");
3879}
3880
3881// Tests ASSERT_GE.
3882TEST(AssertionTest, ASSERT_GE) {
3883 ASSERT_GE(2, 1);
3884 ASSERT_GE(2, 2);
3885 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3886 "Expected: (2) >= (3), actual: 2 vs 3");
3887}
3888
3889// Tests ASSERT_GT.
3890TEST(AssertionTest, ASSERT_GT) {
3891 ASSERT_GT(2, 1);
3892 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3893 "Expected: (2) > (2), actual: 2 vs 2");
3894}
3895
shiqian9204c8e2008-09-12 20:57:22 +00003896#if GTEST_HAS_EXCEPTIONS
3897
zhanyong.wanac60cef2009-02-08 04:53:35 +00003898void ThrowNothing() {}
3899
shiqian9204c8e2008-09-12 20:57:22 +00003900// Tests ASSERT_THROW.
3901TEST(AssertionTest, ASSERT_THROW) {
3902 ASSERT_THROW(ThrowAnInteger(), int);
zhanyong.wan98efcc42009-04-28 00:28:09 +00003903#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 || defined(_DEBUG)
3904 // ICE's in C++Builder 2007 (Release build).
zhanyong.wanac60cef2009-02-08 04:53:35 +00003905 EXPECT_FATAL_FAILURE(
3906 ASSERT_THROW(ThrowAnInteger(), bool),
3907 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3908 " Actual: it throws a different type.");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003909#endif
zhanyong.wanac60cef2009-02-08 04:53:35 +00003910 EXPECT_FATAL_FAILURE(
3911 ASSERT_THROW(ThrowNothing(), bool),
3912 "Expected: ThrowNothing() throws an exception of type bool.\n"
3913 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003914}
3915
3916// Tests ASSERT_NO_THROW.
3917TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003918 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003919 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003920 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003921 "\n Actual: it throws.");
3922}
3923
3924// Tests ASSERT_ANY_THROW.
3925TEST(AssertionTest, ASSERT_ANY_THROW) {
3926 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003927 EXPECT_FATAL_FAILURE(
3928 ASSERT_ANY_THROW(ThrowNothing()),
3929 "Expected: ThrowNothing() throws an exception.\n"
3930 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003931}
3932
3933#endif // GTEST_HAS_EXCEPTIONS
3934
shiqian4b6829f2008-07-03 22:38:12 +00003935// Makes sure we deal with the precedence of <<. This test should
3936// compile.
3937TEST(AssertionTest, AssertPrecedence) {
3938 ASSERT_EQ(1 < 2, true);
3939 ASSERT_EQ(true && false, false);
3940}
3941
3942// A subroutine used by the following test.
3943void TestEq1(int x) {
3944 ASSERT_EQ(1, x);
3945}
3946
3947// Tests calling a test subroutine that's not part of a fixture.
3948TEST(AssertionTest, NonFixtureSubroutine) {
3949 EXPECT_FATAL_FAILURE(TestEq1(2),
3950 "Value of: x");
3951}
3952
3953// An uncopyable class.
3954class Uncopyable {
3955 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00003956 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqian4b6829f2008-07-03 22:38:12 +00003957
3958 int value() const { return value_; }
3959 bool operator==(const Uncopyable& rhs) const {
3960 return value() == rhs.value();
3961 }
3962 private:
3963 // This constructor deliberately has no implementation, as we don't
3964 // want this class to be copyable.
3965 Uncopyable(const Uncopyable&); // NOLINT
3966
3967 int value_;
3968};
3969
3970::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3971 return os << value.value();
3972}
3973
3974
3975bool IsPositiveUncopyable(const Uncopyable& x) {
3976 return x.value() > 0;
3977}
3978
3979// A subroutine used by the following test.
3980void TestAssertNonPositive() {
3981 Uncopyable y(-1);
3982 ASSERT_PRED1(IsPositiveUncopyable, y);
3983}
3984// A subroutine used by the following test.
3985void TestAssertEqualsUncopyable() {
3986 Uncopyable x(5);
3987 Uncopyable y(-1);
3988 ASSERT_EQ(x, y);
3989}
3990
3991// Tests that uncopyable objects can be used in assertions.
3992TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3993 Uncopyable x(5);
3994 ASSERT_PRED1(IsPositiveUncopyable, x);
3995 ASSERT_EQ(x, x);
3996 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3997 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3998 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3999 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
4000}
4001
4002// Tests that uncopyable objects can be used in expects.
4003TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
4004 Uncopyable x(5);
4005 EXPECT_PRED1(IsPositiveUncopyable, x);
4006 Uncopyable y(-1);
4007 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
4008 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
4009 EXPECT_EQ(x, x);
4010 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
4011 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
4012}
4013
4014
4015// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00004016// anonymous enums in assertions. Therefore the following test is not
4017// done on Mac.
4018#if !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00004019
4020// Tests using assertions with anonymous enums.
4021enum {
4022 CASE_A = -1,
zhanyong.wan4cd62602009-02-23 23:21:55 +00004023#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00004024 // We want to test the case where the size of the anonymous enum is
4025 // larger than sizeof(int), to make sure our implementation of the
4026 // assertions doesn't truncate the enums. However, MSVC
4027 // (incorrectly) doesn't allow an enum value to exceed the range of
4028 // an int, so this has to be conditionally compiled.
4029 //
4030 // On Linux, CASE_B and CASE_A have the same value when truncated to
4031 // int size. We want to test whether this will confuse the
4032 // assertions.
shiqian760af5c2008-08-06 21:43:15 +00004033 CASE_B = testing::internal::kMaxBiggestInt,
shiqian4b6829f2008-07-03 22:38:12 +00004034#else
4035 CASE_B = INT_MAX,
4036#endif // GTEST_OS_LINUX
4037};
4038
4039TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00004040#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00004041 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
4042#endif // GTEST_OS_LINUX
4043
4044 EXPECT_EQ(CASE_A, CASE_A);
4045 EXPECT_NE(CASE_A, CASE_B);
4046 EXPECT_LT(CASE_A, CASE_B);
4047 EXPECT_LE(CASE_A, CASE_B);
4048 EXPECT_GT(CASE_B, CASE_A);
4049 EXPECT_GE(CASE_A, CASE_A);
4050 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
4051 "(CASE_A) >= (CASE_B)");
4052
4053 ASSERT_EQ(CASE_A, CASE_A);
4054 ASSERT_NE(CASE_A, CASE_B);
4055 ASSERT_LT(CASE_A, CASE_B);
4056 ASSERT_LE(CASE_A, CASE_B);
4057 ASSERT_GT(CASE_B, CASE_A);
4058 ASSERT_GE(CASE_A, CASE_A);
4059 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
4060 "Value of: CASE_B");
4061}
4062
zhanyong.wanefa2fc72009-03-31 16:27:55 +00004063#endif // !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00004064
zhanyong.wan4cd62602009-02-23 23:21:55 +00004065#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00004066
4067static HRESULT UnexpectedHRESULTFailure() {
4068 return E_UNEXPECTED;
4069}
4070
4071static HRESULT OkHRESULTSuccess() {
4072 return S_OK;
4073}
4074
4075static HRESULT FalseHRESULTSuccess() {
4076 return S_FALSE;
4077}
4078
4079// HRESULT assertion tests test both zero and non-zero
4080// success codes as well as failure message for each.
4081//
4082// Windows CE doesn't support message texts.
4083TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4084 EXPECT_HRESULT_SUCCEEDED(S_OK);
4085 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4086
shiqian4b6829f2008-07-03 22:38:12 +00004087 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00004088 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4089 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00004090}
4091
4092TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4093 ASSERT_HRESULT_SUCCEEDED(S_OK);
4094 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4095
shiqian4b6829f2008-07-03 22:38:12 +00004096 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00004097 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4098 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00004099}
4100
4101TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4102 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4103
shiqian4b6829f2008-07-03 22:38:12 +00004104 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00004105 "Expected: (OkHRESULTSuccess()) fails.\n"
4106 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00004107 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00004108 "Expected: (FalseHRESULTSuccess()) fails.\n"
4109 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00004110}
4111
4112TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4113 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4114
zhanyong.wan98efcc42009-04-28 00:28:09 +00004115#ifndef __BORLANDC__
4116 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00004117 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00004118 "Expected: (OkHRESULTSuccess()) fails.\n"
4119 " Actual: 0x00000000");
zhanyong.wan98efcc42009-04-28 00:28:09 +00004120#endif
shiqian4b6829f2008-07-03 22:38:12 +00004121 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00004122 "Expected: (FalseHRESULTSuccess()) fails.\n"
4123 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00004124}
4125
4126// Tests that streaming to the HRESULT macros works.
4127TEST(HRESULTAssertionTest, Streaming) {
4128 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4129 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4130 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4131 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4132
4133 EXPECT_NONFATAL_FAILURE(
4134 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4135 "expected failure");
4136
zhanyong.wan98efcc42009-04-28 00:28:09 +00004137#ifndef __BORLANDC__
4138 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00004139 EXPECT_FATAL_FAILURE(
4140 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4141 "expected failure");
zhanyong.wan98efcc42009-04-28 00:28:09 +00004142#endif
shiqian4b6829f2008-07-03 22:38:12 +00004143
4144 EXPECT_NONFATAL_FAILURE(
4145 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4146 "expected failure");
4147
4148 EXPECT_FATAL_FAILURE(
4149 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4150 "expected failure");
4151}
4152
zhanyong.wan4cd62602009-02-23 23:21:55 +00004153#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00004154
zhanyong.wan98efcc42009-04-28 00:28:09 +00004155#ifdef __BORLANDC__
4156// Silences warnings: "Condition is always true", "Unreachable code"
4157#pragma option push -w-ccc -w-rch
4158#endif
4159
shiqian4b6829f2008-07-03 22:38:12 +00004160// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00004161TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004162 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00004163 ASSERT_TRUE(false) << "This should never be executed; "
4164 "It's a compilation test only.";
4165
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004166 if (AlwaysTrue())
shiqian4b6829f2008-07-03 22:38:12 +00004167 EXPECT_FALSE(false);
4168 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004169 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00004170
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004171 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00004172 ASSERT_LT(1, 3);
4173
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004174 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004175 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00004176 else
4177 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00004178}
shiqian9204c8e2008-09-12 20:57:22 +00004179
4180#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00004181// Tests that the compiler will not complain about unreachable code in the
4182// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4183TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4184 int n = 0;
4185
4186 EXPECT_THROW(throw 1, int);
4187 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4188 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4189 EXPECT_NO_THROW(n++);
4190 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4191 EXPECT_ANY_THROW(throw 1);
4192 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4193}
4194
shiqiane44602e2008-10-11 07:20:02 +00004195TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004196 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004197 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00004198
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004199 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004200 EXPECT_THROW(ThrowAnInteger(), int);
4201 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004202 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004203
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004204 if (AlwaysFalse())
shiqian9204c8e2008-09-12 20:57:22 +00004205 EXPECT_NO_THROW(ThrowAnInteger());
4206
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004207 if (AlwaysTrue())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004208 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004209 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004210 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004211
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004212 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004213 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004214
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004215 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004216 EXPECT_ANY_THROW(ThrowAnInteger());
4217 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004218 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004219}
shiqian9204c8e2008-09-12 20:57:22 +00004220#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00004221
4222TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004223 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004224 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4225 << "It's a compilation test only.";
4226 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004227 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004228
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004229 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004230 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4231 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004232 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004233
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004234 if (AlwaysTrue())
shiqiane44602e2008-10-11 07:20:02 +00004235 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4236 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004237 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004238
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004239 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004240 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004241 else
4242 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00004243}
4244
4245// Tests that the assertion macros work well with switch statements.
4246TEST(AssertionSyntaxTest, WorksWithSwitch) {
4247 switch (0) {
4248 case 1:
4249 break;
4250 default:
4251 ASSERT_TRUE(true);
4252 }
4253
4254 switch (0)
4255 case 0:
4256 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4257
4258 // Binary assertions are implemented using a different code path
4259 // than the Boolean assertions. Hence we test them separately.
4260 switch (0) {
4261 case 1:
4262 default:
4263 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4264 }
4265
4266 switch (0)
4267 case 0:
4268 EXPECT_NE(1, 2);
4269}
4270
shiqian9204c8e2008-09-12 20:57:22 +00004271#if GTEST_HAS_EXCEPTIONS
4272
4273void ThrowAString() {
4274 throw "String";
4275}
4276
4277// Test that the exception assertion macros compile and work with const
4278// type qualifier.
4279TEST(AssertionSyntaxTest, WorksWithConst) {
4280 ASSERT_THROW(ThrowAString(), const char*);
4281
4282 EXPECT_THROW(ThrowAString(), const char*);
4283}
4284
4285#endif // GTEST_HAS_EXCEPTIONS
4286
shiqian4b6829f2008-07-03 22:38:12 +00004287} // namespace
4288
shiqian4b6829f2008-07-03 22:38:12 +00004289namespace testing {
4290
4291// Tests that Google Test tracks SUCCEED*.
4292TEST(SuccessfulAssertionTest, SUCCEED) {
4293 SUCCEED();
4294 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004295 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004296}
4297
4298// Tests that Google Test doesn't track successful EXPECT_*.
4299TEST(SuccessfulAssertionTest, EXPECT) {
4300 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004301 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004302}
4303
4304// Tests that Google Test doesn't track successful EXPECT_STR*.
4305TEST(SuccessfulAssertionTest, EXPECT_STR) {
4306 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004307 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004308}
4309
4310// Tests that Google Test doesn't track successful ASSERT_*.
4311TEST(SuccessfulAssertionTest, ASSERT) {
4312 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004313 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004314}
4315
4316// Tests that Google Test doesn't track successful ASSERT_STR*.
4317TEST(SuccessfulAssertionTest, ASSERT_STR) {
4318 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004319 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004320}
4321
4322} // namespace testing
4323
4324namespace {
4325
4326// Tests EXPECT_TRUE.
4327TEST(ExpectTest, EXPECT_TRUE) {
4328 EXPECT_TRUE(2 > 1); // NOLINT
4329 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4330 "Value of: 2 < 1\n"
4331 " Actual: false\n"
4332 "Expected: true");
4333 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4334 "2 > 3");
4335}
4336
vladlosevfbd53a52009-10-20 21:03:10 +00004337// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4338TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4339 EXPECT_TRUE(ResultIsEven(2));
4340 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4341 "Value of: ResultIsEven(3)\n"
4342 " Actual: false (3 is odd)\n"
4343 "Expected: true");
4344 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4345 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4346 "Value of: ResultIsEvenNoExplanation(3)\n"
4347 " Actual: false (3 is odd)\n"
4348 "Expected: true");
4349}
4350
shiqian4b6829f2008-07-03 22:38:12 +00004351// Tests EXPECT_FALSE.
4352TEST(ExpectTest, EXPECT_FALSE) {
4353 EXPECT_FALSE(2 < 1); // NOLINT
4354 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4355 "Value of: 2 > 1\n"
4356 " Actual: true\n"
4357 "Expected: false");
4358 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4359 "2 < 3");
4360}
4361
vladlosevfbd53a52009-10-20 21:03:10 +00004362// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4363TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4364 EXPECT_FALSE(ResultIsEven(3));
4365 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4366 "Value of: ResultIsEven(2)\n"
4367 " Actual: true (2 is even)\n"
4368 "Expected: false");
4369 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4370 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4371 "Value of: ResultIsEvenNoExplanation(2)\n"
4372 " Actual: true\n"
4373 "Expected: false");
4374}
4375
zhanyong.wan98efcc42009-04-28 00:28:09 +00004376#ifdef __BORLANDC__
4377// Restores warnings after previous "#pragma option push" supressed them
4378#pragma option pop
4379#endif
4380
shiqian4b6829f2008-07-03 22:38:12 +00004381// Tests EXPECT_EQ.
4382TEST(ExpectTest, EXPECT_EQ) {
4383 EXPECT_EQ(5, 2 + 3);
4384 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4385 "Value of: 2*3\n"
4386 " Actual: 6\n"
4387 "Expected: 5");
4388 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4389 "2 - 3");
4390}
4391
4392// Tests using EXPECT_EQ on double values. The purpose is to make
4393// sure that the specialization we did for integer and anonymous enums
4394// isn't used for double arguments.
4395TEST(ExpectTest, EXPECT_EQ_Double) {
4396 // A success.
4397 EXPECT_EQ(5.6, 5.6);
4398
4399 // A failure.
4400 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4401 "5.1");
4402}
4403
zhanyong.wan4cd62602009-02-23 23:21:55 +00004404#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00004405// Tests EXPECT_EQ(NULL, pointer).
4406TEST(ExpectTest, EXPECT_EQ_NULL) {
4407 // A success.
4408 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00004409 // Some older GCC versions may issue a spurious waring in this or the next
4410 // assertion statement. This warning should not be suppressed with
4411 // static_cast since the test verifies the ability to use bare NULL as the
4412 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00004413 EXPECT_EQ(NULL, p);
4414
4415 // A failure.
4416 int n = 0;
4417 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4418 "Value of: &n\n");
4419}
zhanyong.wan4cd62602009-02-23 23:21:55 +00004420#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00004421
4422// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4423// treated as a null pointer by the compiler, we need to make sure
4424// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4425// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4426TEST(ExpectTest, EXPECT_EQ_0) {
4427 int n = 0;
4428
4429 // A success.
4430 EXPECT_EQ(0, n);
4431
4432 // A failure.
4433 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4434 "Expected: 0");
4435}
4436
4437// Tests EXPECT_NE.
4438TEST(ExpectTest, EXPECT_NE) {
4439 EXPECT_NE(6, 7);
4440
4441 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4442 "Expected: ('a') != ('a'), "
4443 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4444 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4445 "2");
4446 char* const p0 = NULL;
4447 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4448 "p0");
4449 // Only way to get the Nokia compiler to compile the cast
4450 // is to have a separate void* variable first. Putting
4451 // the two casts on the same line doesn't work, neither does
4452 // a direct C-style to char*.
4453 void* pv1 = (void*)0x1234; // NOLINT
4454 char* const p1 = reinterpret_cast<char*>(pv1);
4455 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4456 "p1");
4457}
4458
4459// Tests EXPECT_LE.
4460TEST(ExpectTest, EXPECT_LE) {
4461 EXPECT_LE(2, 3);
4462 EXPECT_LE(2, 2);
4463 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4464 "Expected: (2) <= (0), actual: 2 vs 0");
4465 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4466 "(1.1) <= (0.9)");
4467}
4468
4469// Tests EXPECT_LT.
4470TEST(ExpectTest, EXPECT_LT) {
4471 EXPECT_LT(2, 3);
4472 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4473 "Expected: (2) < (2), actual: 2 vs 2");
4474 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4475 "(2) < (1)");
4476}
4477
4478// Tests EXPECT_GE.
4479TEST(ExpectTest, EXPECT_GE) {
4480 EXPECT_GE(2, 1);
4481 EXPECT_GE(2, 2);
4482 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4483 "Expected: (2) >= (3), actual: 2 vs 3");
4484 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4485 "(0.9) >= (1.1)");
4486}
4487
4488// Tests EXPECT_GT.
4489TEST(ExpectTest, EXPECT_GT) {
4490 EXPECT_GT(2, 1);
4491 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4492 "Expected: (2) > (2), actual: 2 vs 2");
4493 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4494 "(2) > (3)");
4495}
4496
shiqian9204c8e2008-09-12 20:57:22 +00004497#if GTEST_HAS_EXCEPTIONS
4498
4499// Tests EXPECT_THROW.
4500TEST(ExpectTest, EXPECT_THROW) {
4501 EXPECT_THROW(ThrowAnInteger(), int);
4502 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004503 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00004504 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00004505 EXPECT_NONFATAL_FAILURE(
4506 EXPECT_THROW(ThrowNothing(), bool),
4507 "Expected: ThrowNothing() throws an exception of type bool.\n"
4508 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00004509}
4510
4511// Tests EXPECT_NO_THROW.
4512TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00004513 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004514 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004515 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00004516 "exception.\n Actual: it throws.");
4517}
4518
4519// Tests EXPECT_ANY_THROW.
4520TEST(ExpectTest, EXPECT_ANY_THROW) {
4521 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004522 EXPECT_NONFATAL_FAILURE(
4523 EXPECT_ANY_THROW(ThrowNothing()),
4524 "Expected: ThrowNothing() throws an exception.\n"
4525 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004526}
4527
4528#endif // GTEST_HAS_EXCEPTIONS
4529
shiqian4b6829f2008-07-03 22:38:12 +00004530// Make sure we deal with the precedence of <<.
4531TEST(ExpectTest, ExpectPrecedence) {
4532 EXPECT_EQ(1 < 2, true);
4533 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4534 "Value of: true && false");
4535}
4536
4537
4538// Tests the StreamableToString() function.
4539
4540// Tests using StreamableToString() on a scalar.
4541TEST(StreamableToStringTest, Scalar) {
4542 EXPECT_STREQ("5", StreamableToString(5).c_str());
4543}
4544
4545// Tests using StreamableToString() on a non-char pointer.
4546TEST(StreamableToStringTest, Pointer) {
4547 int n = 0;
4548 int* p = &n;
4549 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4550}
4551
4552// Tests using StreamableToString() on a NULL non-char pointer.
4553TEST(StreamableToStringTest, NullPointer) {
4554 int* p = NULL;
4555 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4556}
4557
4558// Tests using StreamableToString() on a C string.
4559TEST(StreamableToStringTest, CString) {
4560 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4561}
4562
4563// Tests using StreamableToString() on a NULL C string.
4564TEST(StreamableToStringTest, NullCString) {
4565 char* p = NULL;
4566 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4567}
4568
4569// Tests using streamable values as assertion messages.
4570
shiqian4b6829f2008-07-03 22:38:12 +00004571// Tests using std::string as an assertion message.
4572TEST(StreamableTest, string) {
4573 static const std::string str(
4574 "This failure message is a std::string, and is expected.");
4575 EXPECT_FATAL_FAILURE(FAIL() << str,
4576 str.c_str());
4577}
4578
4579// Tests that we can output strings containing embedded NULs.
4580// Limited to Linux because we can only do this with std::string's.
4581TEST(StreamableTest, stringWithEmbeddedNUL) {
4582 static const char char_array_with_nul[] =
4583 "Here's a NUL\0 and some more string";
4584 static const std::string string_with_nul(char_array_with_nul,
4585 sizeof(char_array_with_nul)
4586 - 1); // drops the trailing NUL
4587 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4588 "Here's a NUL\\0 and some more string");
4589}
4590
shiqian4b6829f2008-07-03 22:38:12 +00004591// Tests that we can output a NUL char.
4592TEST(StreamableTest, NULChar) {
4593 EXPECT_FATAL_FAILURE({ // NOLINT
4594 FAIL() << "A NUL" << '\0' << " and some more string";
4595 }, "A NUL\\0 and some more string");
4596}
4597
4598// Tests using int as an assertion message.
4599TEST(StreamableTest, int) {
4600 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4601 "900913");
4602}
4603
4604// Tests using NULL char pointer as an assertion message.
4605//
4606// In MSVC, streaming a NULL char * causes access violation. Google Test
4607// implemented a workaround (substituting "(null)" for NULL). This
4608// tests whether the workaround works.
4609TEST(StreamableTest, NullCharPtr) {
4610 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4611 "(null)");
4612}
4613
4614// Tests that basic IO manipulators (endl, ends, and flush) can be
4615// streamed to testing::Message.
4616TEST(StreamableTest, BasicIoManip) {
4617 EXPECT_FATAL_FAILURE({ // NOLINT
4618 FAIL() << "Line 1." << std::endl
4619 << "A NUL char " << std::ends << std::flush << " in line 2.";
4620 }, "Line 1.\nA NUL char \\0 in line 2.");
4621}
4622
shiqian4b6829f2008-07-03 22:38:12 +00004623// Tests the macros that haven't been covered so far.
4624
4625void AddFailureHelper(bool* aborted) {
4626 *aborted = true;
4627 ADD_FAILURE() << "Failure";
4628 *aborted = false;
4629}
4630
4631// Tests ADD_FAILURE.
4632TEST(MacroTest, ADD_FAILURE) {
4633 bool aborted = true;
4634 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4635 "Failure");
4636 EXPECT_FALSE(aborted);
4637}
4638
4639// Tests FAIL.
4640TEST(MacroTest, FAIL) {
4641 EXPECT_FATAL_FAILURE(FAIL(),
4642 "Failed");
4643 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4644 "Intentional failure.");
4645}
4646
4647// Tests SUCCEED
4648TEST(MacroTest, SUCCEED) {
4649 SUCCEED();
4650 SUCCEED() << "Explicit success.";
4651}
4652
4653
4654// Tests for EXPECT_EQ() and ASSERT_EQ().
4655//
4656// These tests fail *intentionally*, s.t. the failure messages can be
4657// generated and tested.
4658//
4659// We have different tests for different argument types.
4660
4661// Tests using bool values in {EXPECT|ASSERT}_EQ.
4662TEST(EqAssertionTest, Bool) {
4663 EXPECT_EQ(true, true);
4664 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4665 "Value of: true");
4666}
4667
4668// Tests using int values in {EXPECT|ASSERT}_EQ.
4669TEST(EqAssertionTest, Int) {
4670 ASSERT_EQ(32, 32);
4671 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4672 "33");
4673}
4674
4675// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4676TEST(EqAssertionTest, Time_T) {
4677 EXPECT_EQ(static_cast<time_t>(0),
4678 static_cast<time_t>(0));
4679 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4680 static_cast<time_t>(1234)),
4681 "1234");
4682}
4683
4684// Tests using char values in {EXPECT|ASSERT}_EQ.
4685TEST(EqAssertionTest, Char) {
4686 ASSERT_EQ('z', 'z');
4687 const char ch = 'b';
4688 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4689 "ch");
4690 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4691 "ch");
4692}
4693
4694// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4695TEST(EqAssertionTest, WideChar) {
4696 EXPECT_EQ(L'b', L'b');
4697
4698 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4699 "Value of: L'x'\n"
4700 " Actual: L'x' (120, 0x78)\n"
4701 "Expected: L'\0'\n"
4702 "Which is: L'\0' (0, 0x0)");
4703
4704 static wchar_t wchar;
4705 wchar = L'b';
4706 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4707 "wchar");
4708 wchar = L'\x8119';
4709 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4710 "Value of: wchar");
4711}
4712
shiqian4b6829f2008-07-03 22:38:12 +00004713// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4714TEST(EqAssertionTest, StdString) {
4715 // Compares a const char* to an std::string that has identical
4716 // content.
4717 ASSERT_EQ("Test", ::std::string("Test"));
4718
4719 // Compares two identical std::strings.
4720 static const ::std::string str1("A * in the middle");
4721 static const ::std::string str2(str1);
4722 EXPECT_EQ(str1, str2);
4723
4724 // Compares a const char* to an std::string that has different
4725 // content
4726 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4727 "::std::string(\"test\")");
4728
4729 // Compares an std::string to a char* that has different content.
4730 char* const p1 = const_cast<char*>("foo");
4731 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4732 "p1");
4733
4734 // Compares two std::strings that have different contents, one of
4735 // which having a NUL character in the middle. This should fail.
4736 static ::std::string str3(str1);
4737 str3.at(2) = '\0';
4738 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4739 "Value of: str3\n"
4740 " Actual: \"A \\0 in the middle\"");
4741}
4742
shiqian4b6829f2008-07-03 22:38:12 +00004743#if GTEST_HAS_STD_WSTRING
4744
4745// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4746TEST(EqAssertionTest, StdWideString) {
4747 // Compares an std::wstring to a const wchar_t* that has identical
4748 // content.
4749 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4750
4751 // Compares two identical std::wstrings.
4752 const ::std::wstring wstr1(L"A * in the middle");
4753 const ::std::wstring wstr2(wstr1);
4754 ASSERT_EQ(wstr1, wstr2);
4755
4756 // Compares an std::wstring to a const wchar_t* that has different
4757 // content.
4758 EXPECT_NONFATAL_FAILURE({ // NOLINT
4759 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4760 }, "L\"Test\\x8120\"");
4761
4762 // Compares two std::wstrings that have different contents, one of
4763 // which having a NUL character in the middle.
4764 ::std::wstring wstr3(wstr1);
4765 wstr3.at(2) = L'\0';
4766 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4767 "wstr3");
4768
4769 // Compares a wchar_t* to an std::wstring that has different
4770 // content.
4771 EXPECT_FATAL_FAILURE({ // NOLINT
4772 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4773 }, "");
4774}
4775
4776#endif // GTEST_HAS_STD_WSTRING
4777
4778#if GTEST_HAS_GLOBAL_STRING
4779// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4780TEST(EqAssertionTest, GlobalString) {
4781 // Compares a const char* to a ::string that has identical content.
4782 EXPECT_EQ("Test", ::string("Test"));
4783
4784 // Compares two identical ::strings.
4785 const ::string str1("A * in the middle");
4786 const ::string str2(str1);
4787 ASSERT_EQ(str1, str2);
4788
4789 // Compares a ::string to a const char* that has different content.
4790 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4791 "test");
4792
4793 // Compares two ::strings that have different contents, one of which
4794 // having a NUL character in the middle.
4795 ::string str3(str1);
4796 str3.at(2) = '\0';
4797 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4798 "str3");
4799
4800 // Compares a ::string to a char* that has different content.
4801 EXPECT_FATAL_FAILURE({ // NOLINT
4802 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4803 }, "");
4804}
4805
4806#endif // GTEST_HAS_GLOBAL_STRING
4807
4808#if GTEST_HAS_GLOBAL_WSTRING
4809
4810// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4811TEST(EqAssertionTest, GlobalWideString) {
4812 // Compares a const wchar_t* to a ::wstring that has identical content.
4813 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4814
4815 // Compares two identical ::wstrings.
4816 static const ::wstring wstr1(L"A * in the middle");
4817 static const ::wstring wstr2(wstr1);
4818 EXPECT_EQ(wstr1, wstr2);
4819
4820 // Compares a const wchar_t* to a ::wstring that has different
4821 // content.
4822 EXPECT_NONFATAL_FAILURE({ // NOLINT
4823 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4824 }, "Test\\x8119");
4825
4826 // Compares a wchar_t* to a ::wstring that has different content.
4827 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4828 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4829 "bar");
4830
4831 // Compares two ::wstrings that have different contents, one of which
4832 // having a NUL character in the middle.
4833 static ::wstring wstr3;
4834 wstr3 = wstr1;
4835 wstr3.at(2) = L'\0';
4836 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4837 "wstr3");
4838}
4839
4840#endif // GTEST_HAS_GLOBAL_WSTRING
4841
4842// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4843TEST(EqAssertionTest, CharPointer) {
4844 char* const p0 = NULL;
4845 // Only way to get the Nokia compiler to compile the cast
4846 // is to have a separate void* variable first. Putting
4847 // the two casts on the same line doesn't work, neither does
4848 // a direct C-style to char*.
4849 void* pv1 = (void*)0x1234; // NOLINT
4850 void* pv2 = (void*)0xABC0; // NOLINT
4851 char* const p1 = reinterpret_cast<char*>(pv1);
4852 char* const p2 = reinterpret_cast<char*>(pv2);
4853 ASSERT_EQ(p1, p1);
4854
4855 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4856 "Value of: p2");
4857 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4858 "p2");
4859 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4860 reinterpret_cast<char*>(0xABC0)),
4861 "ABC0");
4862}
4863
4864// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4865TEST(EqAssertionTest, WideCharPointer) {
4866 wchar_t* const p0 = NULL;
4867 // Only way to get the Nokia compiler to compile the cast
4868 // is to have a separate void* variable first. Putting
4869 // the two casts on the same line doesn't work, neither does
4870 // a direct C-style to char*.
4871 void* pv1 = (void*)0x1234; // NOLINT
4872 void* pv2 = (void*)0xABC0; // NOLINT
4873 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4874 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4875 EXPECT_EQ(p0, p0);
4876
4877 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4878 "Value of: p2");
4879 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4880 "p2");
4881 void* pv3 = (void*)0x1234; // NOLINT
4882 void* pv4 = (void*)0xABC0; // NOLINT
4883 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4884 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4885 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4886 "p4");
4887}
4888
4889// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4890TEST(EqAssertionTest, OtherPointer) {
4891 ASSERT_EQ(static_cast<const int*>(NULL),
4892 static_cast<const int*>(NULL));
4893 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4894 reinterpret_cast<const int*>(0x1234)),
4895 "0x1234");
4896}
4897
4898// Tests the FRIEND_TEST macro.
4899
4900// This class has a private member we want to test. We will test it
4901// both in a TEST and in a TEST_F.
4902class Foo {
4903 public:
4904 Foo() {}
4905
4906 private:
4907 int Bar() const { return 1; }
4908
4909 // Declares the friend tests that can access the private member
4910 // Bar().
4911 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4912 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4913};
4914
4915// Tests that the FRIEND_TEST declaration allows a TEST to access a
4916// class's private members. This should compile.
4917TEST(FRIEND_TEST_Test, TEST) {
4918 ASSERT_EQ(1, Foo().Bar());
4919}
4920
4921// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004922class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004923 protected:
4924 Foo foo;
4925};
4926
4927// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4928// class's private members. This should compile.
4929TEST_F(FRIEND_TEST_Test2, TEST_F) {
4930 ASSERT_EQ(1, foo.Bar());
4931}
4932
4933// Tests the life cycle of Test objects.
4934
4935// The test fixture for testing the life cycle of Test objects.
4936//
4937// This class counts the number of live test objects that uses this
4938// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004939class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004940 protected:
4941 // Constructor. Increments the number of test objects that uses
4942 // this fixture.
4943 TestLifeCycleTest() { count_++; }
4944
4945 // Destructor. Decrements the number of test objects that uses this
4946 // fixture.
4947 ~TestLifeCycleTest() { count_--; }
4948
4949 // Returns the number of live test objects that uses this fixture.
4950 int count() const { return count_; }
4951
4952 private:
4953 static int count_;
4954};
4955
4956int TestLifeCycleTest::count_ = 0;
4957
4958// Tests the life cycle of test objects.
4959TEST_F(TestLifeCycleTest, Test1) {
4960 // There should be only one test object in this test case that's
4961 // currently alive.
4962 ASSERT_EQ(1, count());
4963}
4964
4965// Tests the life cycle of test objects.
4966TEST_F(TestLifeCycleTest, Test2) {
4967 // After Test1 is done and Test2 is started, there should still be
4968 // only one live test object, as the object for Test1 should've been
4969 // deleted.
4970 ASSERT_EQ(1, count());
4971}
4972
4973} // namespace
4974
vladlosevfbd53a52009-10-20 21:03:10 +00004975// Tests that the copy constructor works when it is NOT optimized away by
4976// the compiler.
4977TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
4978 // Checks that the copy constructor doesn't try to dereference NULL pointers
4979 // in the source object.
4980 AssertionResult r1 = AssertionSuccess();
4981 AssertionResult r2 = r1;
4982 // The following line is added to prevent the compiler from optimizing
4983 // away the constructor call.
4984 r1 << "abc";
4985
4986 AssertionResult r3 = r1;
4987 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
4988 EXPECT_STREQ("abc", r1.message());
4989}
4990
4991// Tests that AssertionSuccess and AssertionFailure construct
4992// AssertionResult objects as expected.
4993TEST(AssertionResultTest, ConstructionWorks) {
4994 AssertionResult r1 = AssertionSuccess();
4995 EXPECT_TRUE(r1);
4996 EXPECT_STREQ("", r1.message());
4997
4998 AssertionResult r2 = AssertionSuccess() << "abc";
4999 EXPECT_TRUE(r2);
5000 EXPECT_STREQ("abc", r2.message());
5001
5002 AssertionResult r3 = AssertionFailure();
5003 EXPECT_FALSE(r3);
5004 EXPECT_STREQ("", r3.message());
5005
5006 AssertionResult r4 = AssertionFailure() << "def";
5007 EXPECT_FALSE(r4);
5008 EXPECT_STREQ("def", r4.message());
5009
5010 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5011 EXPECT_FALSE(r5);
5012 EXPECT_STREQ("ghi", r5.message());
5013}
5014
5015// Tests that the negation fips the predicate result but keeps the message.
5016TEST(AssertionResultTest, NegationWorks) {
5017 AssertionResult r1 = AssertionSuccess() << "abc";
5018 EXPECT_FALSE(!r1);
5019 EXPECT_STREQ("abc", (!r1).message());
5020
5021 AssertionResult r2 = AssertionFailure() << "def";
5022 EXPECT_TRUE(!r2);
5023 EXPECT_STREQ("def", (!r2).message());
5024}
5025
5026TEST(AssertionResultTest, StreamingWorks) {
5027 AssertionResult r = AssertionSuccess();
5028 r << "abc" << 'd' << 0 << true;
5029 EXPECT_STREQ("abcd0true", r.message());
5030}
5031
shiqian4b6829f2008-07-03 22:38:12 +00005032// Tests streaming a user type whose definition and operator << are
5033// both in the global namespace.
5034class Base {
5035 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005036 explicit Base(int an_x) : x_(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005037 int x() const { return x_; }
5038 private:
5039 int x_;
5040};
5041std::ostream& operator<<(std::ostream& os,
5042 const Base& val) {
5043 return os << val.x();
5044}
5045std::ostream& operator<<(std::ostream& os,
5046 const Base* pointer) {
5047 return os << "(" << pointer->x() << ")";
5048}
5049
5050TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005051 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005052 Base a(1);
5053
5054 msg << a << &a; // Uses ::operator<<.
5055 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5056}
5057
5058// Tests streaming a user type whose definition and operator<< are
5059// both in an unnamed namespace.
5060namespace {
5061class MyTypeInUnnamedNameSpace : public Base {
5062 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005063 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005064};
5065std::ostream& operator<<(std::ostream& os,
5066 const MyTypeInUnnamedNameSpace& val) {
5067 return os << val.x();
5068}
5069std::ostream& operator<<(std::ostream& os,
5070 const MyTypeInUnnamedNameSpace* pointer) {
5071 return os << "(" << pointer->x() << ")";
5072}
5073} // namespace
5074
5075TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005076 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005077 MyTypeInUnnamedNameSpace a(1);
5078
5079 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5080 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5081}
5082
5083// Tests streaming a user type whose definition and operator<< are
5084// both in a user namespace.
5085namespace namespace1 {
5086class MyTypeInNameSpace1 : public Base {
5087 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005088 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005089};
5090std::ostream& operator<<(std::ostream& os,
5091 const MyTypeInNameSpace1& val) {
5092 return os << val.x();
5093}
5094std::ostream& operator<<(std::ostream& os,
5095 const MyTypeInNameSpace1* pointer) {
5096 return os << "(" << pointer->x() << ")";
5097}
5098} // namespace namespace1
5099
5100TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005101 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005102 namespace1::MyTypeInNameSpace1 a(1);
5103
5104 msg << a << &a; // Uses namespace1::operator<<.
5105 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5106}
5107
5108// Tests streaming a user type whose definition is in a user namespace
5109// but whose operator<< is in the global namespace.
5110namespace namespace2 {
5111class MyTypeInNameSpace2 : public ::Base {
5112 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005113 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005114};
5115} // namespace namespace2
5116std::ostream& operator<<(std::ostream& os,
5117 const namespace2::MyTypeInNameSpace2& val) {
5118 return os << val.x();
5119}
5120std::ostream& operator<<(std::ostream& os,
5121 const namespace2::MyTypeInNameSpace2* pointer) {
5122 return os << "(" << pointer->x() << ")";
5123}
5124
5125TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00005126 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005127 namespace2::MyTypeInNameSpace2 a(1);
5128
5129 msg << a << &a; // Uses ::operator<<.
5130 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5131}
5132
5133// Tests streaming NULL pointers to testing::Message.
5134TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00005135 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005136 char* const p1 = NULL;
5137 unsigned char* const p2 = NULL;
5138 int* p3 = NULL;
5139 double* p4 = NULL;
5140 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00005141 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005142
5143 msg << p1 << p2 << p3 << p4 << p5 << p6;
5144 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5145 msg.GetString().c_str());
5146}
5147
5148// Tests streaming wide strings to testing::Message.
5149TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00005150 // Streams a NULL of type const wchar_t*.
5151 const wchar_t* const_wstr = NULL;
5152 EXPECT_STREQ("(null)",
5153 (Message() << const_wstr).GetString().c_str());
5154
5155 // Streams a NULL of type wchar_t*.
5156 wchar_t* wstr = NULL;
5157 EXPECT_STREQ("(null)",
5158 (Message() << wstr).GetString().c_str());
5159
5160 // Streams a non-NULL of type const wchar_t*.
5161 const_wstr = L"abc\x8119";
5162 EXPECT_STREQ("abc\xe8\x84\x99",
5163 (Message() << const_wstr).GetString().c_str());
5164
5165 // Streams a non-NULL of type wchar_t*.
5166 wstr = const_cast<wchar_t*>(const_wstr);
5167 EXPECT_STREQ("abc\xe8\x84\x99",
5168 (Message() << wstr).GetString().c_str());
5169}
5170
5171
5172// This line tests that we can define tests in the testing namespace.
5173namespace testing {
5174
5175// Tests the TestInfo class.
5176
shiqian760af5c2008-08-06 21:43:15 +00005177class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005178 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005179 static const TestInfo* GetTestInfo(const char* test_name) {
5180 const TestCase* const test_case = GetUnitTestImpl()->
5181 GetTestCase("TestInfoTest", "", NULL, NULL);
5182
5183 for (int i = 0; i < test_case->total_test_count(); ++i) {
5184 const TestInfo* const test_info = test_case->GetTestInfo(i);
5185 if (strcmp(test_name, test_info->name()) == 0)
5186 return test_info;
5187 }
5188 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005189 }
5190
5191 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00005192 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00005193 return test_info->result();
5194 }
5195};
5196
5197// Tests TestInfo::test_case_name() and TestInfo::name().
5198TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005199 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00005200
5201 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5202 ASSERT_STREQ("Names", test_info->name());
5203}
5204
5205// Tests TestInfo::result().
5206TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005207 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00005208
5209 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005210 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005211
5212 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005213 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005214}
5215
5216// Tests setting up and tearing down a test case.
5217
shiqian760af5c2008-08-06 21:43:15 +00005218class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005219 protected:
5220 // This will be called once before the first test in this test case
5221 // is run.
5222 static void SetUpTestCase() {
5223 printf("Setting up the test case . . .\n");
5224
5225 // Initializes some shared resource. In this simple example, we
5226 // just create a C string. More complex stuff can be done if
5227 // desired.
5228 shared_resource_ = "123";
5229
5230 // Increments the number of test cases that have been set up.
5231 counter_++;
5232
5233 // SetUpTestCase() should be called only once.
5234 EXPECT_EQ(1, counter_);
5235 }
5236
5237 // This will be called once after the last test in this test case is
5238 // run.
5239 static void TearDownTestCase() {
5240 printf("Tearing down the test case . . .\n");
5241
5242 // Decrements the number of test cases that have been set up.
5243 counter_--;
5244
5245 // TearDownTestCase() should be called only once.
5246 EXPECT_EQ(0, counter_);
5247
5248 // Cleans up the shared resource.
5249 shared_resource_ = NULL;
5250 }
5251
5252 // This will be called before each test in this test case.
5253 virtual void SetUp() {
5254 // SetUpTestCase() should be called only once, so counter_ should
5255 // always be 1.
5256 EXPECT_EQ(1, counter_);
5257 }
5258
5259 // Number of test cases that have been set up.
5260 static int counter_;
5261
5262 // Some resource to be shared by all tests in this test case.
5263 static const char* shared_resource_;
5264};
5265
5266int SetUpTestCaseTest::counter_ = 0;
5267const char* SetUpTestCaseTest::shared_resource_ = NULL;
5268
5269// A test that uses the shared resource.
5270TEST_F(SetUpTestCaseTest, Test1) {
5271 EXPECT_STRNE(NULL, shared_resource_);
5272}
5273
5274// Another test that uses the shared resource.
5275TEST_F(SetUpTestCaseTest, Test2) {
5276 EXPECT_STREQ("123", shared_resource_);
5277}
5278
5279// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5280
5281// The Flags struct stores a copy of all Google Test flags.
5282struct Flags {
5283 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00005284 Flags() : also_run_disabled_tests(false),
5285 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00005286 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00005287 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00005288 filter(""),
5289 list_tests(false),
5290 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005291 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005292 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005293 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005294 shuffle(false),
vladlosevba015a92009-11-17 22:43:15 +00005295 stack_trace_depth(kMaxStackTraceDepth),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005296 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00005297
5298 // Factory methods.
5299
shiqianca6949f2009-01-10 01:16:33 +00005300 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5301 // the given value.
5302 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5303 Flags flags;
5304 flags.also_run_disabled_tests = also_run_disabled_tests;
5305 return flags;
5306 }
5307
shiqian4b6829f2008-07-03 22:38:12 +00005308 // Creates a Flags struct where the gtest_break_on_failure flag has
5309 // the given value.
5310 static Flags BreakOnFailure(bool break_on_failure) {
5311 Flags flags;
5312 flags.break_on_failure = break_on_failure;
5313 return flags;
5314 }
5315
5316 // Creates a Flags struct where the gtest_catch_exceptions flag has
5317 // the given value.
5318 static Flags CatchExceptions(bool catch_exceptions) {
5319 Flags flags;
5320 flags.catch_exceptions = catch_exceptions;
5321 return flags;
5322 }
5323
shiqian21d43d12009-01-08 01:10:31 +00005324 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5325 // the given value.
5326 static Flags DeathTestUseFork(bool death_test_use_fork) {
5327 Flags flags;
5328 flags.death_test_use_fork = death_test_use_fork;
5329 return flags;
5330 }
5331
shiqian4b6829f2008-07-03 22:38:12 +00005332 // Creates a Flags struct where the gtest_filter flag has the given
5333 // value.
5334 static Flags Filter(const char* filter) {
5335 Flags flags;
5336 flags.filter = filter;
5337 return flags;
5338 }
5339
5340 // Creates a Flags struct where the gtest_list_tests flag has the
5341 // given value.
5342 static Flags ListTests(bool list_tests) {
5343 Flags flags;
5344 flags.list_tests = list_tests;
5345 return flags;
5346 }
5347
5348 // Creates a Flags struct where the gtest_output flag has the given
5349 // value.
5350 static Flags Output(const char* output) {
5351 Flags flags;
5352 flags.output = output;
5353 return flags;
5354 }
5355
shiqiand981cee2008-07-25 04:06:16 +00005356 // Creates a Flags struct where the gtest_print_time flag has the given
5357 // value.
5358 static Flags PrintTime(bool print_time) {
5359 Flags flags;
5360 flags.print_time = print_time;
5361 return flags;
5362 }
5363
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005364 // Creates a Flags struct where the gtest_random_seed flag has
5365 // the given value.
5366 static Flags RandomSeed(Int32 random_seed) {
5367 Flags flags;
5368 flags.random_seed = random_seed;
5369 return flags;
5370 }
5371
shiqian4b6829f2008-07-03 22:38:12 +00005372 // Creates a Flags struct where the gtest_repeat flag has the given
5373 // value.
5374 static Flags Repeat(Int32 repeat) {
5375 Flags flags;
5376 flags.repeat = repeat;
5377 return flags;
5378 }
5379
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005380 // Creates a Flags struct where the gtest_shuffle flag has
5381 // the given value.
5382 static Flags Shuffle(bool shuffle) {
5383 Flags flags;
5384 flags.shuffle = shuffle;
5385 return flags;
5386 }
5387
vladlosevba015a92009-11-17 22:43:15 +00005388 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5389 // the given value.
5390 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5391 Flags flags;
5392 flags.stack_trace_depth = stack_trace_depth;
5393 return flags;
5394 }
5395
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005396 // Creates a Flags struct where the gtest_throw_on_failure flag has
5397 // the given value.
5398 static Flags ThrowOnFailure(bool throw_on_failure) {
5399 Flags flags;
5400 flags.throw_on_failure = throw_on_failure;
5401 return flags;
5402 }
5403
shiqian4b6829f2008-07-03 22:38:12 +00005404 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00005405 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00005406 bool break_on_failure;
5407 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00005408 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00005409 const char* filter;
5410 bool list_tests;
5411 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00005412 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005413 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00005414 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005415 bool shuffle;
vladlosevba015a92009-11-17 22:43:15 +00005416 Int32 stack_trace_depth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005417 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00005418};
5419
5420// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00005421class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005422 protected:
5423 // Clears the flags before each test.
5424 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00005425 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005426 GTEST_FLAG(break_on_failure) = false;
5427 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00005428 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005429 GTEST_FLAG(filter) = "";
5430 GTEST_FLAG(list_tests) = false;
5431 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005432 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005433 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00005434 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005435 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00005436 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005437 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005438 }
5439
5440 // Asserts that two narrow or wide string arrays are equal.
5441 template <typename CharType>
5442 static void AssertStringArrayEq(size_t size1, CharType** array1,
5443 size_t size2, CharType** array2) {
5444 ASSERT_EQ(size1, size2) << " Array sizes different.";
5445
5446 for (size_t i = 0; i != size1; i++) {
5447 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5448 }
5449 }
5450
5451 // Verifies that the flag values match the expected values.
5452 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00005453 EXPECT_EQ(expected.also_run_disabled_tests,
5454 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00005455 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5456 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00005457 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00005458 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5459 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5460 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00005461 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005462 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00005463 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005464 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005465 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
vladlosevba015a92009-11-17 22:43:15 +00005466 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
shiqian4b6829f2008-07-03 22:38:12 +00005467 }
5468
5469 // Parses a command line (specified by argc1 and argv1), then
5470 // verifies that the flag values are expected and that the
5471 // recognized flags are removed from the command line.
5472 template <typename CharType>
5473 static void TestParsingFlags(int argc1, const CharType** argv1,
5474 int argc2, const CharType** argv2,
vladlosevba015a92009-11-17 22:43:15 +00005475 const Flags& expected, bool should_print_help) {
5476 const bool saved_help_flag = ::testing::internal::g_help_flag;
5477 ::testing::internal::g_help_flag = false;
5478
zhanyong.wancf8a5842010-01-28 21:50:29 +00005479#if GTEST_HAS_STREAM_REDIRECTION_
5480 CaptureStdout();
5481#endif // GTEST_HAS_STREAM_REDIRECTION_
5482
shiqian4b6829f2008-07-03 22:38:12 +00005483 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00005484 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00005485
zhanyong.wancf8a5842010-01-28 21:50:29 +00005486#if GTEST_HAS_STREAM_REDIRECTION_
5487 const String captured_stdout = GetCapturedStdout();
5488#endif // GTEST_HAS_STREAM_REDIRECTION_
5489
shiqian4b6829f2008-07-03 22:38:12 +00005490 // Verifies the flag values.
5491 CheckFlags(expected);
5492
5493 // Verifies that the recognized flags are removed from the command
5494 // line.
5495 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
vladlosevba015a92009-11-17 22:43:15 +00005496
5497 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5498 // help message for the flags it recognizes.
5499 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5500
zhanyong.wancf8a5842010-01-28 21:50:29 +00005501#if GTEST_HAS_STREAM_REDIRECTION_
5502 const char* const expected_help_fragment =
5503 "This program contains tests written using";
5504 if (should_print_help) {
5505 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5506 } else {
5507 EXPECT_PRED_FORMAT2(IsNotSubstring,
5508 expected_help_fragment, captured_stdout);
5509 }
5510#endif // GTEST_HAS_STREAM_REDIRECTION_
vladlosevba015a92009-11-17 22:43:15 +00005511
5512 ::testing::internal::g_help_flag = saved_help_flag;
shiqian4b6829f2008-07-03 22:38:12 +00005513 }
5514
5515 // This macro wraps TestParsingFlags s.t. the user doesn't need
5516 // to specify the array sizes.
vladlosevba015a92009-11-17 22:43:15 +00005517#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
shiqian4b6829f2008-07-03 22:38:12 +00005518 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
vladlosevba015a92009-11-17 22:43:15 +00005519 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5520 expected, should_print_help)
shiqian4b6829f2008-07-03 22:38:12 +00005521};
5522
5523// Tests parsing an empty command line.
5524TEST_F(InitGoogleTestTest, Empty) {
5525 const char* argv[] = {
5526 NULL
5527 };
5528
5529 const char* argv2[] = {
5530 NULL
5531 };
5532
vladlosevba015a92009-11-17 22:43:15 +00005533 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005534}
5535
5536// Tests parsing a command line that has no flag.
5537TEST_F(InitGoogleTestTest, NoFlag) {
5538 const char* argv[] = {
5539 "foo.exe",
5540 NULL
5541 };
5542
5543 const char* argv2[] = {
5544 "foo.exe",
5545 NULL
5546 };
5547
vladlosevba015a92009-11-17 22:43:15 +00005548 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005549}
5550
5551// Tests parsing a bad --gtest_filter flag.
5552TEST_F(InitGoogleTestTest, FilterBad) {
5553 const char* argv[] = {
5554 "foo.exe",
5555 "--gtest_filter",
5556 NULL
5557 };
5558
5559 const char* argv2[] = {
5560 "foo.exe",
5561 "--gtest_filter",
5562 NULL
5563 };
5564
vladlosevba015a92009-11-17 22:43:15 +00005565 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
shiqian4b6829f2008-07-03 22:38:12 +00005566}
5567
5568// Tests parsing an empty --gtest_filter flag.
5569TEST_F(InitGoogleTestTest, FilterEmpty) {
5570 const char* argv[] = {
5571 "foo.exe",
5572 "--gtest_filter=",
5573 NULL
5574 };
5575
5576 const char* argv2[] = {
5577 "foo.exe",
5578 NULL
5579 };
5580
vladlosevba015a92009-11-17 22:43:15 +00005581 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
shiqian4b6829f2008-07-03 22:38:12 +00005582}
5583
5584// Tests parsing a non-empty --gtest_filter flag.
5585TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5586 const char* argv[] = {
5587 "foo.exe",
5588 "--gtest_filter=abc",
5589 NULL
5590 };
5591
5592 const char* argv2[] = {
5593 "foo.exe",
5594 NULL
5595 };
5596
vladlosevba015a92009-11-17 22:43:15 +00005597 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005598}
5599
5600// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005601TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00005602 const char* argv[] = {
5603 "foo.exe",
5604 "--gtest_break_on_failure",
5605 NULL
5606};
5607
5608 const char* argv2[] = {
5609 "foo.exe",
5610 NULL
5611 };
5612
vladlosevba015a92009-11-17 22:43:15 +00005613 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005614}
5615
5616// Tests parsing --gtest_break_on_failure=0.
5617TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5618 const char* argv[] = {
5619 "foo.exe",
5620 "--gtest_break_on_failure=0",
5621 NULL
5622 };
5623
5624 const char* argv2[] = {
5625 "foo.exe",
5626 NULL
5627 };
5628
vladlosevba015a92009-11-17 22:43:15 +00005629 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005630}
5631
5632// Tests parsing --gtest_break_on_failure=f.
5633TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5634 const char* argv[] = {
5635 "foo.exe",
5636 "--gtest_break_on_failure=f",
5637 NULL
5638 };
5639
5640 const char* argv2[] = {
5641 "foo.exe",
5642 NULL
5643 };
5644
vladlosevba015a92009-11-17 22:43:15 +00005645 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005646}
5647
5648// Tests parsing --gtest_break_on_failure=F.
5649TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5650 const char* argv[] = {
5651 "foo.exe",
5652 "--gtest_break_on_failure=F",
5653 NULL
5654 };
5655
5656 const char* argv2[] = {
5657 "foo.exe",
5658 NULL
5659 };
5660
vladlosevba015a92009-11-17 22:43:15 +00005661 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005662}
5663
5664// Tests parsing a --gtest_break_on_failure flag that has a "true"
5665// definition.
5666TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5667 const char* argv[] = {
5668 "foo.exe",
5669 "--gtest_break_on_failure=1",
5670 NULL
5671 };
5672
5673 const char* argv2[] = {
5674 "foo.exe",
5675 NULL
5676 };
5677
vladlosevba015a92009-11-17 22:43:15 +00005678 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005679}
5680
5681// Tests parsing --gtest_catch_exceptions.
5682TEST_F(InitGoogleTestTest, CatchExceptions) {
5683 const char* argv[] = {
5684 "foo.exe",
5685 "--gtest_catch_exceptions",
5686 NULL
5687 };
5688
5689 const char* argv2[] = {
5690 "foo.exe",
5691 NULL
5692 };
5693
vladlosevba015a92009-11-17 22:43:15 +00005694 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005695}
5696
shiqian21d43d12009-01-08 01:10:31 +00005697// Tests parsing --gtest_death_test_use_fork.
5698TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5699 const char* argv[] = {
5700 "foo.exe",
5701 "--gtest_death_test_use_fork",
5702 NULL
5703 };
5704
5705 const char* argv2[] = {
5706 "foo.exe",
5707 NULL
5708 };
5709
vladlosevba015a92009-11-17 22:43:15 +00005710 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
shiqian21d43d12009-01-08 01:10:31 +00005711}
5712
shiqian4b6829f2008-07-03 22:38:12 +00005713// Tests having the same flag twice with different values. The
5714// expected behavior is that the one coming last takes precedence.
5715TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5716 const char* argv[] = {
5717 "foo.exe",
5718 "--gtest_filter=a",
5719 "--gtest_filter=b",
5720 NULL
5721 };
5722
5723 const char* argv2[] = {
5724 "foo.exe",
5725 NULL
5726 };
5727
vladlosevba015a92009-11-17 22:43:15 +00005728 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005729}
5730
5731// Tests having an unrecognized flag on the command line.
5732TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5733 const char* argv[] = {
5734 "foo.exe",
5735 "--gtest_break_on_failure",
5736 "bar", // Unrecognized by Google Test.
5737 "--gtest_filter=b",
5738 NULL
5739 };
5740
5741 const char* argv2[] = {
5742 "foo.exe",
5743 "bar",
5744 NULL
5745 };
5746
5747 Flags flags;
5748 flags.break_on_failure = true;
5749 flags.filter = "b";
vladlosevba015a92009-11-17 22:43:15 +00005750 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00005751}
5752
5753// Tests having a --gtest_list_tests flag
5754TEST_F(InitGoogleTestTest, ListTestsFlag) {
5755 const char* argv[] = {
5756 "foo.exe",
5757 "--gtest_list_tests",
5758 NULL
5759 };
5760
5761 const char* argv2[] = {
5762 "foo.exe",
5763 NULL
5764 };
5765
vladlosevba015a92009-11-17 22:43:15 +00005766 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005767}
5768
5769// Tests having a --gtest_list_tests flag with a "true" value
5770TEST_F(InitGoogleTestTest, ListTestsTrue) {
5771 const char* argv[] = {
5772 "foo.exe",
5773 "--gtest_list_tests=1",
5774 NULL
5775 };
5776
5777 const char* argv2[] = {
5778 "foo.exe",
5779 NULL
5780 };
5781
vladlosevba015a92009-11-17 22:43:15 +00005782 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005783}
5784
5785// Tests having a --gtest_list_tests flag with a "false" value
5786TEST_F(InitGoogleTestTest, ListTestsFalse) {
5787 const char* argv[] = {
5788 "foo.exe",
5789 "--gtest_list_tests=0",
5790 NULL
5791 };
5792
5793 const char* argv2[] = {
5794 "foo.exe",
5795 NULL
5796 };
5797
vladlosevba015a92009-11-17 22:43:15 +00005798 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005799}
5800
5801// Tests parsing --gtest_list_tests=f.
5802TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5803 const char* argv[] = {
5804 "foo.exe",
5805 "--gtest_list_tests=f",
5806 NULL
5807 };
5808
5809 const char* argv2[] = {
5810 "foo.exe",
5811 NULL
5812 };
5813
vladlosevba015a92009-11-17 22:43:15 +00005814 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005815}
5816
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005817// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005818TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5819 const char* argv[] = {
5820 "foo.exe",
5821 "--gtest_list_tests=F",
5822 NULL
5823 };
5824
5825 const char* argv2[] = {
5826 "foo.exe",
5827 NULL
5828 };
5829
vladlosevba015a92009-11-17 22:43:15 +00005830 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005831}
5832
5833// Tests parsing --gtest_output (invalid).
5834TEST_F(InitGoogleTestTest, OutputEmpty) {
5835 const char* argv[] = {
5836 "foo.exe",
5837 "--gtest_output",
5838 NULL
5839 };
5840
5841 const char* argv2[] = {
5842 "foo.exe",
5843 "--gtest_output",
5844 NULL
5845 };
5846
vladlosevba015a92009-11-17 22:43:15 +00005847 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
shiqian4b6829f2008-07-03 22:38:12 +00005848}
5849
5850// Tests parsing --gtest_output=xml
5851TEST_F(InitGoogleTestTest, OutputXml) {
5852 const char* argv[] = {
5853 "foo.exe",
5854 "--gtest_output=xml",
5855 NULL
5856 };
5857
5858 const char* argv2[] = {
5859 "foo.exe",
5860 NULL
5861 };
5862
vladlosevba015a92009-11-17 22:43:15 +00005863 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005864}
5865
5866// Tests parsing --gtest_output=xml:file
5867TEST_F(InitGoogleTestTest, OutputXmlFile) {
5868 const char* argv[] = {
5869 "foo.exe",
5870 "--gtest_output=xml:file",
5871 NULL
5872 };
5873
5874 const char* argv2[] = {
5875 "foo.exe",
5876 NULL
5877 };
5878
vladlosevba015a92009-11-17 22:43:15 +00005879 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005880}
5881
5882// Tests parsing --gtest_output=xml:directory/path/
5883TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5884 const char* argv[] = {
5885 "foo.exe",
5886 "--gtest_output=xml:directory/path/",
5887 NULL
5888 };
5889
5890 const char* argv2[] = {
5891 "foo.exe",
5892 NULL
5893 };
5894
vladlosevba015a92009-11-17 22:43:15 +00005895 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5896 Flags::Output("xml:directory/path/"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005897}
5898
shiqiand981cee2008-07-25 04:06:16 +00005899// Tests having a --gtest_print_time flag
5900TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5901 const char* argv[] = {
5902 "foo.exe",
5903 "--gtest_print_time",
5904 NULL
5905 };
5906
5907 const char* argv2[] = {
5908 "foo.exe",
5909 NULL
5910 };
5911
vladlosevba015a92009-11-17 22:43:15 +00005912 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005913}
5914
5915// Tests having a --gtest_print_time flag with a "true" value
5916TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5917 const char* argv[] = {
5918 "foo.exe",
5919 "--gtest_print_time=1",
5920 NULL
5921 };
5922
5923 const char* argv2[] = {
5924 "foo.exe",
5925 NULL
5926 };
5927
vladlosevba015a92009-11-17 22:43:15 +00005928 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005929}
5930
5931// Tests having a --gtest_print_time flag with a "false" value
5932TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5933 const char* argv[] = {
5934 "foo.exe",
5935 "--gtest_print_time=0",
5936 NULL
5937 };
5938
5939 const char* argv2[] = {
5940 "foo.exe",
5941 NULL
5942 };
5943
vladlosevba015a92009-11-17 22:43:15 +00005944 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005945}
5946
5947// Tests parsing --gtest_print_time=f.
5948TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5949 const char* argv[] = {
5950 "foo.exe",
5951 "--gtest_print_time=f",
5952 NULL
5953 };
5954
5955 const char* argv2[] = {
5956 "foo.exe",
5957 NULL
5958 };
5959
vladlosevba015a92009-11-17 22:43:15 +00005960 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005961}
5962
5963// Tests parsing --gtest_print_time=F.
5964TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5965 const char* argv[] = {
5966 "foo.exe",
5967 "--gtest_print_time=F",
5968 NULL
5969 };
5970
5971 const char* argv2[] = {
5972 "foo.exe",
5973 NULL
5974 };
5975
vladlosevba015a92009-11-17 22:43:15 +00005976 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005977}
5978
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005979// Tests parsing --gtest_random_seed=number
5980TEST_F(InitGoogleTestTest, RandomSeed) {
5981 const char* argv[] = {
5982 "foo.exe",
5983 "--gtest_random_seed=1000",
5984 NULL
5985 };
5986
5987 const char* argv2[] = {
5988 "foo.exe",
5989 NULL
5990 };
5991
vladlosevba015a92009-11-17 22:43:15 +00005992 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005993}
5994
shiqian4b6829f2008-07-03 22:38:12 +00005995// Tests parsing --gtest_repeat=number
5996TEST_F(InitGoogleTestTest, Repeat) {
5997 const char* argv[] = {
5998 "foo.exe",
5999 "--gtest_repeat=1000",
6000 NULL
6001 };
6002
6003 const char* argv2[] = {
6004 "foo.exe",
6005 NULL
6006 };
6007
vladlosevba015a92009-11-17 22:43:15 +00006008 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
shiqian4b6829f2008-07-03 22:38:12 +00006009}
6010
shiqianca6949f2009-01-10 01:16:33 +00006011// Tests having a --gtest_also_run_disabled_tests flag
6012TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6013 const char* argv[] = {
6014 "foo.exe",
6015 "--gtest_also_run_disabled_tests",
6016 NULL
6017 };
6018
6019 const char* argv2[] = {
6020 "foo.exe",
6021 NULL
6022 };
6023
vladlosevba015a92009-11-17 22:43:15 +00006024 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6025 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00006026}
6027
6028// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6029TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6030 const char* argv[] = {
6031 "foo.exe",
6032 "--gtest_also_run_disabled_tests=1",
6033 NULL
6034 };
6035
6036 const char* argv2[] = {
6037 "foo.exe",
6038 NULL
6039 };
6040
vladlosevba015a92009-11-17 22:43:15 +00006041 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6042 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00006043}
6044
6045// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6046TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6047 const char* argv[] = {
6048 "foo.exe",
6049 "--gtest_also_run_disabled_tests=0",
6050 NULL
6051 };
6052
6053 const char* argv2[] = {
6054 "foo.exe",
6055 NULL
6056 };
6057
vladlosevba015a92009-11-17 22:43:15 +00006058 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6059 Flags::AlsoRunDisabledTests(false), false);
shiqianca6949f2009-01-10 01:16:33 +00006060}
6061
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006062// Tests parsing --gtest_shuffle.
6063TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6064 const char* argv[] = {
6065 "foo.exe",
6066 "--gtest_shuffle",
6067 NULL
6068};
6069
6070 const char* argv2[] = {
6071 "foo.exe",
6072 NULL
6073 };
6074
vladlosevba015a92009-11-17 22:43:15 +00006075 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006076}
6077
6078// Tests parsing --gtest_shuffle=0.
6079TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6080 const char* argv[] = {
6081 "foo.exe",
6082 "--gtest_shuffle=0",
6083 NULL
6084 };
6085
6086 const char* argv2[] = {
6087 "foo.exe",
6088 NULL
6089 };
6090
vladlosevba015a92009-11-17 22:43:15 +00006091 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006092}
6093
6094// Tests parsing a --gtest_shuffle flag that has a "true"
6095// definition.
6096TEST_F(InitGoogleTestTest, ShuffleTrue) {
6097 const char* argv[] = {
6098 "foo.exe",
6099 "--gtest_shuffle=1",
6100 NULL
6101 };
6102
6103 const char* argv2[] = {
6104 "foo.exe",
6105 NULL
6106 };
6107
vladlosevba015a92009-11-17 22:43:15 +00006108 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6109}
6110
6111// Tests parsing --gtest_stack_trace_depth=number.
6112TEST_F(InitGoogleTestTest, StackTraceDepth) {
6113 const char* argv[] = {
6114 "foo.exe",
6115 "--gtest_stack_trace_depth=5",
6116 NULL
6117 };
6118
6119 const char* argv2[] = {
6120 "foo.exe",
6121 NULL
6122 };
6123
6124 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006125}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006126
6127// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006128TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006129 const char* argv[] = {
6130 "foo.exe",
6131 "--gtest_throw_on_failure",
6132 NULL
6133};
6134
6135 const char* argv2[] = {
6136 "foo.exe",
6137 NULL
6138 };
6139
vladlosevba015a92009-11-17 22:43:15 +00006140 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006141}
6142
6143// Tests parsing --gtest_throw_on_failure=0.
6144TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6145 const char* argv[] = {
6146 "foo.exe",
6147 "--gtest_throw_on_failure=0",
6148 NULL
6149 };
6150
6151 const char* argv2[] = {
6152 "foo.exe",
6153 NULL
6154 };
6155
vladlosevba015a92009-11-17 22:43:15 +00006156 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006157}
6158
6159// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6160// definition.
6161TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6162 const char* argv[] = {
6163 "foo.exe",
6164 "--gtest_throw_on_failure=1",
6165 NULL
6166 };
6167
6168 const char* argv2[] = {
6169 "foo.exe",
6170 NULL
6171 };
6172
vladlosevba015a92009-11-17 22:43:15 +00006173 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006174}
6175
zhanyong.wan4cd62602009-02-23 23:21:55 +00006176#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006177// Tests parsing wide strings.
6178TEST_F(InitGoogleTestTest, WideStrings) {
6179 const wchar_t* argv[] = {
6180 L"foo.exe",
6181 L"--gtest_filter=Foo*",
6182 L"--gtest_list_tests=1",
6183 L"--gtest_break_on_failure",
6184 L"--non_gtest_flag",
6185 NULL
6186 };
6187
6188 const wchar_t* argv2[] = {
6189 L"foo.exe",
6190 L"--non_gtest_flag",
6191 NULL
6192 };
6193
6194 Flags expected_flags;
6195 expected_flags.break_on_failure = true;
6196 expected_flags.filter = "Foo*";
6197 expected_flags.list_tests = true;
6198
vladlosevba015a92009-11-17 22:43:15 +00006199 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00006200}
6201#endif // GTEST_OS_WINDOWS
6202
6203// Tests current_test_info() in UnitTest.
6204class CurrentTestInfoTest : public Test {
6205 protected:
6206 // Tests that current_test_info() returns NULL before the first test in
6207 // the test case is run.
6208 static void SetUpTestCase() {
6209 // There should be no tests running at this point.
6210 const TestInfo* test_info =
6211 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006212 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006213 << "There should be no tests running at this point.";
6214 }
6215
6216 // Tests that current_test_info() returns NULL after the last test in
6217 // the test case has run.
6218 static void TearDownTestCase() {
6219 const TestInfo* test_info =
6220 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006221 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006222 << "There should be no tests running at this point.";
6223 }
6224};
6225
6226// Tests that current_test_info() returns TestInfo for currently running
6227// test by checking the expected test name against the actual one.
6228TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6229 const TestInfo* test_info =
6230 UnitTest::GetInstance()->current_test_info();
6231 ASSERT_TRUE(NULL != test_info)
6232 << "There is a test running so we should have a valid TestInfo.";
6233 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6234 << "Expected the name of the currently running test case.";
6235 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6236 << "Expected the name of the currently running test.";
6237}
6238
6239// Tests that current_test_info() returns TestInfo for currently running
6240// test by checking the expected test name against the actual one. We
6241// use this test to see that the TestInfo object actually changed from
6242// the previous invocation.
6243TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6244 const TestInfo* test_info =
6245 UnitTest::GetInstance()->current_test_info();
6246 ASSERT_TRUE(NULL != test_info)
6247 << "There is a test running so we should have a valid TestInfo.";
6248 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6249 << "Expected the name of the currently running test case.";
6250 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6251 << "Expected the name of the currently running test.";
6252}
6253
6254} // namespace testing
6255
6256// These two lines test that we can define tests in a namespace that
6257// has the name "testing" and is nested in another namespace.
6258namespace my_namespace {
6259namespace testing {
6260
6261// Makes sure that TEST knows to use ::testing::Test instead of
6262// ::my_namespace::testing::Test.
6263class Test {};
6264
6265// Makes sure that an assertion knows to use ::testing::Message instead of
6266// ::my_namespace::testing::Message.
6267class Message {};
6268
6269// Makes sure that an assertion knows to use
6270// ::testing::AssertionResult instead of
6271// ::my_namespace::testing::AssertionResult.
6272class AssertionResult {};
6273
6274// Tests that an assertion that should succeed works as expected.
6275TEST(NestedTestingNamespaceTest, Success) {
6276 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6277}
6278
6279// Tests that an assertion that should fail works as expected.
6280TEST(NestedTestingNamespaceTest, Failure) {
6281 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6282 "This failure is expected.");
6283}
6284
6285} // namespace testing
6286} // namespace my_namespace
6287
6288// Tests that one can call superclass SetUp and TearDown methods--
6289// that is, that they are not private.
6290// No tests are based on this fixture; the test "passes" if it compiles
6291// successfully.
shiqian760af5c2008-08-06 21:43:15 +00006292class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00006293 protected:
6294 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00006295 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00006296 }
6297 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00006298 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00006299 }
6300};
6301
6302// StreamingAssertionsTest tests the streaming versions of a representative
6303// sample of assertions.
6304TEST(StreamingAssertionsTest, Unconditional) {
6305 SUCCEED() << "expected success";
6306 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6307 "expected failure");
6308 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6309 "expected failure");
6310}
6311
zhanyong.wan98efcc42009-04-28 00:28:09 +00006312#ifdef __BORLANDC__
6313// Silences warnings: "Condition is always true", "Unreachable code"
6314#pragma option push -w-ccc -w-rch
6315#endif
6316
shiqian4b6829f2008-07-03 22:38:12 +00006317TEST(StreamingAssertionsTest, Truth) {
6318 EXPECT_TRUE(true) << "unexpected failure";
6319 ASSERT_TRUE(true) << "unexpected failure";
6320 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6321 "expected failure");
6322 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6323 "expected failure");
6324}
6325
6326TEST(StreamingAssertionsTest, Truth2) {
6327 EXPECT_FALSE(false) << "unexpected failure";
6328 ASSERT_FALSE(false) << "unexpected failure";
6329 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6330 "expected failure");
6331 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6332 "expected failure");
6333}
6334
zhanyong.wan98efcc42009-04-28 00:28:09 +00006335#ifdef __BORLANDC__
6336// Restores warnings after previous "#pragma option push" supressed them
6337#pragma option pop
6338#endif
6339
shiqian4b6829f2008-07-03 22:38:12 +00006340TEST(StreamingAssertionsTest, IntegerEquals) {
6341 EXPECT_EQ(1, 1) << "unexpected failure";
6342 ASSERT_EQ(1, 1) << "unexpected failure";
6343 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6344 "expected failure");
6345 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6346 "expected failure");
6347}
6348
6349TEST(StreamingAssertionsTest, IntegerLessThan) {
6350 EXPECT_LT(1, 2) << "unexpected failure";
6351 ASSERT_LT(1, 2) << "unexpected failure";
6352 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6353 "expected failure");
6354 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6355 "expected failure");
6356}
6357
6358TEST(StreamingAssertionsTest, StringsEqual) {
6359 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6360 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6361 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6362 "expected failure");
6363 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6364 "expected failure");
6365}
6366
6367TEST(StreamingAssertionsTest, StringsNotEqual) {
6368 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6369 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6370 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6371 "expected failure");
6372 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6373 "expected failure");
6374}
6375
6376TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6377 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6378 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6379 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6380 "expected failure");
6381 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6382 "expected failure");
6383}
6384
6385TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6386 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6387 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6388 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6389 "expected failure");
6390 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6391 "expected failure");
6392}
6393
6394TEST(StreamingAssertionsTest, FloatingPointEquals) {
6395 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6396 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6397 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6398 "expected failure");
6399 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6400 "expected failure");
6401}
6402
shiqian9204c8e2008-09-12 20:57:22 +00006403#if GTEST_HAS_EXCEPTIONS
6404
6405TEST(StreamingAssertionsTest, Throw) {
6406 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6407 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6408 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6409 "expected failure", "expected failure");
6410 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6411 "expected failure", "expected failure");
6412}
6413
6414TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00006415 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6416 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00006417 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6418 "expected failure", "expected failure");
6419 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6420 "expected failure", "expected failure");
6421}
6422
6423TEST(StreamingAssertionsTest, AnyThrow) {
6424 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6425 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00006426 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006427 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00006428 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006429 "expected failure", "expected failure");
6430}
6431
6432#endif // GTEST_HAS_EXCEPTIONS
6433
shiqian4b6829f2008-07-03 22:38:12 +00006434// Tests that Google Test correctly decides whether to use colors in the output.
6435
6436TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6437 GTEST_FLAG(color) = "yes";
6438
6439 SetEnv("TERM", "xterm"); // TERM supports colors.
6440 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6441 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6442
6443 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6444 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6445 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6446}
6447
6448TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6449 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6450
6451 GTEST_FLAG(color) = "True";
6452 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6453
6454 GTEST_FLAG(color) = "t";
6455 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6456
6457 GTEST_FLAG(color) = "1";
6458 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6459}
6460
6461TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6462 GTEST_FLAG(color) = "no";
6463
6464 SetEnv("TERM", "xterm"); // TERM supports colors.
6465 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6466 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6467
6468 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6469 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6470 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6471}
6472
6473TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6474 SetEnv("TERM", "xterm"); // TERM supports colors.
6475
6476 GTEST_FLAG(color) = "F";
6477 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6478
6479 GTEST_FLAG(color) = "0";
6480 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6481
6482 GTEST_FLAG(color) = "unknown";
6483 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6484}
6485
6486TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6487 GTEST_FLAG(color) = "auto";
6488
6489 SetEnv("TERM", "xterm"); // TERM supports colors.
6490 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6491 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6492}
6493
6494TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6495 GTEST_FLAG(color) = "auto";
6496
zhanyong.wan4cd62602009-02-23 23:21:55 +00006497#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006498 // On Windows, we ignore the TERM variable as it's usually not set.
6499
6500 SetEnv("TERM", "dumb");
6501 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6502
6503 SetEnv("TERM", "");
6504 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6505
6506 SetEnv("TERM", "xterm");
6507 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6508#else
6509 // On non-Windows platforms, we rely on TERM to determine if the
6510 // terminal supports colors.
6511
6512 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6513 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6514
6515 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6516 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6517
6518 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6519 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6520
6521 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6522 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6523
6524 SetEnv("TERM", "xterm"); // TERM supports colors.
6525 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6526
6527 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6528 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00006529
6530 SetEnv("TERM", "linux"); // TERM supports colors.
6531 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00006532#endif // GTEST_OS_WINDOWS
6533}
6534
shiqian21d43d12009-01-08 01:10:31 +00006535// Verifies that StaticAssertTypeEq works in a namespace scope.
6536
6537static bool dummy1 = StaticAssertTypeEq<bool, bool>();
6538static bool dummy2 = StaticAssertTypeEq<const int, const int>();
6539
6540// Verifies that StaticAssertTypeEq works in a class.
6541
6542template <typename T>
6543class StaticAssertTypeEqTestHelper {
6544 public:
6545 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6546};
6547
6548TEST(StaticAssertTypeEqTest, WorksInClass) {
6549 StaticAssertTypeEqTestHelper<bool>();
6550}
6551
6552// Verifies that StaticAssertTypeEq works inside a function.
6553
6554typedef int IntAlias;
6555
6556TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6557 StaticAssertTypeEq<int, IntAlias>();
6558 StaticAssertTypeEq<int*, IntAlias*>();
6559}
6560
shiqiane44602e2008-10-11 07:20:02 +00006561TEST(ThreadLocalTest, DefaultConstructor) {
6562 ThreadLocal<int> t1;
6563 EXPECT_EQ(0, t1.get());
6564
6565 ThreadLocal<void*> t2;
6566 EXPECT_TRUE(t2.get() == NULL);
6567}
6568
6569TEST(ThreadLocalTest, Init) {
6570 ThreadLocal<int> t1(123);
6571 EXPECT_EQ(123, t1.get());
6572
6573 int i = 0;
6574 ThreadLocal<int*> t2(&i);
6575 EXPECT_EQ(&i, t2.get());
6576}
6577
vladlosevf904a612008-11-20 01:40:35 +00006578TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6579 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6580
6581 // We don't have a stack walker in Google Test yet.
6582 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6583 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6584}
zhanyong.wan1b171102009-04-07 21:03:22 +00006585
6586TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6587 EXPECT_FALSE(HasNonfatalFailure());
6588}
6589
6590static void FailFatally() { FAIL(); }
6591
6592TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6593 FailFatally();
6594 const bool has_nonfatal_failure = HasNonfatalFailure();
6595 ClearCurrentTestPartResults();
6596 EXPECT_FALSE(has_nonfatal_failure);
6597}
6598
6599TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6600 ADD_FAILURE();
6601 const bool has_nonfatal_failure = HasNonfatalFailure();
6602 ClearCurrentTestPartResults();
6603 EXPECT_TRUE(has_nonfatal_failure);
6604}
6605
6606TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6607 FailFatally();
6608 ADD_FAILURE();
6609 const bool has_nonfatal_failure = HasNonfatalFailure();
6610 ClearCurrentTestPartResults();
6611 EXPECT_TRUE(has_nonfatal_failure);
6612}
6613
6614// A wrapper for calling HasNonfatalFailure outside of a test body.
6615static bool HasNonfatalFailureHelper() {
6616 return testing::Test::HasNonfatalFailure();
6617}
6618
6619TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6620 EXPECT_FALSE(HasNonfatalFailureHelper());
6621}
6622
6623TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6624 ADD_FAILURE();
6625 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6626 ClearCurrentTestPartResults();
6627 EXPECT_TRUE(has_nonfatal_failure);
6628}
6629
6630TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6631 EXPECT_FALSE(HasFailure());
6632}
6633
6634TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6635 FailFatally();
6636 const bool has_failure = HasFailure();
6637 ClearCurrentTestPartResults();
6638 EXPECT_TRUE(has_failure);
6639}
6640
6641TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6642 ADD_FAILURE();
6643 const bool has_failure = HasFailure();
6644 ClearCurrentTestPartResults();
6645 EXPECT_TRUE(has_failure);
6646}
6647
6648TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6649 FailFatally();
6650 ADD_FAILURE();
6651 const bool has_failure = HasFailure();
6652 ClearCurrentTestPartResults();
6653 EXPECT_TRUE(has_failure);
6654}
6655
6656// A wrapper for calling HasFailure outside of a test body.
6657static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6658
6659TEST(HasFailureTest, WorksOutsideOfTestBody) {
6660 EXPECT_FALSE(HasFailureHelper());
6661}
6662
6663TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6664 ADD_FAILURE();
6665 const bool has_failure = HasFailureHelper();
6666 ClearCurrentTestPartResults();
6667 EXPECT_TRUE(has_failure);
6668}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006669
6670class TestListener : public EmptyTestEventListener {
6671 public:
6672 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6673 TestListener(int* on_start_counter, bool* is_destroyed)
6674 : on_start_counter_(on_start_counter),
6675 is_destroyed_(is_destroyed) {}
6676
6677 virtual ~TestListener() {
6678 if (is_destroyed_)
6679 *is_destroyed_ = true;
6680 }
6681
6682 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006683 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006684 if (on_start_counter_ != NULL)
6685 (*on_start_counter_)++;
6686 }
6687
6688 private:
6689 int* on_start_counter_;
6690 bool* is_destroyed_;
6691};
6692
6693// Tests the constructor.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006694TEST(TestEventListenersTest, ConstructionWorks) {
6695 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006696
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006697 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006698 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6699 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6700}
6701
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006702// Tests that the TestEventListeners destructor deletes all the listeners it
zhanyong.wanf39160b2009-09-04 18:30:25 +00006703// owns.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006704TEST(TestEventListenersTest, DestructionWorks) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006705 bool default_result_printer_is_destroyed = false;
6706 bool default_xml_printer_is_destroyed = false;
6707 bool extra_listener_is_destroyed = false;
6708 TestListener* default_result_printer = new TestListener(
6709 NULL, &default_result_printer_is_destroyed);
6710 TestListener* default_xml_printer = new TestListener(
6711 NULL, &default_xml_printer_is_destroyed);
6712 TestListener* extra_listener = new TestListener(
6713 NULL, &extra_listener_is_destroyed);
6714
6715 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006716 TestEventListeners listeners;
6717 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6718 default_result_printer);
6719 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6720 default_xml_printer);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006721 listeners.Append(extra_listener);
6722 }
6723 EXPECT_TRUE(default_result_printer_is_destroyed);
6724 EXPECT_TRUE(default_xml_printer_is_destroyed);
6725 EXPECT_TRUE(extra_listener_is_destroyed);
6726}
6727
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006728// Tests that a listener Append'ed to a TestEventListeners list starts
zhanyong.wanf39160b2009-09-04 18:30:25 +00006729// receiving events.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006730TEST(TestEventListenersTest, Append) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006731 int on_start_counter = 0;
6732 bool is_destroyed = false;
6733 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6734 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006735 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006736 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006737 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006738 *UnitTest::GetInstance());
6739 EXPECT_EQ(1, on_start_counter);
6740 }
6741 EXPECT_TRUE(is_destroyed);
6742}
6743
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006744// Tests that listeners receive events in the order they were appended to
6745// the list, except for *End requests, which must be received in the reverse
6746// order.
zhanyong.wanf39160b2009-09-04 18:30:25 +00006747class SequenceTestingListener : public EmptyTestEventListener {
6748 public:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006749 SequenceTestingListener(Vector<String>* vector, const char* id)
6750 : vector_(vector), id_(id) {}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006751
6752 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006753 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6754 vector_->PushBack(GetEventDescription("OnTestProgramStart"));
6755 }
6756
6757 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
6758 vector_->PushBack(GetEventDescription("OnTestProgramEnd"));
6759 }
6760
6761 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
6762 int /*iteration*/) {
6763 vector_->PushBack(GetEventDescription("OnTestIterationStart"));
6764 }
6765
6766 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6767 int /*iteration*/) {
6768 vector_->PushBack(GetEventDescription("OnTestIterationEnd"));
zhanyong.wanf39160b2009-09-04 18:30:25 +00006769 }
6770
6771 private:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006772 String GetEventDescription(const char* method) {
6773 Message message;
6774 message << id_ << "." << method;
6775 return message.GetString();
6776 }
6777
6778 Vector<String>* vector_;
6779 const char* const id_;
zhanyong.wand586f9f2009-09-18 16:35:15 +00006780
6781 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006782};
6783
6784TEST(EventListenerTest, AppendKeepsOrder) {
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006785 Vector<String> vec;
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006786 TestEventListeners listeners;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006787 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6788 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6789 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6790
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006791 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006792 *UnitTest::GetInstance());
6793 ASSERT_EQ(3, vec.size());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006794 EXPECT_STREQ("1st.OnTestProgramStart", vec.GetElement(0).c_str());
6795 EXPECT_STREQ("2nd.OnTestProgramStart", vec.GetElement(1).c_str());
6796 EXPECT_STREQ("3rd.OnTestProgramStart", vec.GetElement(2).c_str());
6797
6798 vec.Clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006799 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006800 *UnitTest::GetInstance());
6801 ASSERT_EQ(3, vec.size());
6802 EXPECT_STREQ("3rd.OnTestProgramEnd", vec.GetElement(0).c_str());
6803 EXPECT_STREQ("2nd.OnTestProgramEnd", vec.GetElement(1).c_str());
6804 EXPECT_STREQ("1st.OnTestProgramEnd", vec.GetElement(2).c_str());
6805
6806 vec.Clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006807 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006808 *UnitTest::GetInstance(), 0);
6809 ASSERT_EQ(3, vec.size());
6810 EXPECT_STREQ("1st.OnTestIterationStart", vec.GetElement(0).c_str());
6811 EXPECT_STREQ("2nd.OnTestIterationStart", vec.GetElement(1).c_str());
6812 EXPECT_STREQ("3rd.OnTestIterationStart", vec.GetElement(2).c_str());
6813
6814 vec.Clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006815 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006816 *UnitTest::GetInstance(), 0);
6817 ASSERT_EQ(3, vec.size());
6818 EXPECT_STREQ("3rd.OnTestIterationEnd", vec.GetElement(0).c_str());
6819 EXPECT_STREQ("2nd.OnTestIterationEnd", vec.GetElement(1).c_str());
6820 EXPECT_STREQ("1st.OnTestIterationEnd", vec.GetElement(2).c_str());
zhanyong.wanf39160b2009-09-04 18:30:25 +00006821}
6822
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006823// Tests that a listener removed from a TestEventListeners list stops receiving
zhanyong.wanf39160b2009-09-04 18:30:25 +00006824// events and is not deleted when the list is destroyed.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006825TEST(TestEventListenersTest, Release) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006826 int on_start_counter = 0;
6827 bool is_destroyed = false;
6828 // Although Append passes the ownership of this object to the list,
6829 // the following calls release it, and we need to delete it before the
6830 // test ends.
6831 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6832 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006833 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006834 listeners.Append(listener);
6835 EXPECT_EQ(listener, listeners.Release(listener));
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006836 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006837 *UnitTest::GetInstance());
6838 EXPECT_TRUE(listeners.Release(listener) == NULL);
6839 }
6840 EXPECT_EQ(0, on_start_counter);
6841 EXPECT_FALSE(is_destroyed);
6842 delete listener;
6843}
6844
6845// Tests that no events are forwarded when event forwarding is disabled.
6846TEST(EventListenerTest, SuppressEventForwarding) {
6847 int on_start_counter = 0;
6848 TestListener* listener = new TestListener(&on_start_counter, NULL);
6849
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006850 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006851 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006852 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6853 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6854 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6855 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006856 *UnitTest::GetInstance());
6857 EXPECT_EQ(0, on_start_counter);
6858}
6859
zhanyong.wanf39160b2009-09-04 18:30:25 +00006860// Tests that events generated by Google Test are not forwarded in
6861// death test subprocesses.
6862TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
zhanyong.wand541f022009-09-11 06:59:42 +00006863 EXPECT_DEATH_IF_SUPPORTED({
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006864 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006865 *GetUnitTestImpl()->listeners())) << "expected failure";},
6866 "expected failure");
6867}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006868
6869// Tests that a listener installed via SetDefaultResultPrinter() starts
6870// receiving events and is returned via default_result_printer() and that
6871// the previous default_result_printer is removed from the list and deleted.
6872TEST(EventListenerTest, default_result_printer) {
6873 int on_start_counter = 0;
6874 bool is_destroyed = false;
6875 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6876
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006877 TestEventListeners listeners;
6878 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006879
6880 EXPECT_EQ(listener, listeners.default_result_printer());
6881
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006882 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006883 *UnitTest::GetInstance());
6884
6885 EXPECT_EQ(1, on_start_counter);
6886
6887 // Replacing default_result_printer with something else should remove it
6888 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006889 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006890
6891 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6892 EXPECT_TRUE(is_destroyed);
6893
6894 // After broadcasting an event the counter is still the same, indicating
6895 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006896 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006897 *UnitTest::GetInstance());
6898 EXPECT_EQ(1, on_start_counter);
6899}
6900
6901// Tests that the default_result_printer listener stops receiving events
6902// when removed via Release and that is not owned by the list anymore.
6903TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6904 int on_start_counter = 0;
6905 bool is_destroyed = false;
6906 // Although Append passes the ownership of this object to the list,
6907 // the following calls release it, and we need to delete it before the
6908 // test ends.
6909 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6910 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006911 TestEventListeners listeners;
6912 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006913
6914 EXPECT_EQ(listener, listeners.Release(listener));
6915 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6916 EXPECT_FALSE(is_destroyed);
6917
6918 // Broadcasting events now should not affect default_result_printer.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006919 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006920 *UnitTest::GetInstance());
6921 EXPECT_EQ(0, on_start_counter);
6922 }
6923 // Destroying the list should not affect the listener now, too.
6924 EXPECT_FALSE(is_destroyed);
6925 delete listener;
6926}
6927
6928// Tests that a listener installed via SetDefaultXmlGenerator() starts
6929// receiving events and is returned via default_xml_generator() and that
6930// the previous default_xml_generator is removed from the list and deleted.
6931TEST(EventListenerTest, default_xml_generator) {
6932 int on_start_counter = 0;
6933 bool is_destroyed = false;
6934 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6935
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006936 TestEventListeners listeners;
6937 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006938
6939 EXPECT_EQ(listener, listeners.default_xml_generator());
6940
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006941 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006942 *UnitTest::GetInstance());
6943
6944 EXPECT_EQ(1, on_start_counter);
6945
6946 // Replacing default_xml_generator with something else should remove it
6947 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006948 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006949
6950 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6951 EXPECT_TRUE(is_destroyed);
6952
6953 // After broadcasting an event the counter is still the same, indicating
6954 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006955 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006956 *UnitTest::GetInstance());
6957 EXPECT_EQ(1, on_start_counter);
6958}
6959
6960// Tests that the default_xml_generator listener stops receiving events
6961// when removed via Release and that is not owned by the list anymore.
6962TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6963 int on_start_counter = 0;
6964 bool is_destroyed = false;
6965 // Although Append passes the ownership of this object to the list,
6966 // the following calls release it, and we need to delete it before the
6967 // test ends.
6968 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6969 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006970 TestEventListeners listeners;
6971 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006972
6973 EXPECT_EQ(listener, listeners.Release(listener));
6974 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6975 EXPECT_FALSE(is_destroyed);
6976
6977 // Broadcasting events now should not affect default_xml_generator.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006978 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006979 *UnitTest::GetInstance());
6980 EXPECT_EQ(0, on_start_counter);
6981 }
6982 // Destroying the list should not affect the listener now, too.
6983 EXPECT_FALSE(is_destroyed);
6984 delete listener;
6985}