blob: 4eb098e7bfc71d6124ea55d4569aa2ab792d9386 [file] [log] [blame]
shiqian4b6829f2008-07-03 22:38:12 +00001// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google Test itself. This verifies that the basic constructs of
33// Google Test work.
34
35#include <gtest/gtest.h>
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000036
37// Verifies that the command line flag variables can be accessed
38// in code once <gtest/gtest.h> has been #included.
39// Do not move it after other #includes.
40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000049 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000050 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000052 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000053 || testing::GTEST_FLAG(stack_trace_depth) > 0
54 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000055 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
56}
57
shiqian4b6829f2008-07-03 22:38:12 +000058#include <gtest/gtest-spi.h>
59
60// Indicates that this translation unit is part of Google Test's
61// implementation. It must come before gtest-internal-inl.h is
62// included, or there will be a compiler error. This trick is to
63// prevent a user from accidentally including gtest-internal-inl.h in
64// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000065#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000066#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000067#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000068
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +000069#include <limits.h> // For INT_MAX.
shiqian4b6829f2008-07-03 22:38:12 +000070#include <stdlib.h>
zhanyong.wan98efcc42009-04-28 00:28:09 +000071#include <time.h>
shiqian4b6829f2008-07-03 22:38:12 +000072
shiqiane44602e2008-10-11 07:20:02 +000073#if GTEST_HAS_PTHREAD
74#include <pthread.h>
75#endif // GTEST_HAS_PTHREAD
76
zhanyong.wan98efcc42009-04-28 00:28:09 +000077#ifdef __BORLANDC__
78#include <map>
79#endif
80
zhanyong.wan449f84d2009-07-01 22:55:05 +000081// GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex) expands to a
82// real death test if death tests are supported; otherwise it expands
83// to empty.
84#if GTEST_HAS_DEATH_TEST
85#define GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex) \
86 EXPECT_DEATH(statement, regex)
87#else
88#define GTEST_EXPECT_DEATH_IF_SUPPORTED_(statement, regex)
89#endif
90
shiqian4b6829f2008-07-03 22:38:12 +000091namespace testing {
92namespace internal {
shiqianf0e809a2008-09-26 16:08:30 +000093const char* FormatTimeInMillisAsSeconds(TimeInMillis ms);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000094
shiqian4b6829f2008-07-03 22:38:12 +000095bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000096
shiqian4b6829f2008-07-03 22:38:12 +000097} // namespace internal
98} // namespace testing
99
shiqianf0e809a2008-09-26 16:08:30 +0000100using testing::internal::FormatTimeInMillisAsSeconds;
shiqian4b6829f2008-07-03 22:38:12 +0000101using testing::internal::ParseInt32Flag;
102
103namespace testing {
104
shiqiane44602e2008-10-11 07:20:02 +0000105GTEST_DECLARE_string_(output);
106GTEST_DECLARE_string_(color);
shiqian4b6829f2008-07-03 22:38:12 +0000107
108namespace internal {
109bool ShouldUseColor(bool stdout_is_tty);
110} // namespace internal
111} // namespace testing
112
shiqian760af5c2008-08-06 21:43:15 +0000113using testing::AssertionFailure;
114using testing::AssertionResult;
115using testing::AssertionSuccess;
116using testing::DoubleLE;
117using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000118using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000119using testing::GTEST_FLAG(break_on_failure);
120using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000121using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000122using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000123using testing::GTEST_FLAG(filter);
124using testing::GTEST_FLAG(list_tests);
125using testing::GTEST_FLAG(output);
126using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000127using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000128using testing::GTEST_FLAG(repeat);
129using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000130using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000131using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000132using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000133using testing::IsNotSubstring;
134using testing::IsSubstring;
135using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000136using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000137using testing::StaticAssertTypeEq;
shiqian760af5c2008-08-06 21:43:15 +0000138using testing::TPRT_FATAL_FAILURE;
139using testing::TPRT_NONFATAL_FAILURE;
140using testing::TPRT_SUCCESS;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000141using testing::Test;
142using testing::TestPartResult;
143using testing::TestPartResultArray;
shiqian4b6829f2008-07-03 22:38:12 +0000144using testing::UnitTest;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000145using testing::internal::kMaxRandomSeed;
shiqianfe6a9a42008-11-24 20:13:22 +0000146using testing::internal::kTestTypeIdInGoogleTest;
shiqian4b6829f2008-07-03 22:38:12 +0000147using testing::internal::AppendUserMessage;
vladloseve006e682008-08-25 23:11:54 +0000148using testing::internal::CodePointToUtf8;
shiqian4b6829f2008-07-03 22:38:12 +0000149using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000150using testing::internal::FloatingPoint;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000151using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000152using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000153using testing::internal::GetNextRandomSeed;
154using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000155using testing::internal::GetTestTypeId;
156using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000157using testing::internal::GetUnitTestImpl;
shiqian4b6829f2008-07-03 22:38:12 +0000158using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000159using testing::internal::Int32FromEnvOrDie;
zhanyong.wan905074c2009-02-09 18:05:21 +0000160using testing::internal::ShouldRunTestOnShard;
161using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000162using testing::internal::ShouldUseColor;
163using testing::internal::StreamableToString;
164using testing::internal::String;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000165using testing::internal::TestCase;
shiqian4b6829f2008-07-03 22:38:12 +0000166using testing::internal::TestProperty;
167using testing::internal::TestResult;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000168using testing::internal::TestResultAccessor;
shiqiane44602e2008-10-11 07:20:02 +0000169using testing::internal::ThreadLocal;
zhanyong.wana8a582f2009-07-13 19:25:02 +0000170using testing::internal::Vector;
vladloseve006e682008-08-25 23:11:54 +0000171using testing::internal::WideStringToUtf8;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000172using testing::internal::kTestTypeIdInGoogleTest;
shiqian4b6829f2008-07-03 22:38:12 +0000173
174// This line tests that we can define tests in an unnamed namespace.
175namespace {
176
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000177TEST(GetRandomSeedFromFlagTest, HandlesZero) {
178 const int seed = GetRandomSeedFromFlag(0);
179 EXPECT_LE(1, seed);
180 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
181}
182
183TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
184 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
185 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
186 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
187 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
188 GetRandomSeedFromFlag(kMaxRandomSeed));
189}
190
191TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
192 const int seed1 = GetRandomSeedFromFlag(-1);
193 EXPECT_LE(1, seed1);
194 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
195
196 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
197 EXPECT_LE(1, seed2);
198 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
199}
200
201TEST(GetNextRandomSeedTest, WorksForValidInput) {
202 EXPECT_EQ(2, GetNextRandomSeed(1));
203 EXPECT_EQ(3, GetNextRandomSeed(2));
204 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
205 GetNextRandomSeed(kMaxRandomSeed - 1));
206 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
207
208 // We deliberately don't test GetNextRandomSeed() with invalid
209 // inputs, as that requires death tests, which are expensive. This
210 // is fine as GetNextRandomSeed() is internal and has a
211 // straightforward definition.
212}
213
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000214static void ClearCurrentTestPartResults() {
215 TestResultAccessor::ClearTestPartResults(
216 GetUnitTestImpl()->current_test_result());
217}
218
shiqianfe6a9a42008-11-24 20:13:22 +0000219// Tests GetTypeId.
220
221TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
222 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
223 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
224}
225
226class SubClassOfTest : public Test {};
227class AnotherSubClassOfTest : public Test {};
228
229TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
230 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
231 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
232 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
233 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
234 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
235 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
236}
237
238// Verifies that GetTestTypeId() returns the same value, no matter it
239// is called from inside Google Test or outside of it.
240TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
241 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
242}
243
shiqianf0e809a2008-09-26 16:08:30 +0000244// Tests FormatTimeInMillisAsSeconds().
245
246TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
247 EXPECT_STREQ("0", FormatTimeInMillisAsSeconds(0));
248}
249
250TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
251 EXPECT_STREQ("0.003", FormatTimeInMillisAsSeconds(3));
252 EXPECT_STREQ("0.01", FormatTimeInMillisAsSeconds(10));
253 EXPECT_STREQ("0.2", FormatTimeInMillisAsSeconds(200));
254 EXPECT_STREQ("1.2", FormatTimeInMillisAsSeconds(1200));
255 EXPECT_STREQ("3", FormatTimeInMillisAsSeconds(3000));
256}
257
258TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
259 EXPECT_STREQ("-0.003", FormatTimeInMillisAsSeconds(-3));
260 EXPECT_STREQ("-0.01", FormatTimeInMillisAsSeconds(-10));
261 EXPECT_STREQ("-0.2", FormatTimeInMillisAsSeconds(-200));
262 EXPECT_STREQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
263 EXPECT_STREQ("-3", FormatTimeInMillisAsSeconds(-3000));
264}
265
zhanyong.wan4cd62602009-02-23 23:21:55 +0000266#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +0000267// NULL testing does not work with Symbian compilers.
268
zhanyong.wan98efcc42009-04-28 00:28:09 +0000269#ifdef __BORLANDC__
270// Silences warnings: "Condition is always true", "Unreachable code"
271#pragma option push -w-ccc -w-rch
272#endif
273
shiqiane44602e2008-10-11 07:20:02 +0000274// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000275// pointer literal.
276TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000277 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
278 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000279 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
280 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
281 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000282#ifndef __BORLANDC__
283 // Some compilers may fail to detect some null pointer literals;
284 // as long as users of the framework don't use such literals, this
285 // is harmless.
286 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
shiqiane44602e2008-10-11 07:20:02 +0000287 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000288#endif
shiqian4b6829f2008-07-03 22:38:12 +0000289}
290
shiqiane44602e2008-10-11 07:20:02 +0000291// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
shiqian4b6829f2008-07-03 22:38:12 +0000292// pointer literal.
293TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000294 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
295 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
296 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
297 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
shiqian4b6829f2008-07-03 22:38:12 +0000298}
299
zhanyong.wan98efcc42009-04-28 00:28:09 +0000300#ifdef __BORLANDC__
301// Restores warnings after previous "#pragma option push" supressed them
302#pragma option pop
303#endif
304
zhanyong.wan4cd62602009-02-23 23:21:55 +0000305#endif // !GTEST_OS_SYMBIAN
vladloseve006e682008-08-25 23:11:54 +0000306//
307// Tests CodePointToUtf8().
shiqian4b6829f2008-07-03 22:38:12 +0000308
309// Tests that the NUL character L'\0' is encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000310TEST(CodePointToUtf8Test, CanEncodeNul) {
311 char buffer[32];
312 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000313}
314
315// Tests that ASCII characters are encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000316TEST(CodePointToUtf8Test, CanEncodeAscii) {
317 char buffer[32];
318 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
319 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
320 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
321 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000322}
323
324// Tests that Unicode code-points that have 8 to 11 bits are encoded
325// as 110xxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000326TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
327 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000328 // 000 1101 0011 => 110-00011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000329 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000330
331 // 101 0111 0110 => 110-10101 10-110110
vladloseve006e682008-08-25 23:11:54 +0000332 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000333}
334
335// Tests that Unicode code-points that have 12 to 16 bits are encoded
336// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000337TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
338 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000339 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000340 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000341
342 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
vladloseve006e682008-08-25 23:11:54 +0000343 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000344}
345
zhanyong.wan4cd62602009-02-23 23:21:55 +0000346#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000347// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000348// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000349// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000350
351// Tests that Unicode code-points that have 17 to 21 bits are encoded
352// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000353TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
354 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000355 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
vladloseve006e682008-08-25 23:11:54 +0000356 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000357
vladloseve006e682008-08-25 23:11:54 +0000358 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
359 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
360
361 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
362 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000363}
364
365// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000366TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
367 char buffer[32];
shiqian4b6829f2008-07-03 22:38:12 +0000368 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
vladloseve006e682008-08-25 23:11:54 +0000369 CodePointToUtf8(L'\x1234ABCD', buffer));
shiqian4b6829f2008-07-03 22:38:12 +0000370}
371
zhanyong.wan4cd62602009-02-23 23:21:55 +0000372#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000373
374// Tests WideStringToUtf8().
375
376// Tests that the NUL character L'\0' is encoded correctly.
377TEST(WideStringToUtf8Test, CanEncodeNul) {
378 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
379 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
380}
381
382// Tests that ASCII strings are encoded correctly.
383TEST(WideStringToUtf8Test, CanEncodeAscii) {
384 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
385 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
386 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
387 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
388}
389
390// Tests that Unicode code-points that have 8 to 11 bits are encoded
391// as 110xxxxx 10xxxxxx.
392TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
393 // 000 1101 0011 => 110-00011 10-010011
394 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
395 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
396
397 // 101 0111 0110 => 110-10101 10-110110
398 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
399 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
400}
401
402// Tests that Unicode code-points that have 12 to 16 bits are encoded
403// as 1110xxxx 10xxxxxx 10xxxxxx.
404TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
405 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
406 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
407 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
408
409 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
410 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
411 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
412}
413
414// Tests that the conversion stops when the function encounters \0 character.
415TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
416 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
417}
418
419// Tests that the conversion stops when the function reaches the limit
420// specified by the 'length' parameter.
421TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
422 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
423}
424
425
zhanyong.wan4cd62602009-02-23 23:21:55 +0000426#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000427// Tests that Unicode code-points that have 17 to 21 bits are encoded
428// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
429// on the systems using UTF-16 encoding.
430TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
431 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
432 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
433 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
434
435 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
436 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
437 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
438}
439
440// Tests that encoding an invalid code-point generates the expected result.
441TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
442 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
443 WideStringToUtf8(L"\xABCDFF", -1).c_str());
444}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000445#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000446// Tests that surrogate pairs are encoded correctly on the systems using
447// UTF-16 encoding in the wide strings.
448TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
449 EXPECT_STREQ("\xF0\x90\x90\x80",
450 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
451}
452
453// Tests that encoding an invalid UTF-16 surrogate pair
454// generates the expected result.
455TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
456 // Leading surrogate is at the end of the string.
457 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
458 // Leading surrogate is not followed by the trailing surrogate.
459 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
460 // Trailing surrogate appearas without a leading surrogate.
461 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
462}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000463#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000464
465// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000466#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000467TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
468 EXPECT_STREQ(
469 "\xF4\x88\x98\xB4"
470 "\xEC\x9D\x8D"
471 "\n"
472 "\xD5\xB6"
473 "\xE0\xA3\x93"
474 "\xF4\x88\x98\xB4",
475 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
476}
477#else
478TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
479 EXPECT_STREQ(
480 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
481 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
482}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000483#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000484
zhanyong.wana8a582f2009-07-13 19:25:02 +0000485// Tests the Vector class template.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000486
zhanyong.wana8a582f2009-07-13 19:25:02 +0000487// Tests Vector::Clear().
488TEST(VectorTest, Clear) {
489 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000490 a.PushBack(1);
491 a.Clear();
492 EXPECT_EQ(0, a.size());
493
494 a.PushBack(2);
495 a.PushBack(3);
496 a.Clear();
497 EXPECT_EQ(0, a.size());
498}
499
zhanyong.wana8a582f2009-07-13 19:25:02 +0000500// Tests Vector::PushBack().
501TEST(VectorTest, PushBack) {
502 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000503 a.PushBack('a');
504 ASSERT_EQ(1, a.size());
505 EXPECT_EQ('a', a.GetElement(0));
506
507 a.PushBack('b');
508 ASSERT_EQ(2, a.size());
509 EXPECT_EQ('a', a.GetElement(0));
510 EXPECT_EQ('b', a.GetElement(1));
511}
shiqian4b6829f2008-07-03 22:38:12 +0000512
zhanyong.wana8a582f2009-07-13 19:25:02 +0000513// Tests Vector::PushFront().
514TEST(VectorTest, PushFront) {
515 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000516 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000517
zhanyong.wana8a582f2009-07-13 19:25:02 +0000518 // Calls PushFront() on an empty Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000519 a.PushFront(1);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000520 ASSERT_EQ(1, a.size());
521 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000522
zhanyong.wana8a582f2009-07-13 19:25:02 +0000523 // Calls PushFront() on a singleton Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000524 a.PushFront(2);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000525 ASSERT_EQ(2, a.size());
526 EXPECT_EQ(2, a.GetElement(0));
527 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000528
zhanyong.wana8a582f2009-07-13 19:25:02 +0000529 // Calls PushFront() on a Vector with more than one elements.
shiqian4b6829f2008-07-03 22:38:12 +0000530 a.PushFront(3);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000531 ASSERT_EQ(3, a.size());
532 EXPECT_EQ(3, a.GetElement(0));
533 EXPECT_EQ(2, a.GetElement(1));
534 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000535}
536
zhanyong.wana8a582f2009-07-13 19:25:02 +0000537// Tests Vector::PopFront().
538TEST(VectorTest, PopFront) {
539 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000540
zhanyong.wana8a582f2009-07-13 19:25:02 +0000541 // Popping on an empty Vector should fail.
shiqian4b6829f2008-07-03 22:38:12 +0000542 EXPECT_FALSE(a.PopFront(NULL));
543
zhanyong.wana8a582f2009-07-13 19:25:02 +0000544 // Popping again on an empty Vector should fail, and the result element
shiqian4b6829f2008-07-03 22:38:12 +0000545 // shouldn't be overwritten.
546 int element = 1;
547 EXPECT_FALSE(a.PopFront(&element));
548 EXPECT_EQ(1, element);
549
550 a.PushFront(2);
551 a.PushFront(3);
552
zhanyong.wana8a582f2009-07-13 19:25:02 +0000553 // PopFront() should pop the element in the front of the Vector.
shiqian4b6829f2008-07-03 22:38:12 +0000554 EXPECT_TRUE(a.PopFront(&element));
555 EXPECT_EQ(3, element);
556
zhanyong.wana8a582f2009-07-13 19:25:02 +0000557 // After popping the last element, the Vector should be empty.
shiqian4b6829f2008-07-03 22:38:12 +0000558 EXPECT_TRUE(a.PopFront(NULL));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000559 EXPECT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000560}
561
zhanyong.wana8a582f2009-07-13 19:25:02 +0000562// Tests inserting at the beginning using Vector::Insert().
563TEST(VectorTest, InsertAtBeginning) {
564 Vector<int> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000565 ASSERT_EQ(0, a.size());
shiqian4b6829f2008-07-03 22:38:12 +0000566
zhanyong.wana8a582f2009-07-13 19:25:02 +0000567 // Inserts into an empty Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000568 a.Insert(1, 0);
569 ASSERT_EQ(1, a.size());
570 EXPECT_EQ(1, a.GetElement(0));
shiqian4b6829f2008-07-03 22:38:12 +0000571
zhanyong.wana8a582f2009-07-13 19:25:02 +0000572 // Inserts at the beginning of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000573 a.Insert(2, 0);
574 ASSERT_EQ(2, a.size());
575 EXPECT_EQ(2, a.GetElement(0));
576 EXPECT_EQ(1, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000577
zhanyong.wana8a582f2009-07-13 19:25:02 +0000578 // Inserts at the beginning of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000579 a.Insert(3, 0);
580 ASSERT_EQ(3, a.size());
581 EXPECT_EQ(3, a.GetElement(0));
582 EXPECT_EQ(2, a.GetElement(1));
583 EXPECT_EQ(1, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000584}
585
586// Tests inserting at a location other than the beginning using
zhanyong.wana8a582f2009-07-13 19:25:02 +0000587// Vector::Insert().
588TEST(VectorTest, InsertNotAtBeginning) {
589 // Prepares a singleton Vector.
590 Vector<int> a;
shiqian4b6829f2008-07-03 22:38:12 +0000591 a.PushBack(1);
592
zhanyong.wana8a582f2009-07-13 19:25:02 +0000593 // Inserts at the end of a singleton Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000594 a.Insert(2, a.size());
595 ASSERT_EQ(2, a.size());
596 EXPECT_EQ(1, a.GetElement(0));
597 EXPECT_EQ(2, a.GetElement(1));
shiqian4b6829f2008-07-03 22:38:12 +0000598
zhanyong.wana8a582f2009-07-13 19:25:02 +0000599 // Inserts at the end of a Vector with more than one elements.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000600 a.Insert(3, a.size());
601 ASSERT_EQ(3, a.size());
602 EXPECT_EQ(1, a.GetElement(0));
603 EXPECT_EQ(2, a.GetElement(1));
604 EXPECT_EQ(3, a.GetElement(2));
shiqian4b6829f2008-07-03 22:38:12 +0000605
zhanyong.wana8a582f2009-07-13 19:25:02 +0000606 // Inserts in the middle of a Vector.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000607 a.Insert(4, 1);
608 ASSERT_EQ(4, a.size());
609 EXPECT_EQ(1, a.GetElement(0));
610 EXPECT_EQ(4, a.GetElement(1));
611 EXPECT_EQ(2, a.GetElement(2));
612 EXPECT_EQ(3, a.GetElement(3));
613}
614
zhanyong.wana8a582f2009-07-13 19:25:02 +0000615// Tests Vector::GetElementOr().
616TEST(VectorTest, GetElementOr) {
617 Vector<char> a;
zhanyong.wan449f84d2009-07-01 22:55:05 +0000618 EXPECT_EQ('x', a.GetElementOr(0, 'x'));
619
620 a.PushBack('a');
621 a.PushBack('b');
622 EXPECT_EQ('a', a.GetElementOr(0, 'x'));
623 EXPECT_EQ('b', a.GetElementOr(1, 'x'));
624 EXPECT_EQ('x', a.GetElementOr(-2, 'x'));
625 EXPECT_EQ('x', a.GetElementOr(2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000626}
627
zhanyong.wana8a582f2009-07-13 19:25:02 +0000628// Tests Vector::Erase().
629TEST(VectorDeathTest, Erase) {
630 Vector<int> a;
631
632 // Tests erasing from an empty vector.
633 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
634 a.Erase(0),
635 "Invalid Vector index 0: must be in range \\[0, -1\\]\\.");
636
637 // Tests erasing from a singleton vector.
638 a.PushBack(0);
639
640 a.Erase(0);
641 EXPECT_EQ(0, a.size());
642
643 // Tests Erase parameters beyond the bounds of the vector.
644 Vector<int> a1;
645 a1.PushBack(0);
646 a1.PushBack(1);
647 a1.PushBack(2);
648
649 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
650 a1.Erase(3),
651 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
652 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
653 a1.Erase(-1),
654 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
655
656 // Tests erasing at the end of the vector.
657 Vector<int> a2;
658 a2.PushBack(0);
659 a2.PushBack(1);
660 a2.PushBack(2);
661
662 a2.Erase(2);
663 ASSERT_EQ(2, a2.size());
664 EXPECT_EQ(0, a2.GetElement(0));
665 EXPECT_EQ(1, a2.GetElement(1));
666
667 // Tests erasing in the middle of the vector.
668 Vector<int> a3;
669 a3.PushBack(0);
670 a3.PushBack(1);
671 a3.PushBack(2);
672
673 a3.Erase(1);
674 ASSERT_EQ(2, a3.size());
675 EXPECT_EQ(0, a3.GetElement(0));
676 EXPECT_EQ(2, a3.GetElement(1));
677
678 // Tests erasing at the beginning of the vector.
679 Vector<int> a4;
680 a4.PushBack(0);
681 a4.PushBack(1);
682 a4.PushBack(2);
683
684 a4.Erase(0);
685 ASSERT_EQ(2, a4.size());
686 EXPECT_EQ(1, a4.GetElement(0));
687 EXPECT_EQ(2, a4.GetElement(1));
688}
689
zhanyong.wan9644db82009-06-24 23:02:50 +0000690// Tests the GetElement accessor.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000691TEST(ListDeathTest, GetElement) {
zhanyong.wana8a582f2009-07-13 19:25:02 +0000692 Vector<int> a;
zhanyong.wan9644db82009-06-24 23:02:50 +0000693 a.PushBack(0);
694 a.PushBack(1);
695 a.PushBack(2);
696
zhanyong.wan449f84d2009-07-01 22:55:05 +0000697 EXPECT_EQ(0, a.GetElement(0));
698 EXPECT_EQ(1, a.GetElement(1));
699 EXPECT_EQ(2, a.GetElement(2));
700 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
701 a.GetElement(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000702 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +0000703 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
704 a.GetElement(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +0000705 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +0000706}
shiqian4b6829f2008-07-03 22:38:12 +0000707
708// Tests the String class.
709
710// Tests String's constructors.
711TEST(StringTest, Constructors) {
712 // Default ctor.
713 String s1;
shiqiandd4a17b2008-07-31 18:34:08 +0000714 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
715 // pointers with NULL isn't supported on all platforms.
716 EXPECT_TRUE(NULL == s1.c_str());
shiqian4b6829f2008-07-03 22:38:12 +0000717
718 // Implicitly constructs from a C-string.
719 String s2 = "Hi";
720 EXPECT_STREQ("Hi", s2.c_str());
721
722 // Constructs from a C-string and a length.
723 String s3("hello", 3);
724 EXPECT_STREQ("hel", s3.c_str());
725
726 // Copy ctor.
727 String s4 = s3;
728 EXPECT_STREQ("hel", s4.c_str());
729}
730
vladlosevf179f4e2008-11-26 20:48:45 +0000731#if GTEST_HAS_STD_STRING
732
733TEST(StringTest, ConvertsFromStdString) {
734 // An empty std::string.
735 const std::string src1("");
736 const String dest1 = src1;
737 EXPECT_STREQ("", dest1.c_str());
738
739 // A normal std::string.
740 const std::string src2("Hi");
741 const String dest2 = src2;
742 EXPECT_STREQ("Hi", dest2.c_str());
743
744 // An std::string with an embedded NUL character.
745 const char src3[] = "Hello\0world.";
746 const String dest3 = std::string(src3, sizeof(src3));
747 EXPECT_STREQ("Hello", dest3.c_str());
748}
749
750TEST(StringTest, ConvertsToStdString) {
751 // An empty String.
752 const String src1("");
753 const std::string dest1 = src1;
754 EXPECT_EQ("", dest1);
755
756 // A normal String.
757 const String src2("Hi");
758 const std::string dest2 = src2;
759 EXPECT_EQ("Hi", dest2);
760}
761
762#endif // GTEST_HAS_STD_STRING
763
764#if GTEST_HAS_GLOBAL_STRING
765
766TEST(StringTest, ConvertsFromGlobalString) {
767 // An empty ::string.
768 const ::string src1("");
769 const String dest1 = src1;
770 EXPECT_STREQ("", dest1.c_str());
771
772 // A normal ::string.
773 const ::string src2("Hi");
774 const String dest2 = src2;
775 EXPECT_STREQ("Hi", dest2.c_str());
776
777 // An ::string with an embedded NUL character.
778 const char src3[] = "Hello\0world.";
779 const String dest3 = ::string(src3, sizeof(src3));
780 EXPECT_STREQ("Hello", dest3.c_str());
781}
782
783TEST(StringTest, ConvertsToGlobalString) {
784 // An empty String.
785 const String src1("");
786 const ::string dest1 = src1;
787 EXPECT_EQ("", dest1);
788
789 // A normal String.
790 const String src2("Hi");
791 const ::string dest2 = src2;
792 EXPECT_EQ("Hi", dest2);
793}
794
795#endif // GTEST_HAS_GLOBAL_STRING
796
shiqian4b6829f2008-07-03 22:38:12 +0000797// Tests String::ShowCString().
798TEST(StringTest, ShowCString) {
799 EXPECT_STREQ("(null)", String::ShowCString(NULL));
800 EXPECT_STREQ("", String::ShowCString(""));
801 EXPECT_STREQ("foo", String::ShowCString("foo"));
802}
803
804// Tests String::ShowCStringQuoted().
805TEST(StringTest, ShowCStringQuoted) {
806 EXPECT_STREQ("(null)",
807 String::ShowCStringQuoted(NULL).c_str());
808 EXPECT_STREQ("\"\"",
809 String::ShowCStringQuoted("").c_str());
810 EXPECT_STREQ("\"foo\"",
811 String::ShowCStringQuoted("foo").c_str());
812}
813
814// Tests String::operator==().
815TEST(StringTest, Equals) {
816 const String null(NULL);
817 EXPECT_TRUE(null == NULL); // NOLINT
818 EXPECT_FALSE(null == ""); // NOLINT
819 EXPECT_FALSE(null == "bar"); // NOLINT
820
821 const String empty("");
822 EXPECT_FALSE(empty == NULL); // NOLINT
823 EXPECT_TRUE(empty == ""); // NOLINT
824 EXPECT_FALSE(empty == "bar"); // NOLINT
825
826 const String foo("foo");
827 EXPECT_FALSE(foo == NULL); // NOLINT
828 EXPECT_FALSE(foo == ""); // NOLINT
829 EXPECT_FALSE(foo == "bar"); // NOLINT
830 EXPECT_TRUE(foo == "foo"); // NOLINT
831}
832
833// Tests String::operator!=().
834TEST(StringTest, NotEquals) {
835 const String null(NULL);
836 EXPECT_FALSE(null != NULL); // NOLINT
837 EXPECT_TRUE(null != ""); // NOLINT
838 EXPECT_TRUE(null != "bar"); // NOLINT
839
840 const String empty("");
841 EXPECT_TRUE(empty != NULL); // NOLINT
842 EXPECT_FALSE(empty != ""); // NOLINT
843 EXPECT_TRUE(empty != "bar"); // NOLINT
844
845 const String foo("foo");
846 EXPECT_TRUE(foo != NULL); // NOLINT
847 EXPECT_TRUE(foo != ""); // NOLINT
848 EXPECT_TRUE(foo != "bar"); // NOLINT
849 EXPECT_FALSE(foo != "foo"); // NOLINT
850}
851
852// Tests String::EndsWith().
853TEST(StringTest, EndsWith) {
854 EXPECT_TRUE(String("foobar").EndsWith("bar"));
855 EXPECT_TRUE(String("foobar").EndsWith(""));
856 EXPECT_TRUE(String("").EndsWith(""));
857
858 EXPECT_FALSE(String("foobar").EndsWith("foo"));
859 EXPECT_FALSE(String("").EndsWith("foo"));
860}
861
862// Tests String::EndsWithCaseInsensitive().
863TEST(StringTest, EndsWithCaseInsensitive) {
864 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
865 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
866 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
867 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
868
869 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
870 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
871 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
872}
873
zhanyong.wan98efcc42009-04-28 00:28:09 +0000874// C++Builder's preprocessor is buggy; it fails to expand macros that
875// appear in macro parameters after wide char literals. Provide an alias
876// for NULL as a workaround.
877static const wchar_t* const kNull = NULL;
878
shiqiane8ff1482008-09-08 17:55:52 +0000879// Tests String::CaseInsensitiveWideCStringEquals
880TEST(StringTest, CaseInsensitiveWideCStringEquals) {
881 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +0000882 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
883 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
884 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
885 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +0000886 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
887 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
888 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
889}
890
shiqian4b6829f2008-07-03 22:38:12 +0000891// Tests that NULL can be assigned to a String.
892TEST(StringTest, CanBeAssignedNULL) {
893 const String src(NULL);
894 String dest;
895
896 dest = src;
897 EXPECT_STREQ(NULL, dest.c_str());
898}
899
900// Tests that the empty string "" can be assigned to a String.
901TEST(StringTest, CanBeAssignedEmpty) {
902 const String src("");
903 String dest;
904
905 dest = src;
906 EXPECT_STREQ("", dest.c_str());
907}
908
909// Tests that a non-empty string can be assigned to a String.
910TEST(StringTest, CanBeAssignedNonEmpty) {
911 const String src("hello");
912 String dest;
913
914 dest = src;
915 EXPECT_STREQ("hello", dest.c_str());
916}
917
918// Tests that a String can be assigned to itself.
919TEST(StringTest, CanBeAssignedSelf) {
920 String dest("hello");
921
922 dest = dest;
923 EXPECT_STREQ("hello", dest.c_str());
924}
925
zhanyong.wan4cd62602009-02-23 23:21:55 +0000926#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +0000927
928// Tests String::ShowWideCString().
929TEST(StringTest, ShowWideCString) {
930 EXPECT_STREQ("(null)",
931 String::ShowWideCString(NULL).c_str());
932 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
933 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
934}
935
936// Tests String::ShowWideCStringQuoted().
937TEST(StringTest, ShowWideCStringQuoted) {
938 EXPECT_STREQ("(null)",
939 String::ShowWideCStringQuoted(NULL).c_str());
940 EXPECT_STREQ("L\"\"",
941 String::ShowWideCStringQuoted(L"").c_str());
942 EXPECT_STREQ("L\"foo\"",
943 String::ShowWideCStringQuoted(L"foo").c_str());
944}
945
shiqiandd4a17b2008-07-31 18:34:08 +0000946#ifdef _WIN32_WCE
947TEST(StringTest, AnsiAndUtf16Null) {
948 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
949 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
950}
951
952TEST(StringTest, AnsiAndUtf16ConvertBasic) {
953 const char* ansi = String::Utf16ToAnsi(L"str");
954 EXPECT_STREQ("str", ansi);
955 delete [] ansi;
956 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +0000957 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +0000958 delete [] utf16;
959}
960
961TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
962 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
963 EXPECT_STREQ(".:\\ \"*?", ansi);
964 delete [] ansi;
965 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +0000966 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +0000967 delete [] utf16;
968}
969#endif // _WIN32_WCE
970
shiqian4b6829f2008-07-03 22:38:12 +0000971#endif // GTEST_OS_WINDOWS
972
973// Tests TestProperty construction.
974TEST(TestPropertyTest, StringValue) {
975 TestProperty property("key", "1");
976 EXPECT_STREQ("key", property.key());
977 EXPECT_STREQ("1", property.value());
978}
979
980// Tests TestProperty replacing a value.
981TEST(TestPropertyTest, ReplaceStringValue) {
982 TestProperty property("key", "1");
983 EXPECT_STREQ("1", property.value());
984 property.SetValue("2");
985 EXPECT_STREQ("2", property.value());
986}
987
zhanyong.wan98efcc42009-04-28 00:28:09 +0000988// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
989// functions (i.e. their definitions cannot be inlined at the call
990// sites), or C++Builder won't compile the code.
991static void AddFatalFailure() {
992 FAIL() << "Expected fatal failure.";
993}
994
995static void AddNonfatalFailure() {
996 ADD_FAILURE() << "Expected non-fatal failure.";
997}
998
shiqiane44602e2008-10-11 07:20:02 +0000999class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001000 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001001 enum FailureMode {
1002 FATAL_FAILURE,
1003 NONFATAL_FAILURE
1004 };
1005 static void AddFailure(FailureMode failure) {
1006 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001007 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001008 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001009 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001010 }
1011 }
shiqian4b6829f2008-07-03 22:38:12 +00001012};
1013
shiqian4b6829f2008-07-03 22:38:12 +00001014// Tests that ScopedFakeTestPartResultReporter intercepts test
1015// failures.
shiqiane44602e2008-10-11 07:20:02 +00001016TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001017 TestPartResultArray results;
1018 {
shiqiane44602e2008-10-11 07:20:02 +00001019 ScopedFakeTestPartResultReporter reporter(
1020 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1021 &results);
1022 AddFailure(NONFATAL_FAILURE);
1023 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001024 }
1025
1026 EXPECT_EQ(2, results.size());
1027 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1028 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1029}
1030
shiqiane44602e2008-10-11 07:20:02 +00001031TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1032 TestPartResultArray results;
1033 {
1034 // Tests, that the deprecated constructor still works.
1035 ScopedFakeTestPartResultReporter reporter(&results);
1036 AddFailure(NONFATAL_FAILURE);
1037 }
1038 EXPECT_EQ(1, results.size());
1039}
1040
1041#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1042
1043class ScopedFakeTestPartResultReporterWithThreadsTest
1044 : public ScopedFakeTestPartResultReporterTest {
1045 protected:
1046 static void AddFailureInOtherThread(FailureMode failure) {
1047 pthread_t tid;
1048 pthread_create(&tid,
1049 NULL,
1050 ScopedFakeTestPartResultReporterWithThreadsTest::
1051 FailureThread,
1052 &failure);
1053 pthread_join(tid, NULL);
1054 }
1055 private:
1056 static void* FailureThread(void* attr) {
1057 FailureMode* failure = static_cast<FailureMode*>(attr);
1058 AddFailure(*failure);
1059 return NULL;
1060 }
1061};
1062
1063TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1064 InterceptsTestFailuresInAllThreads) {
1065 TestPartResultArray results;
1066 {
1067 ScopedFakeTestPartResultReporter reporter(
1068 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1069 AddFailure(NONFATAL_FAILURE);
1070 AddFailure(FATAL_FAILURE);
1071 AddFailureInOtherThread(NONFATAL_FAILURE);
1072 AddFailureInOtherThread(FATAL_FAILURE);
1073 }
1074
1075 EXPECT_EQ(4, results.size());
1076 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1077 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1078 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1079 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1080}
1081
1082#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1083
zhanyong.wan98efcc42009-04-28 00:28:09 +00001084// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1085// work even if the failure is generated in a called function rather than
1086// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001087
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001088typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001089
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001090TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001091 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001092}
1093
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001094TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1095 // We have another test below to verify that the macro catches fatal
1096 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001097 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001098 "Expected fatal failure.");
1099}
1100
zhanyong.wan98efcc42009-04-28 00:28:09 +00001101#ifdef __BORLANDC__
1102// Silences warnings: "Condition is always true"
1103#pragma option push -w-ccc
1104#endif
1105
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001106// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1107// function even when the statement in it contains ASSERT_*.
1108
1109int NonVoidFunction() {
1110 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1111 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1112 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001113}
1114
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001115TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1116 NonVoidFunction();
1117}
1118
1119// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1120// current function even though 'statement' generates a fatal failure.
1121
1122void DoesNotAbortHelper(bool* aborted) {
1123 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1124 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1125
1126 *aborted = false;
1127}
1128
zhanyong.wan98efcc42009-04-28 00:28:09 +00001129#ifdef __BORLANDC__
1130// Restores warnings after previous "#pragma option push" supressed them
1131#pragma option pop
1132#endif
1133
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001134TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1135 bool aborted = true;
1136 DoesNotAbortHelper(&aborted);
1137 EXPECT_FALSE(aborted);
1138}
1139
1140// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1141// statement that contains a macro which expands to code containing an
1142// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001143
1144static int global_var = 0;
1145#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1146
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001147TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001148#ifndef __BORLANDC__
1149 // ICE's in C++Builder 2007.
shiqiane44602e2008-10-11 07:20:02 +00001150 EXPECT_FATAL_FAILURE({
1151 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001152 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001153 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001154#endif
shiqiane44602e2008-10-11 07:20:02 +00001155
1156 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1157 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001158 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001159 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001160}
shiqiane44602e2008-10-11 07:20:02 +00001161
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001162// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1163
1164typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1165
1166TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001167 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001168 "Expected non-fatal failure.");
1169}
1170
1171TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1172 // We have another test below to verify that the macro catches
1173 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001174 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001175 "Expected non-fatal failure.");
1176}
1177
1178// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1179// statement that contains a macro which expands to code containing an
1180// unprotected comma.
1181TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001182 EXPECT_NONFATAL_FAILURE({
1183 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001184 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001185 }, "");
1186
1187 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1188 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001189 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001190 }, "");
1191}
1192
1193#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1194
1195typedef ScopedFakeTestPartResultReporterWithThreadsTest
1196 ExpectFailureWithThreadsTest;
1197
1198TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1199 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1200 "Expected fatal failure.");
1201}
1202
1203TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1204 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1205 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1206}
1207
1208#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
1209
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001210// Tests the TestProperty class.
1211
1212TEST(TestPropertyTest, ConstructorWorks) {
1213 const TestProperty property("key", "value");
1214 EXPECT_STREQ("key", property.key());
1215 EXPECT_STREQ("value", property.value());
1216}
1217
1218TEST(TestPropertyTest, SetValue) {
1219 TestProperty property("key", "value_1");
1220 EXPECT_STREQ("key", property.key());
1221 property.SetValue("value_2");
1222 EXPECT_STREQ("key", property.key());
1223 EXPECT_STREQ("value_2", property.value());
1224}
1225
1226// Tests the TestPartResult class.
1227
1228TEST(TestPartResultTest, ConstructorWorks) {
1229 Message message;
1230 message << "something is terribly wrong";
1231 message << static_cast<const char*>(testing::internal::kStackTraceMarker);
1232 message << "some unimportant stack trace";
1233
1234 const TestPartResult result(TPRT_NONFATAL_FAILURE,
1235 "some_file.cc",
1236 42,
1237 message.GetString().c_str());
1238
1239 EXPECT_EQ(TPRT_NONFATAL_FAILURE, result.type());
1240 EXPECT_STREQ("some_file.cc", result.file_name());
1241 EXPECT_EQ(42, result.line_number());
1242 EXPECT_STREQ(message.GetString().c_str(), result.message());
1243 EXPECT_STREQ("something is terribly wrong", result.summary());
1244}
1245
1246TEST(TestPartResultTest, ResultAccessorsWork) {
1247 const TestPartResult success(TPRT_SUCCESS, "file.cc", 42, "message");
1248 EXPECT_TRUE(success.passed());
1249 EXPECT_FALSE(success.failed());
1250 EXPECT_FALSE(success.nonfatally_failed());
1251 EXPECT_FALSE(success.fatally_failed());
1252
1253 const TestPartResult nonfatal_failure(TPRT_NONFATAL_FAILURE,
1254 "file.cc",
1255 42,
1256 "message");
1257 EXPECT_FALSE(nonfatal_failure.passed());
1258 EXPECT_TRUE(nonfatal_failure.failed());
1259 EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
1260 EXPECT_FALSE(nonfatal_failure.fatally_failed());
1261
1262 const TestPartResult fatal_failure(TPRT_FATAL_FAILURE,
1263 "file.cc",
1264 42,
1265 "message");
1266 EXPECT_FALSE(fatal_failure.passed());
1267 EXPECT_TRUE(fatal_failure.failed());
1268 EXPECT_FALSE(fatal_failure.nonfatally_failed());
1269 EXPECT_TRUE(fatal_failure.fatally_failed());
1270}
1271
shiqian4b6829f2008-07-03 22:38:12 +00001272// Tests the TestResult class
1273
1274// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001275class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001276 protected:
zhanyong.wana8a582f2009-07-13 19:25:02 +00001277 typedef Vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001278
1279 // We make use of 2 TestPartResult objects,
1280 TestPartResult * pr1, * pr2;
1281
1282 // ... and 3 TestResult objects.
1283 TestResult * r0, * r1, * r2;
1284
1285 virtual void SetUp() {
1286 // pr1 is for success.
shiqian760af5c2008-08-06 21:43:15 +00001287 pr1 = new TestPartResult(TPRT_SUCCESS, "foo/bar.cc", 10, "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001288
1289 // pr2 is for fatal failure.
shiqian760af5c2008-08-06 21:43:15 +00001290 pr2 = new TestPartResult(TPRT_FATAL_FAILURE, "foo/bar.cc",
1291 -1, // This line number means "unknown"
1292 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001293
1294 // Creates the TestResult objects.
1295 r0 = new TestResult();
1296 r1 = new TestResult();
1297 r2 = new TestResult();
1298
1299 // In order to test TestResult, we need to modify its internal
zhanyong.wana8a582f2009-07-13 19:25:02 +00001300 // state, in particular the TestPartResult Vector it holds.
1301 // test_part_results() returns a const reference to this Vector.
shiqian4b6829f2008-07-03 22:38:12 +00001302 // We cast it to a non-const object s.t. it can be modified (yes,
1303 // this is a hack).
zhanyong.wana8a582f2009-07-13 19:25:02 +00001304 TPRVector* results1 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001305 &TestResultAccessor::test_part_results(*r1));
zhanyong.wana8a582f2009-07-13 19:25:02 +00001306 TPRVector* results2 = const_cast<Vector<TestPartResult> *>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001307 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001308
1309 // r0 is an empty TestResult.
1310
1311 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001312 results1->PushBack(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001313
1314 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wana8a582f2009-07-13 19:25:02 +00001315 results2->PushBack(*pr1);
1316 results2->PushBack(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001317 }
1318
1319 virtual void TearDown() {
1320 delete pr1;
1321 delete pr2;
1322
1323 delete r0;
1324 delete r1;
1325 delete r2;
1326 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001327
1328 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001329 static void CompareTestPartResult(const TestPartResult& expected,
1330 const TestPartResult& actual) {
1331 EXPECT_EQ(expected.type(), actual.type());
1332 EXPECT_STREQ(expected.file_name(), actual.file_name());
1333 EXPECT_EQ(expected.line_number(), actual.line_number());
1334 EXPECT_STREQ(expected.summary(), actual.summary());
1335 EXPECT_STREQ(expected.message(), actual.message());
1336 EXPECT_EQ(expected.passed(), actual.passed());
1337 EXPECT_EQ(expected.failed(), actual.failed());
1338 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1339 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001340 }
shiqian4b6829f2008-07-03 22:38:12 +00001341};
1342
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001343// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001344TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001345 ASSERT_EQ(0, r0->total_part_count());
1346 ASSERT_EQ(1, r1->total_part_count());
1347 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001348}
1349
zhanyong.wan9644db82009-06-24 23:02:50 +00001350// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001351TEST_F(TestResultTest, Passed) {
1352 ASSERT_TRUE(r0->Passed());
1353 ASSERT_TRUE(r1->Passed());
1354 ASSERT_FALSE(r2->Passed());
1355}
1356
zhanyong.wan9644db82009-06-24 23:02:50 +00001357// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001358TEST_F(TestResultTest, Failed) {
1359 ASSERT_FALSE(r0->Failed());
1360 ASSERT_FALSE(r1->Failed());
1361 ASSERT_TRUE(r2->Failed());
1362}
1363
zhanyong.wan9644db82009-06-24 23:02:50 +00001364// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001365
1366typedef TestResultTest TestResultDeathTest;
1367
1368TEST_F(TestResultDeathTest, GetTestPartResult) {
1369 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1370 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1371 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1372 r2->GetTestPartResult(2),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001373 "Invalid Vector index 2: must be in range \\[0, 1\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001374 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1375 r2->GetTestPartResult(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001376 "Invalid Vector index -1: must be in range \\[0, 1\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001377}
1378
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001379// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001380TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1381 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001382 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001383}
1384
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001385// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001386TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1387 TestResult test_result;
1388 TestProperty property("key_1", "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001389 TestResultAccessor::RecordProperty(&test_result, property);
1390 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001391 const TestProperty& actual_property = test_result.GetTestProperty(0);
1392 EXPECT_STREQ("key_1", actual_property.key());
1393 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001394}
1395
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001396// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001397TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1398 TestResult test_result;
1399 TestProperty property_1("key_1", "1");
1400 TestProperty property_2("key_2", "2");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001401 TestResultAccessor::RecordProperty(&test_result, property_1);
1402 TestResultAccessor::RecordProperty(&test_result, property_2);
1403 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001404 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1405 EXPECT_STREQ("key_1", actual_property_1.key());
1406 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001407
zhanyong.wan449f84d2009-07-01 22:55:05 +00001408 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1409 EXPECT_STREQ("key_2", actual_property_2.key());
1410 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001411}
1412
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001413// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001414TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1415 TestResult test_result;
1416 TestProperty property_1_1("key_1", "1");
1417 TestProperty property_2_1("key_2", "2");
1418 TestProperty property_1_2("key_1", "12");
1419 TestProperty property_2_2("key_2", "22");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001420 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1421 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1422 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1423 TestResultAccessor::RecordProperty(&test_result, property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001424
zhanyong.wan9644db82009-06-24 23:02:50 +00001425 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001426 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1427 EXPECT_STREQ("key_1", actual_property_1.key());
1428 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001429
zhanyong.wan449f84d2009-07-01 22:55:05 +00001430 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1431 EXPECT_STREQ("key_2", actual_property_2.key());
1432 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001433}
1434
1435// Tests TestResult::GetTestProperty().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001436TEST(TestResultPropertyDeathTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001437 TestResult test_result;
1438 TestProperty property_1("key_1", "1");
1439 TestProperty property_2("key_2", "2");
1440 TestProperty property_3("key_3", "3");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001441 TestResultAccessor::RecordProperty(&test_result, property_1);
1442 TestResultAccessor::RecordProperty(&test_result, property_2);
1443 TestResultAccessor::RecordProperty(&test_result, property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001444
zhanyong.wan449f84d2009-07-01 22:55:05 +00001445 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1446 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1447 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001448
zhanyong.wan449f84d2009-07-01 22:55:05 +00001449 EXPECT_STREQ("key_1", fetched_property_1.key());
1450 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001451
zhanyong.wan449f84d2009-07-01 22:55:05 +00001452 EXPECT_STREQ("key_2", fetched_property_2.key());
1453 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001454
zhanyong.wan449f84d2009-07-01 22:55:05 +00001455 EXPECT_STREQ("key_3", fetched_property_3.key());
1456 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001457
zhanyong.wan449f84d2009-07-01 22:55:05 +00001458 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1459 test_result.GetTestProperty(3),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001460 "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001461 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1462 test_result.GetTestProperty(-1),
zhanyong.wana8a582f2009-07-13 19:25:02 +00001463 "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
zhanyong.wan9644db82009-06-24 23:02:50 +00001464}
1465
shiqian4b6829f2008-07-03 22:38:12 +00001466// When a property using a reserved key is supplied to this function, it tests
1467// that a non-fatal failure is added, a fatal failure is not added, and that the
1468// property is not recorded.
1469void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1470 TestResult test_result;
zhanyong.wanb0a12f72009-01-29 06:49:00 +00001471 TestProperty property(key, "1");
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001472 EXPECT_NONFATAL_FAILURE(
1473 TestResultAccessor::RecordProperty(&test_result, property),
1474 "Reserved key");
1475 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
shiqian4b6829f2008-07-03 22:38:12 +00001476}
1477
1478// Attempting to recording a property with the Reserved literal "name"
1479// should add a non-fatal failure and the property should not be recorded.
1480TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1481 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1482}
1483
1484// Attempting to recording a property with the Reserved literal "status"
1485// should add a non-fatal failure and the property should not be recorded.
1486TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1487 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1488}
1489
1490// Attempting to recording a property with the Reserved literal "time"
1491// should add a non-fatal failure and the property should not be recorded.
1492TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1493 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1494}
1495
1496// Attempting to recording a property with the Reserved literal "classname"
1497// should add a non-fatal failure and the property should not be recorded.
1498TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1499 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1500}
1501
1502// Tests that GTestFlagSaver works on Windows and Mac.
1503
shiqian760af5c2008-08-06 21:43:15 +00001504class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001505 protected:
1506 // Saves the Google Test flags such that we can restore them later, and
1507 // then sets them to their default values. This will be called
1508 // before the first test in this test case is run.
1509 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001510 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001511
shiqianca6949f2009-01-10 01:16:33 +00001512 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001513 GTEST_FLAG(break_on_failure) = false;
1514 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001515 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001516 GTEST_FLAG(color) = "auto";
1517 GTEST_FLAG(filter) = "";
1518 GTEST_FLAG(list_tests) = false;
1519 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001520 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001521 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001522 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001523 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001524 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001525 }
1526
1527 // Restores the Google Test flags that the tests have modified. This will
1528 // be called after the last test in this test case is run.
1529 static void TearDownTestCase() {
1530 delete saver_;
1531 saver_ = NULL;
1532 }
1533
1534 // Verifies that the Google Test flags have their default values, and then
1535 // modifies each of them.
1536 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001537 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001538 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1539 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1540 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001541 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001542 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1543 EXPECT_FALSE(GTEST_FLAG(list_tests));
1544 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001545 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001546 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001547 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001548 EXPECT_FALSE(GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001549 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001550
shiqianca6949f2009-01-10 01:16:33 +00001551 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001552 GTEST_FLAG(break_on_failure) = true;
1553 GTEST_FLAG(catch_exceptions) = true;
1554 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001555 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001556 GTEST_FLAG(filter) = "abc";
1557 GTEST_FLAG(list_tests) = true;
1558 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001559 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001560 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001561 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001562 GTEST_FLAG(shuffle) = true;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001563 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001564 }
1565 private:
1566 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001567 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001568};
1569
shiqian760af5c2008-08-06 21:43:15 +00001570GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001571
1572// Google Test doesn't guarantee the order of tests. The following two
1573// tests are designed to work regardless of their order.
1574
1575// Modifies the Google Test flags in the test body.
1576TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1577 VerifyAndModifyFlags();
1578}
1579
1580// Verifies that the Google Test flags in the body of the previous test were
1581// restored to their original values.
1582TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1583 VerifyAndModifyFlags();
1584}
1585
1586// Sets an environment variable with the given name to the given
1587// value. If the value argument is "", unsets the environment
1588// variable. The caller must ensure that both arguments are not NULL.
1589static void SetEnv(const char* name, const char* value) {
1590#ifdef _WIN32_WCE
1591 // Environment variables are not supported on Windows CE.
1592 return;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001593#elif defined(__BORLANDC__)
1594 // C++Builder's putenv only stores a pointer to its parameter; we have to
1595 // ensure that the string remains valid as long as it might be needed.
1596 // We use an std::map to do so.
1597 static std::map<String, String*> added_env;
1598
1599 // Because putenv stores a pointer to the string buffer, we can't delete the
1600 // previous string (if present) until after it's replaced.
1601 String *prev_env = NULL;
1602 if (added_env.find(name) != added_env.end()) {
1603 prev_env = added_env[name];
1604 }
1605 added_env[name] = new String((Message() << name << "=" << value).GetString());
1606 putenv(added_env[name]->c_str());
1607 delete prev_env;
1608
zhanyong.wan4cd62602009-02-23 23:21:55 +00001609#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001610 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001611#else
1612 if (*value == '\0') {
1613 unsetenv(name);
1614 } else {
1615 setenv(name, value, 1);
1616 }
1617#endif
1618}
1619
1620#ifndef _WIN32_WCE
1621// Environment variables are not supported on Windows CE.
1622
shiqian760af5c2008-08-06 21:43:15 +00001623using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001624
1625// Tests Int32FromGTestEnv().
1626
1627// Tests that Int32FromGTestEnv() returns the default value when the
1628// environment variable is not set.
1629TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001630 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001631 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1632}
1633
1634// Tests that Int32FromGTestEnv() returns the default value when the
1635// environment variable overflows as an Int32.
1636TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1637 printf("(expecting 2 warnings)\n");
1638
zhanyong.wan4cd62602009-02-23 23:21:55 +00001639 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001640 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1641
zhanyong.wan4cd62602009-02-23 23:21:55 +00001642 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001643 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1644}
1645
1646// Tests that Int32FromGTestEnv() returns the default value when the
1647// environment variable does not represent a valid decimal integer.
1648TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1649 printf("(expecting 2 warnings)\n");
1650
zhanyong.wan4cd62602009-02-23 23:21:55 +00001651 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001652 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1653
zhanyong.wan4cd62602009-02-23 23:21:55 +00001654 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001655 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1656}
1657
1658// Tests that Int32FromGTestEnv() parses and returns the value of the
1659// environment variable when it represents a valid decimal integer in
1660// the range of an Int32.
1661TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001662 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001663 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1664
zhanyong.wan4cd62602009-02-23 23:21:55 +00001665 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001666 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1667}
1668#endif // !defined(_WIN32_WCE)
1669
1670// Tests ParseInt32Flag().
1671
1672// Tests that ParseInt32Flag() returns false and doesn't change the
1673// output value when the flag has wrong format
1674TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1675 Int32 value = 123;
1676 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1677 EXPECT_EQ(123, value);
1678
1679 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1680 EXPECT_EQ(123, value);
1681}
1682
1683// Tests that ParseInt32Flag() returns false and doesn't change the
1684// output value when the flag overflows as an Int32.
1685TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1686 printf("(expecting 2 warnings)\n");
1687
1688 Int32 value = 123;
1689 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1690 EXPECT_EQ(123, value);
1691
1692 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1693 EXPECT_EQ(123, value);
1694}
1695
1696// Tests that ParseInt32Flag() returns false and doesn't change the
1697// output value when the flag does not represent a valid decimal
1698// integer.
1699TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1700 printf("(expecting 2 warnings)\n");
1701
1702 Int32 value = 123;
1703 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1704 EXPECT_EQ(123, value);
1705
1706 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1707 EXPECT_EQ(123, value);
1708}
1709
1710// Tests that ParseInt32Flag() parses the value of the flag and
1711// returns true when the flag represents a valid decimal integer in
1712// the range of an Int32.
1713TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1714 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001715 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001716 EXPECT_EQ(456, value);
1717
zhanyong.wan98efcc42009-04-28 00:28:09 +00001718 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1719 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001720 EXPECT_EQ(-789, value);
1721}
1722
zhanyong.wan905074c2009-02-09 18:05:21 +00001723// Tests that Int32FromEnvOrDie() parses the value of the var or
1724// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001725// Environment variables are not supported on Windows CE.
1726#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001727TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001728 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1729 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1730 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1731 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1732 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001733}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001734#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001735
1736// Tests that Int32FromEnvOrDie() aborts with an error message
1737// if the variable is not an Int32.
1738TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001739 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001740 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1741 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1742 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001743}
1744
1745// Tests that Int32FromEnvOrDie() aborts with an error message
1746// if the variable cannot be represnted by an Int32.
1747TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001748 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001749 GTEST_EXPECT_DEATH_IF_SUPPORTED_(
1750 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1751 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001752}
1753
zhanyong.wan905074c2009-02-09 18:05:21 +00001754// Tests that ShouldRunTestOnShard() selects all tests
1755// where there is 1 shard.
1756TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1757 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1758 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1759 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1760 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1761 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1762}
1763
1764class ShouldShardTest : public testing::Test {
1765 protected:
1766 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001767 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1768 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00001769 }
1770
1771 virtual void TearDown() {
1772 SetEnv(index_var_, "");
1773 SetEnv(total_var_, "");
1774 }
1775
1776 const char* index_var_;
1777 const char* total_var_;
1778};
1779
1780// Tests that sharding is disabled if neither of the environment variables
1781// are set.
1782TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1783 SetEnv(index_var_, "");
1784 SetEnv(total_var_, "");
1785
1786 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1787 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1788}
1789
1790// Tests that sharding is not enabled if total_shards == 1.
1791TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1792 SetEnv(index_var_, "0");
1793 SetEnv(total_var_, "1");
1794 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1795 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1796}
1797
1798// Tests that sharding is enabled if total_shards > 1 and
1799// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001800// Environment variables are not supported on Windows CE.
1801#ifndef _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001802TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1803 SetEnv(index_var_, "4");
1804 SetEnv(total_var_, "22");
1805 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1806 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1807
1808 SetEnv(index_var_, "8");
1809 SetEnv(total_var_, "9");
1810 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1811 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1812
1813 SetEnv(index_var_, "0");
1814 SetEnv(total_var_, "9");
1815 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1816 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1817}
zhanyong.wan449f84d2009-07-01 22:55:05 +00001818#endif // _WIN32_WCE
zhanyong.wan905074c2009-02-09 18:05:21 +00001819
1820// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001821
1822typedef ShouldShardTest ShouldShardDeathTest;
1823
1824TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00001825 SetEnv(index_var_, "4");
1826 SetEnv(total_var_, "4");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001827 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1828 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001829
1830 SetEnv(index_var_, "4");
1831 SetEnv(total_var_, "-2");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001832 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1833 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001834
1835 SetEnv(index_var_, "5");
1836 SetEnv(total_var_, "");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001837 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1838 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001839
1840 SetEnv(index_var_, "");
1841 SetEnv(total_var_, "5");
zhanyong.wan449f84d2009-07-01 22:55:05 +00001842 GTEST_EXPECT_DEATH_IF_SUPPORTED_(ShouldShard(total_var_, index_var_, false),
1843 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001844}
1845
zhanyong.wan905074c2009-02-09 18:05:21 +00001846// Tests that ShouldRunTestOnShard is a partition when 5
1847// shards are used.
1848TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1849 // Choose an arbitrary number of tests and shards.
1850 const int num_tests = 17;
1851 const int num_shards = 5;
1852
1853 // Check partitioning: each test should be on exactly 1 shard.
1854 for (int test_id = 0; test_id < num_tests; test_id++) {
1855 int prev_selected_shard_index = -1;
1856 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1857 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1858 if (prev_selected_shard_index < 0) {
1859 prev_selected_shard_index = shard_index;
1860 } else {
1861 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1862 << shard_index << " are both selected to run test " << test_id;
1863 }
1864 }
1865 }
1866 }
1867
1868 // Check balance: This is not required by the sharding protocol, but is a
1869 // desirable property for performance.
1870 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1871 int num_tests_on_shard = 0;
1872 for (int test_id = 0; test_id < num_tests; test_id++) {
1873 num_tests_on_shard +=
1874 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1875 }
1876 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1877 }
1878}
1879
shiqian4b6829f2008-07-03 22:38:12 +00001880// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00001881// Test class, there are no separate tests for the following classes
1882// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00001883//
1884// TestCase, UnitTest, UnitTestResultPrinter.
1885//
1886// Similarly, there are no separate tests for the following macros:
1887//
1888// TEST, TEST_F, RUN_ALL_TESTS
1889
shiqianc3b4de32008-09-12 04:01:37 +00001890TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1891 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1892 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1893}
1894
shiqian4b6829f2008-07-03 22:38:12 +00001895// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
1896// of various arities. They do not attempt to be exhaustive. Rather,
1897// view them as smoke tests that can be easily reviewed and verified.
1898// A more complete set of tests for predicate assertions can be found
1899// in gtest_pred_impl_unittest.cc.
1900
1901// First, some predicates and predicate-formatters needed by the tests.
1902
1903// Returns true iff the argument is an even number.
1904bool IsEven(int n) {
1905 return (n % 2) == 0;
1906}
1907
1908// A functor that returns true iff the argument is an even number.
1909struct IsEvenFunctor {
1910 bool operator()(int n) { return IsEven(n); }
1911};
1912
1913// A predicate-formatter function that asserts the argument is an even
1914// number.
shiqian760af5c2008-08-06 21:43:15 +00001915AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00001916 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00001917 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001918 }
1919
shiqian760af5c2008-08-06 21:43:15 +00001920 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001921 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001922 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001923}
1924
1925// A predicate-formatter functor that asserts the argument is an even
1926// number.
1927struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00001928 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00001929 return AssertIsEven(expr, n);
1930 }
1931};
1932
1933// Returns true iff the sum of the arguments is an even number.
1934bool SumIsEven2(int n1, int n2) {
1935 return IsEven(n1 + n2);
1936}
1937
1938// A functor that returns true iff the sum of the arguments is an even
1939// number.
1940struct SumIsEven3Functor {
1941 bool operator()(int n1, int n2, int n3) {
1942 return IsEven(n1 + n2 + n3);
1943 }
1944};
1945
1946// A predicate-formatter function that asserts the sum of the
1947// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00001948AssertionResult AssertSumIsEven4(
1949 const char* e1, const char* e2, const char* e3, const char* e4,
1950 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00001951 const int sum = n1 + n2 + n3 + n4;
1952 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00001953 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001954 }
1955
shiqian760af5c2008-08-06 21:43:15 +00001956 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001957 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
1958 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
1959 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001960 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001961}
1962
1963// A predicate-formatter functor that asserts the sum of the arguments
1964// is an even number.
1965struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00001966 AssertionResult operator()(
1967 const char* e1, const char* e2, const char* e3, const char* e4,
1968 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00001969 const int sum = n1 + n2 + n3 + n4 + n5;
1970 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00001971 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00001972 }
1973
shiqian760af5c2008-08-06 21:43:15 +00001974 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00001975 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
1976 << " ("
1977 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
1978 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00001979 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00001980 }
1981};
1982
1983
1984// Tests unary predicate assertions.
1985
1986// Tests unary predicate assertions that don't use a custom formatter.
1987TEST(Pred1Test, WithoutFormat) {
1988 // Success cases.
1989 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
1990 ASSERT_PRED1(IsEven, 4);
1991
1992 // Failure cases.
1993 EXPECT_NONFATAL_FAILURE({ // NOLINT
1994 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
1995 }, "This failure is expected.");
1996 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
1997 "evaluates to false");
1998}
1999
2000// Tests unary predicate assertions that use a custom formatter.
2001TEST(Pred1Test, WithFormat) {
2002 // Success cases.
2003 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2004 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2005 << "This failure is UNEXPECTED!";
2006
2007 // Failure cases.
2008 const int n = 5;
2009 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2010 "n evaluates to 5, which is not even.");
2011 EXPECT_FATAL_FAILURE({ // NOLINT
2012 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2013 }, "This failure is expected.");
2014}
2015
2016// Tests that unary predicate assertions evaluates their arguments
2017// exactly once.
2018TEST(Pred1Test, SingleEvaluationOnFailure) {
2019 // A success case.
2020 static int n = 0;
2021 EXPECT_PRED1(IsEven, n++);
2022 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2023
2024 // A failure case.
2025 EXPECT_FATAL_FAILURE({ // NOLINT
2026 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2027 << "This failure is expected.";
2028 }, "This failure is expected.");
2029 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2030}
2031
2032
2033// Tests predicate assertions whose arity is >= 2.
2034
2035// Tests predicate assertions that don't use a custom formatter.
2036TEST(PredTest, WithoutFormat) {
2037 // Success cases.
2038 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2039 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2040
2041 // Failure cases.
2042 const int n1 = 1;
2043 const int n2 = 2;
2044 EXPECT_NONFATAL_FAILURE({ // NOLINT
2045 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2046 }, "This failure is expected.");
2047 EXPECT_FATAL_FAILURE({ // NOLINT
2048 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2049 }, "evaluates to false");
2050}
2051
2052// Tests predicate assertions that use a custom formatter.
2053TEST(PredTest, WithFormat) {
2054 // Success cases.
2055 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2056 "This failure is UNEXPECTED!";
2057 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2058
2059 // Failure cases.
2060 const int n1 = 1;
2061 const int n2 = 2;
2062 const int n3 = 4;
2063 const int n4 = 6;
2064 EXPECT_NONFATAL_FAILURE({ // NOLINT
2065 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2066 }, "evaluates to 13, which is not even.");
2067 EXPECT_FATAL_FAILURE({ // NOLINT
2068 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2069 << "This failure is expected.";
2070 }, "This failure is expected.");
2071}
2072
2073// Tests that predicate assertions evaluates their arguments
2074// exactly once.
2075TEST(PredTest, SingleEvaluationOnFailure) {
2076 // A success case.
2077 int n1 = 0;
2078 int n2 = 0;
2079 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2080 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2081 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2082
2083 // Another success case.
2084 n1 = n2 = 0;
2085 int n3 = 0;
2086 int n4 = 0;
2087 int n5 = 0;
2088 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2089 n1++, n2++, n3++, n4++, n5++)
2090 << "This failure is UNEXPECTED!";
2091 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2092 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2093 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2094 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2095 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2096
2097 // A failure case.
2098 n1 = n2 = n3 = 0;
2099 EXPECT_NONFATAL_FAILURE({ // NOLINT
2100 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2101 << "This failure is expected.";
2102 }, "This failure is expected.");
2103 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2104 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2105 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2106
2107 // Another failure case.
2108 n1 = n2 = n3 = n4 = 0;
2109 EXPECT_NONFATAL_FAILURE({ // NOLINT
2110 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2111 }, "evaluates to 1, which is not even.");
2112 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2113 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2114 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2115 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2116}
2117
2118
2119// Some helper functions for testing using overloaded/template
2120// functions with ASSERT_PREDn and EXPECT_PREDn.
2121
2122bool IsPositive(int n) {
2123 return n > 0;
2124}
2125
2126bool IsPositive(double x) {
2127 return x > 0;
2128}
2129
2130template <typename T>
2131bool IsNegative(T x) {
2132 return x < 0;
2133}
2134
2135template <typename T1, typename T2>
2136bool GreaterThan(T1 x1, T2 x2) {
2137 return x1 > x2;
2138}
2139
2140// Tests that overloaded functions can be used in *_PRED* as long as
2141// their types are explicitly specified.
2142TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002143 // C++Builder requires C-style casts rather than static_cast.
2144 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2145 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002146}
2147
2148// Tests that template functions can be used in *_PRED* as long as
2149// their types are explicitly specified.
2150TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2151 EXPECT_PRED1(IsNegative<int>, -5);
2152 // Makes sure that we can handle templates with more than one
2153 // parameter.
2154 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2155}
2156
2157
2158// Some helper functions for testing using overloaded/template
2159// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2160
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002161AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002162 return n > 0 ? AssertionSuccess() :
2163 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002164}
2165
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002166AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002167 return x > 0 ? AssertionSuccess() :
2168 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002169}
2170
2171template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002172AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002173 return x < 0 ? AssertionSuccess() :
2174 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002175}
2176
2177template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002178AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002179 const T1& x1, const T2& x2) {
2180 return x1 == x2 ? AssertionSuccess() :
2181 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002182}
2183
2184// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002185// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002186TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2187 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2188 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2189}
2190
2191// Tests that template functions can be used in *_PRED_FORMAT* without
2192// explicitly specifying their types.
2193TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2194 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2195 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2196}
2197
2198
2199// Tests string assertions.
2200
2201// Tests ASSERT_STREQ with non-NULL arguments.
2202TEST(StringAssertionTest, ASSERT_STREQ) {
2203 const char * const p1 = "good";
2204 ASSERT_STREQ(p1, p1);
2205
2206 // Let p2 have the same content as p1, but be at a different address.
2207 const char p2[] = "good";
2208 ASSERT_STREQ(p1, p2);
2209
2210 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2211 "Expected: \"bad\"");
2212}
2213
2214// Tests ASSERT_STREQ with NULL arguments.
2215TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2216 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2217 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2218 "non-null");
2219}
2220
2221// Tests ASSERT_STREQ with NULL arguments.
2222TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2223 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2224 "non-null");
2225}
2226
2227// Tests ASSERT_STRNE.
2228TEST(StringAssertionTest, ASSERT_STRNE) {
2229 ASSERT_STRNE("hi", "Hi");
2230 ASSERT_STRNE("Hi", NULL);
2231 ASSERT_STRNE(NULL, "Hi");
2232 ASSERT_STRNE("", NULL);
2233 ASSERT_STRNE(NULL, "");
2234 ASSERT_STRNE("", "Hi");
2235 ASSERT_STRNE("Hi", "");
2236 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2237 "\"Hi\" vs \"Hi\"");
2238}
2239
2240// Tests ASSERT_STRCASEEQ.
2241TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2242 ASSERT_STRCASEEQ("hi", "Hi");
2243 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2244
2245 ASSERT_STRCASEEQ("", "");
2246 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2247 "(ignoring case)");
2248}
2249
2250// Tests ASSERT_STRCASENE.
2251TEST(StringAssertionTest, ASSERT_STRCASENE) {
2252 ASSERT_STRCASENE("hi1", "Hi2");
2253 ASSERT_STRCASENE("Hi", NULL);
2254 ASSERT_STRCASENE(NULL, "Hi");
2255 ASSERT_STRCASENE("", NULL);
2256 ASSERT_STRCASENE(NULL, "");
2257 ASSERT_STRCASENE("", "Hi");
2258 ASSERT_STRCASENE("Hi", "");
2259 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2260 "(ignoring case)");
2261}
2262
2263// Tests *_STREQ on wide strings.
2264TEST(StringAssertionTest, STREQ_Wide) {
2265 // NULL strings.
2266 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2267
2268 // Empty strings.
2269 ASSERT_STREQ(L"", L"");
2270
2271 // Non-null vs NULL.
2272 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2273 "non-null");
2274
2275 // Equal strings.
2276 EXPECT_STREQ(L"Hi", L"Hi");
2277
2278 // Unequal strings.
2279 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2280 "Abc");
2281
2282 // Strings containing wide characters.
2283 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2284 "abc");
2285}
2286
2287// Tests *_STRNE on wide strings.
2288TEST(StringAssertionTest, STRNE_Wide) {
2289 // NULL strings.
2290 EXPECT_NONFATAL_FAILURE({ // NOLINT
2291 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2292 }, "");
2293
2294 // Empty strings.
2295 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2296 "L\"\"");
2297
2298 // Non-null vs NULL.
2299 ASSERT_STRNE(L"non-null", NULL);
2300
2301 // Equal strings.
2302 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2303 "L\"Hi\"");
2304
2305 // Unequal strings.
2306 EXPECT_STRNE(L"abc", L"Abc");
2307
2308 // Strings containing wide characters.
2309 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2310 "abc");
2311}
2312
2313// Tests for ::testing::IsSubstring().
2314
2315// Tests that IsSubstring() returns the correct result when the input
2316// argument type is const char*.
2317TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002318 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2319 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2320 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2321
2322 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2323 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2324}
2325
2326// Tests that IsSubstring() returns the correct result when the input
2327// argument type is const wchar_t*.
2328TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002329 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2330 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002331 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2332
2333 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2334 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2335}
2336
2337// Tests that IsSubstring() generates the correct message when the input
2338// argument type is const char*.
2339TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2340 EXPECT_STREQ("Value of: needle_expr\n"
2341 " Actual: \"needle\"\n"
2342 "Expected: a substring of haystack_expr\n"
2343 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002344 IsSubstring("needle_expr", "haystack_expr",
2345 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002346}
2347
2348#if GTEST_HAS_STD_STRING
2349
2350// Tests that IsSubstring returns the correct result when the input
2351// argument type is ::std::string.
2352TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002353 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2354 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002355}
2356
2357#endif // GTEST_HAS_STD_STRING
2358
2359#if GTEST_HAS_STD_WSTRING
2360// Tests that IsSubstring returns the correct result when the input
2361// argument type is ::std::wstring.
2362TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002363 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2364 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2365}
2366
2367// Tests that IsSubstring() generates the correct message when the input
2368// argument type is ::std::wstring.
2369TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2370 EXPECT_STREQ("Value of: needle_expr\n"
2371 " Actual: L\"needle\"\n"
2372 "Expected: a substring of haystack_expr\n"
2373 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002374 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002375 "needle_expr", "haystack_expr",
2376 ::std::wstring(L"needle"), L"haystack").failure_message());
2377}
2378
2379#endif // GTEST_HAS_STD_WSTRING
2380
2381// Tests for ::testing::IsNotSubstring().
2382
2383// Tests that IsNotSubstring() returns the correct result when the input
2384// argument type is const char*.
2385TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002386 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2387 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2388}
2389
2390// Tests that IsNotSubstring() returns the correct result when the input
2391// argument type is const wchar_t*.
2392TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002393 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2394 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2395}
2396
2397// Tests that IsNotSubstring() generates the correct message when the input
2398// argument type is const wchar_t*.
2399TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2400 EXPECT_STREQ("Value of: needle_expr\n"
2401 " Actual: L\"needle\"\n"
2402 "Expected: not a substring of haystack_expr\n"
2403 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002404 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002405 "needle_expr", "haystack_expr",
2406 L"needle", L"two needles").failure_message());
2407}
2408
2409#if GTEST_HAS_STD_STRING
2410
2411// Tests that IsNotSubstring returns the correct result when the input
2412// argument type is ::std::string.
2413TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002414 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2415 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2416}
2417
2418// Tests that IsNotSubstring() generates the correct message when the input
2419// argument type is ::std::string.
2420TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2421 EXPECT_STREQ("Value of: needle_expr\n"
2422 " Actual: \"needle\"\n"
2423 "Expected: not a substring of haystack_expr\n"
2424 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002425 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002426 "needle_expr", "haystack_expr",
2427 ::std::string("needle"), "two needles").failure_message());
2428}
2429
2430#endif // GTEST_HAS_STD_STRING
2431
2432#if GTEST_HAS_STD_WSTRING
2433
2434// Tests that IsNotSubstring returns the correct result when the input
2435// argument type is ::std::wstring.
2436TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002437 EXPECT_FALSE(
2438 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2439 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2440}
2441
2442#endif // GTEST_HAS_STD_WSTRING
2443
2444// Tests floating-point assertions.
2445
2446template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002447class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002448 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002449
2450 // Pre-calculated numbers to be used by the tests.
2451 struct TestValues {
2452 RawType close_to_positive_zero;
2453 RawType close_to_negative_zero;
2454 RawType further_from_negative_zero;
2455
2456 RawType close_to_one;
2457 RawType further_from_one;
2458
2459 RawType infinity;
2460 RawType close_to_infinity;
2461 RawType further_from_infinity;
2462
2463 RawType nan1;
2464 RawType nan2;
2465 };
2466
shiqian4b6829f2008-07-03 22:38:12 +00002467 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2468 typedef typename Floating::Bits Bits;
2469
2470 virtual void SetUp() {
2471 const size_t max_ulps = Floating::kMaxUlps;
2472
2473 // The bits that represent 0.0.
2474 const Bits zero_bits = Floating(0).bits();
2475
2476 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002477 values_.close_to_positive_zero = Floating::ReinterpretBits(
2478 zero_bits + max_ulps/2);
2479 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002480 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002481 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002482 zero_bits + max_ulps + 1 - max_ulps/2);
2483
2484 // The bits that represent 1.0.
2485 const Bits one_bits = Floating(1).bits();
2486
2487 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002488 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2489 values_.further_from_one = Floating::ReinterpretBits(
2490 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002491
2492 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002493 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002494
2495 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002496 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002497
2498 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002499 values_.close_to_infinity = Floating::ReinterpretBits(
2500 infinity_bits - max_ulps);
2501 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002502 infinity_bits - max_ulps - 1);
2503
zhanyong.wan98efcc42009-04-28 00:28:09 +00002504 // Makes some NAN's. Sets the most significant bit of the fraction so that
2505 // our NaN's are quiet; trying to process a signaling NaN would raise an
2506 // exception if our environment enables floating point exceptions.
2507 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2508 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2509 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2510 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002511 }
2512
2513 void TestSize() {
2514 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2515 }
2516
zhanyong.wan98efcc42009-04-28 00:28:09 +00002517 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002518};
2519
2520template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002521typename FloatingPointTest<RawType>::TestValues
2522 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002523
2524// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2525typedef FloatingPointTest<float> FloatTest;
2526
2527// Tests that the size of Float::Bits matches the size of float.
2528TEST_F(FloatTest, Size) {
2529 TestSize();
2530}
2531
2532// Tests comparing with +0 and -0.
2533TEST_F(FloatTest, Zeros) {
2534 EXPECT_FLOAT_EQ(0.0, -0.0);
2535 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2536 "1.0");
2537 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2538 "1.5");
2539}
2540
2541// Tests comparing numbers close to 0.
2542//
2543// This ensures that *_FLOAT_EQ handles the sign correctly and no
2544// overflow occurs when comparing numbers whose absolute value is very
2545// small.
2546TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002547 // In C++Builder, names within local classes (such as used by
2548 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2549 // scoping class. Use a static local alias as a workaround.
2550 static const FloatTest::TestValues& v(this->values_);
2551
2552 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2553 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2554 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002555
2556 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002557 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2558 v.further_from_negative_zero);
2559 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002560}
2561
2562// Tests comparing numbers close to each other.
2563TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002564 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2565 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2566 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002567}
2568
2569// Tests comparing numbers far apart.
2570TEST_F(FloatTest, LargeDiff) {
2571 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2572 "3.0");
2573}
2574
2575// Tests comparing with infinity.
2576//
2577// This ensures that no overflow occurs when comparing numbers whose
2578// absolute value is very large.
2579TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002580 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2581 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002582#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002583 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002584 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2585 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002586
zhanyong.wan98efcc42009-04-28 00:28:09 +00002587 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002588 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002589 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2590 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002591#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002592}
2593
2594// Tests that comparing with NAN always returns false.
2595TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002596#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002597// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002598
zhanyong.wan98efcc42009-04-28 00:28:09 +00002599 // In C++Builder, names within local classes (such as used by
2600 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2601 // scoping class. Use a static local alias as a workaround.
2602 static const FloatTest::TestValues& v(this->values_);
2603
2604 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2605 "v.nan1");
2606 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2607 "v.nan2");
2608 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2609 "v.nan1");
2610
2611 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2612 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002613#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002614}
2615
2616// Tests that *_FLOAT_EQ are reflexive.
2617TEST_F(FloatTest, Reflexive) {
2618 EXPECT_FLOAT_EQ(0.0, 0.0);
2619 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002620 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002621}
2622
2623// Tests that *_FLOAT_EQ are commutative.
2624TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002625 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2626 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002627
zhanyong.wan98efcc42009-04-28 00:28:09 +00002628 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2629 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002630 "1.0");
2631}
2632
2633// Tests EXPECT_NEAR.
2634TEST_F(FloatTest, EXPECT_NEAR) {
2635 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2636 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2637 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2638 "The difference between 1.0f and 1.2f is 0.2, "
2639 "which exceeds 0.1f");
2640 // To work around a bug in gcc 2.95.0, there is intentionally no
2641 // space after the first comma in the previous line.
2642}
2643
2644// Tests ASSERT_NEAR.
2645TEST_F(FloatTest, ASSERT_NEAR) {
2646 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2647 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2648 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2649 "The difference between 1.0f and 1.2f is 0.2, "
2650 "which exceeds 0.1f");
2651 // To work around a bug in gcc 2.95.0, there is intentionally no
2652 // space after the first comma in the previous line.
2653}
2654
2655// Tests the cases where FloatLE() should succeed.
2656TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002657 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2658 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002659
2660 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002661 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002662}
2663
2664// Tests the cases where FloatLE() should fail.
2665TEST_F(FloatTest, FloatLEFails) {
2666 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002667 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002668 "(2.0f) <= (1.0f)");
2669
2670 // or by a small yet non-negligible margin,
2671 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002672 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2673 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002674
zhanyong.wan98efcc42009-04-28 00:28:09 +00002675#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002676 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002677 // C++Builder gives bad results for ordered comparisons involving NaNs
2678 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002679 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002680 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2681 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002682 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002683 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2684 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002685 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002686 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2687 }, "(values_.nan1) <= (values_.nan1)");
2688#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002689}
2690
2691// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2692typedef FloatingPointTest<double> DoubleTest;
2693
2694// Tests that the size of Double::Bits matches the size of double.
2695TEST_F(DoubleTest, Size) {
2696 TestSize();
2697}
2698
2699// Tests comparing with +0 and -0.
2700TEST_F(DoubleTest, Zeros) {
2701 EXPECT_DOUBLE_EQ(0.0, -0.0);
2702 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2703 "1.0");
2704 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2705 "1.0");
2706}
2707
2708// Tests comparing numbers close to 0.
2709//
2710// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2711// overflow occurs when comparing numbers whose absolute value is very
2712// small.
2713TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002714 // In C++Builder, names within local classes (such as used by
2715 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2716 // scoping class. Use a static local alias as a workaround.
2717 static const DoubleTest::TestValues& v(this->values_);
2718
2719 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2720 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2721 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002722
2723 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002724 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2725 v.further_from_negative_zero);
2726 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002727}
2728
2729// Tests comparing numbers close to each other.
2730TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002731 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2732 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2733 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002734}
2735
2736// Tests comparing numbers far apart.
2737TEST_F(DoubleTest, LargeDiff) {
2738 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2739 "3.0");
2740}
2741
2742// Tests comparing with infinity.
2743//
2744// This ensures that no overflow occurs when comparing numbers whose
2745// absolute value is very large.
2746TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002747 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2748 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002749#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002750 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002751 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2752 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002753
2754 // This is interesting as the representations of infinity_ and nan1_
2755 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002756 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2757 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002758#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002759}
2760
2761// Tests that comparing with NAN always returns false.
2762TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002763#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00002764 // In C++Builder, names within local classes (such as used by
2765 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2766 // scoping class. Use a static local alias as a workaround.
2767 static const DoubleTest::TestValues& v(this->values_);
2768
shiqiane44602e2008-10-11 07:20:02 +00002769 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002770 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2771 "v.nan1");
2772 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2773 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2774 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2775 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002776#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002777}
2778
2779// Tests that *_DOUBLE_EQ are reflexive.
2780TEST_F(DoubleTest, Reflexive) {
2781 EXPECT_DOUBLE_EQ(0.0, 0.0);
2782 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002783#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002784 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002785 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002786#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002787}
2788
2789// Tests that *_DOUBLE_EQ are commutative.
2790TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002791 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
2792 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002793
zhanyong.wan98efcc42009-04-28 00:28:09 +00002794 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
2795 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
2796 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00002797}
2798
2799// Tests EXPECT_NEAR.
2800TEST_F(DoubleTest, EXPECT_NEAR) {
2801 EXPECT_NEAR(-1.0, -1.1, 0.2);
2802 EXPECT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002803 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
2804 "The difference between 1.0 and 1.2 is 0.2, "
2805 "which exceeds 0.1");
2806 // To work around a bug in gcc 2.95.0, there is intentionally no
2807 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002808}
2809
2810// Tests ASSERT_NEAR.
2811TEST_F(DoubleTest, ASSERT_NEAR) {
2812 ASSERT_NEAR(-1.0, -1.1, 0.2);
2813 ASSERT_NEAR(2.0, 3.0, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002814 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
2815 "The difference between 1.0 and 1.2 is 0.2, "
2816 "which exceeds 0.1");
2817 // To work around a bug in gcc 2.95.0, there is intentionally no
2818 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00002819}
2820
2821// Tests the cases where DoubleLE() should succeed.
2822TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002823 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
2824 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002825
2826 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002827 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00002828}
2829
2830// Tests the cases where DoubleLE() should fail.
2831TEST_F(DoubleTest, DoubleLEFails) {
2832 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002833 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002834 "(2.0) <= (1.0)");
2835
2836 // or by a small yet non-negligible margin,
2837 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002838 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
2839 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00002840
zhanyong.wan98efcc42009-04-28 00:28:09 +00002841#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002842 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002843 // C++Builder gives bad results for ordered comparisons involving NaNs
2844 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002845 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002846 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
2847 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002848 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002849 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
2850 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002851 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002852 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
2853 }, "(values_.nan1) <= (values_.nan1)");
2854#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002855}
2856
2857
2858// Verifies that a test or test case whose name starts with DISABLED_ is
2859// not run.
2860
2861// A test whose name starts with DISABLED_.
2862// Should not run.
2863TEST(DisabledTest, DISABLED_TestShouldNotRun) {
2864 FAIL() << "Unexpected failure: Disabled test should not be run.";
2865}
2866
2867// A test whose name does not start with DISABLED_.
2868// Should run.
2869TEST(DisabledTest, NotDISABLED_TestShouldRun) {
2870 EXPECT_EQ(1, 1);
2871}
2872
2873// A test case whose name starts with DISABLED_.
2874// Should not run.
2875TEST(DISABLED_TestCase, TestShouldNotRun) {
2876 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2877}
2878
2879// A test case and test whose names start with DISABLED_.
2880// Should not run.
2881TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
2882 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2883}
2884
2885// Check that when all tests in a test case are disabled, SetupTestCase() and
2886// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00002887class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002888 protected:
2889 static void SetUpTestCase() {
2890 FAIL() << "Unexpected failure: All tests disabled in test case. "
2891 "SetupTestCase() should not be called.";
2892 }
2893
2894 static void TearDownTestCase() {
2895 FAIL() << "Unexpected failure: All tests disabled in test case. "
2896 "TearDownTestCase() should not be called.";
2897 }
2898};
2899
2900TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
2901 FAIL() << "Unexpected failure: Disabled test should not be run.";
2902}
2903
2904TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
2905 FAIL() << "Unexpected failure: Disabled test should not be run.";
2906}
2907
shiqiane8ff1482008-09-08 17:55:52 +00002908// Tests that disabled typed tests aren't run.
2909
zhanyong.wan4cd62602009-02-23 23:21:55 +00002910#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00002911
2912template <typename T>
2913class TypedTest : public Test {
2914};
2915
2916typedef testing::Types<int, double> NumericTypes;
2917TYPED_TEST_CASE(TypedTest, NumericTypes);
2918
2919TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
2920 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2921}
2922
2923template <typename T>
2924class DISABLED_TypedTest : public Test {
2925};
2926
2927TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
2928
2929TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
2930 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2931}
2932
2933#endif // GTEST_HAS_TYPED_TEST
2934
2935// Tests that disabled type-parameterized tests aren't run.
2936
zhanyong.wan4cd62602009-02-23 23:21:55 +00002937#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00002938
2939template <typename T>
2940class TypedTestP : public Test {
2941};
2942
2943TYPED_TEST_CASE_P(TypedTestP);
2944
2945TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
2946 FAIL() << "Unexpected failure: "
2947 << "Disabled type-parameterized test should not run.";
2948}
2949
2950REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
2951
2952INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
2953
2954template <typename T>
2955class DISABLED_TypedTestP : public Test {
2956};
2957
2958TYPED_TEST_CASE_P(DISABLED_TypedTestP);
2959
2960TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
2961 FAIL() << "Unexpected failure: "
2962 << "Disabled type-parameterized test should not run.";
2963}
2964
2965REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
2966
2967INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
2968
2969#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00002970
2971// Tests that assertion macros evaluate their arguments exactly once.
2972
shiqian760af5c2008-08-06 21:43:15 +00002973class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00002974 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002975 // This helper function is needed by the FailedASSERT_STREQ test
2976 // below. It's public to work around C++Builder's bug with scoping local
2977 // classes.
2978 static void CompareAndIncrementCharPtrs() {
2979 ASSERT_STREQ(p1_++, p2_++);
2980 }
2981
2982 // This helper function is needed by the FailedASSERT_NE test below. It's
2983 // public to work around C++Builder's bug with scoping local classes.
2984 static void CompareAndIncrementInts() {
2985 ASSERT_NE(a_++, b_++);
2986 }
2987
shiqian4b6829f2008-07-03 22:38:12 +00002988 protected:
2989 SingleEvaluationTest() {
2990 p1_ = s1_;
2991 p2_ = s2_;
2992 a_ = 0;
2993 b_ = 0;
2994 }
2995
shiqian4b6829f2008-07-03 22:38:12 +00002996 static const char* const s1_;
2997 static const char* const s2_;
2998 static const char* p1_;
2999 static const char* p2_;
3000
3001 static int a_;
3002 static int b_;
3003};
3004
3005const char* const SingleEvaluationTest::s1_ = "01234";
3006const char* const SingleEvaluationTest::s2_ = "abcde";
3007const char* SingleEvaluationTest::p1_;
3008const char* SingleEvaluationTest::p2_;
3009int SingleEvaluationTest::a_;
3010int SingleEvaluationTest::b_;
3011
3012// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3013// exactly once.
3014TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003015 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003016 "p2_++");
3017 EXPECT_EQ(s1_ + 1, p1_);
3018 EXPECT_EQ(s2_ + 1, p2_);
3019}
3020
3021// Tests that string assertion arguments are evaluated exactly once.
3022TEST_F(SingleEvaluationTest, ASSERT_STR) {
3023 // successful EXPECT_STRNE
3024 EXPECT_STRNE(p1_++, p2_++);
3025 EXPECT_EQ(s1_ + 1, p1_);
3026 EXPECT_EQ(s2_ + 1, p2_);
3027
3028 // failed EXPECT_STRCASEEQ
3029 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3030 "ignoring case");
3031 EXPECT_EQ(s1_ + 2, p1_);
3032 EXPECT_EQ(s2_ + 2, p2_);
3033}
3034
3035// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3036// once.
3037TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003038 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3039 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003040 EXPECT_EQ(1, a_);
3041 EXPECT_EQ(1, b_);
3042}
3043
3044// Tests that assertion arguments are evaluated exactly once.
3045TEST_F(SingleEvaluationTest, OtherCases) {
3046 // successful EXPECT_TRUE
3047 EXPECT_TRUE(0 == a_++); // NOLINT
3048 EXPECT_EQ(1, a_);
3049
3050 // failed EXPECT_TRUE
3051 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3052 EXPECT_EQ(2, a_);
3053
3054 // successful EXPECT_GT
3055 EXPECT_GT(a_++, b_++);
3056 EXPECT_EQ(3, a_);
3057 EXPECT_EQ(1, b_);
3058
3059 // failed EXPECT_LT
3060 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3061 EXPECT_EQ(4, a_);
3062 EXPECT_EQ(2, b_);
3063
3064 // successful ASSERT_TRUE
3065 ASSERT_TRUE(0 < a_++); // NOLINT
3066 EXPECT_EQ(5, a_);
3067
3068 // successful ASSERT_GT
3069 ASSERT_GT(a_++, b_++);
3070 EXPECT_EQ(6, a_);
3071 EXPECT_EQ(3, b_);
3072}
3073
shiqian9204c8e2008-09-12 20:57:22 +00003074#if GTEST_HAS_EXCEPTIONS
3075
3076void ThrowAnInteger() {
3077 throw 1;
3078}
3079
3080// Tests that assertion arguments are evaluated exactly once.
3081TEST_F(SingleEvaluationTest, ExceptionTests) {
3082 // successful EXPECT_THROW
3083 EXPECT_THROW({ // NOLINT
3084 a_++;
3085 ThrowAnInteger();
3086 }, int);
3087 EXPECT_EQ(1, a_);
3088
3089 // failed EXPECT_THROW, throws different
3090 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3091 a_++;
3092 ThrowAnInteger();
3093 }, bool), "throws a different type");
3094 EXPECT_EQ(2, a_);
3095
3096 // failed EXPECT_THROW, throws nothing
3097 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3098 EXPECT_EQ(3, a_);
3099
3100 // successful EXPECT_NO_THROW
3101 EXPECT_NO_THROW(a_++);
3102 EXPECT_EQ(4, a_);
3103
3104 // failed EXPECT_NO_THROW
3105 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3106 a_++;
3107 ThrowAnInteger();
3108 }), "it throws");
3109 EXPECT_EQ(5, a_);
3110
3111 // successful EXPECT_ANY_THROW
3112 EXPECT_ANY_THROW({ // NOLINT
3113 a_++;
3114 ThrowAnInteger();
3115 });
3116 EXPECT_EQ(6, a_);
3117
3118 // failed EXPECT_ANY_THROW
3119 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3120 EXPECT_EQ(7, a_);
3121}
3122
3123#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003124
shiqiane44602e2008-10-11 07:20:02 +00003125// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3126class NoFatalFailureTest : public Test {
3127 protected:
3128 void Succeeds() {}
3129 void FailsNonFatal() {
3130 ADD_FAILURE() << "some non-fatal failure";
3131 }
3132 void Fails() {
3133 FAIL() << "some fatal failure";
3134 }
3135
3136 void DoAssertNoFatalFailureOnFails() {
3137 ASSERT_NO_FATAL_FAILURE(Fails());
3138 ADD_FAILURE() << "shold not reach here.";
3139 }
3140
3141 void DoExpectNoFatalFailureOnFails() {
3142 EXPECT_NO_FATAL_FAILURE(Fails());
3143 ADD_FAILURE() << "other failure";
3144 }
3145};
3146
3147TEST_F(NoFatalFailureTest, NoFailure) {
3148 EXPECT_NO_FATAL_FAILURE(Succeeds());
3149 ASSERT_NO_FATAL_FAILURE(Succeeds());
3150}
3151
3152TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3153 EXPECT_NONFATAL_FAILURE(
3154 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3155 "some non-fatal failure");
3156 EXPECT_NONFATAL_FAILURE(
3157 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3158 "some non-fatal failure");
3159}
3160
3161TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3162 TestPartResultArray gtest_failures;
3163 {
3164 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3165 DoAssertNoFatalFailureOnFails();
3166 }
3167 ASSERT_EQ(2, gtest_failures.size());
3168 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3169 gtest_failures.GetTestPartResult(0).type());
3170 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3171 gtest_failures.GetTestPartResult(1).type());
3172 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3173 gtest_failures.GetTestPartResult(0).message());
3174 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3175 gtest_failures.GetTestPartResult(1).message());
3176}
3177
3178TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3179 TestPartResultArray gtest_failures;
3180 {
3181 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3182 DoExpectNoFatalFailureOnFails();
3183 }
3184 ASSERT_EQ(3, gtest_failures.size());
3185 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
3186 gtest_failures.GetTestPartResult(0).type());
3187 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3188 gtest_failures.GetTestPartResult(1).type());
3189 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3190 gtest_failures.GetTestPartResult(2).type());
3191 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3192 gtest_failures.GetTestPartResult(0).message());
3193 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3194 gtest_failures.GetTestPartResult(1).message());
3195 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3196 gtest_failures.GetTestPartResult(2).message());
3197}
3198
3199TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3200 TestPartResultArray gtest_failures;
3201 {
3202 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3203 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3204 }
3205 ASSERT_EQ(2, gtest_failures.size());
3206 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3207 gtest_failures.GetTestPartResult(0).type());
3208 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
3209 gtest_failures.GetTestPartResult(1).type());
3210 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3211 gtest_failures.GetTestPartResult(0).message());
3212 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3213 gtest_failures.GetTestPartResult(1).message());
3214}
3215
shiqian4b6829f2008-07-03 22:38:12 +00003216// Tests non-string assertions.
3217
3218// Tests EqFailure(), used for implementing *EQ* assertions.
3219TEST(AssertionTest, EqFailure) {
3220 const String foo_val("5"), bar_val("6");
3221 const String msg1(
3222 EqFailure("foo", "bar", foo_val, bar_val, false)
3223 .failure_message());
3224 EXPECT_STREQ(
3225 "Value of: bar\n"
3226 " Actual: 6\n"
3227 "Expected: foo\n"
3228 "Which is: 5",
3229 msg1.c_str());
3230
3231 const String msg2(
3232 EqFailure("foo", "6", foo_val, bar_val, false)
3233 .failure_message());
3234 EXPECT_STREQ(
3235 "Value of: 6\n"
3236 "Expected: foo\n"
3237 "Which is: 5",
3238 msg2.c_str());
3239
3240 const String msg3(
3241 EqFailure("5", "bar", foo_val, bar_val, false)
3242 .failure_message());
3243 EXPECT_STREQ(
3244 "Value of: bar\n"
3245 " Actual: 6\n"
3246 "Expected: 5",
3247 msg3.c_str());
3248
3249 const String msg4(
3250 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3251 EXPECT_STREQ(
3252 "Value of: 6\n"
3253 "Expected: 5",
3254 msg4.c_str());
3255
3256 const String msg5(
3257 EqFailure("foo", "bar",
3258 String("\"x\""), String("\"y\""),
3259 true).failure_message());
3260 EXPECT_STREQ(
3261 "Value of: bar\n"
3262 " Actual: \"y\"\n"
3263 "Expected: foo (ignoring case)\n"
3264 "Which is: \"x\"",
3265 msg5.c_str());
3266}
3267
3268// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3269TEST(AssertionTest, AppendUserMessage) {
3270 const String foo("foo");
3271
shiqian760af5c2008-08-06 21:43:15 +00003272 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003273 EXPECT_STREQ("foo",
3274 AppendUserMessage(foo, msg).c_str());
3275
3276 msg << "bar";
3277 EXPECT_STREQ("foo\nbar",
3278 AppendUserMessage(foo, msg).c_str());
3279}
3280
zhanyong.wan98efcc42009-04-28 00:28:09 +00003281#ifdef __BORLANDC__
3282// Silences warnings: "Condition is always true", "Unreachable code"
3283#pragma option push -w-ccc -w-rch
3284#endif
3285
shiqian4b6829f2008-07-03 22:38:12 +00003286// Tests ASSERT_TRUE.
3287TEST(AssertionTest, ASSERT_TRUE) {
3288 ASSERT_TRUE(2 > 1); // NOLINT
3289 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3290 "2 < 1");
3291}
3292
3293// Tests ASSERT_FALSE.
3294TEST(AssertionTest, ASSERT_FALSE) {
3295 ASSERT_FALSE(2 < 1); // NOLINT
3296 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3297 "Value of: 2 > 1\n"
3298 " Actual: true\n"
3299 "Expected: false");
3300}
3301
zhanyong.wan98efcc42009-04-28 00:28:09 +00003302#ifdef __BORLANDC__
3303// Restores warnings after previous "#pragma option push" supressed them
3304#pragma option pop
3305#endif
3306
shiqian4b6829f2008-07-03 22:38:12 +00003307// Tests using ASSERT_EQ on double values. The purpose is to make
3308// sure that the specialization we did for integer and anonymous enums
3309// isn't used for double arguments.
3310TEST(ExpectTest, ASSERT_EQ_Double) {
3311 // A success.
3312 ASSERT_EQ(5.6, 5.6);
3313
3314 // A failure.
3315 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3316 "5.1");
3317}
3318
3319// Tests ASSERT_EQ.
3320TEST(AssertionTest, ASSERT_EQ) {
3321 ASSERT_EQ(5, 2 + 3);
3322 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3323 "Value of: 2*3\n"
3324 " Actual: 6\n"
3325 "Expected: 5");
3326}
3327
3328// Tests ASSERT_EQ(NULL, pointer).
zhanyong.wan4cd62602009-02-23 23:21:55 +00003329#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003330// The NULL-detection template magic fails to compile with
3331// the Nokia compiler and crashes the ARM compiler, hence
3332// not testing on Symbian.
3333TEST(AssertionTest, ASSERT_EQ_NULL) {
3334 // A success.
3335 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003336 // Some older GCC versions may issue a spurious waring in this or the next
3337 // assertion statement. This warning should not be suppressed with
3338 // static_cast since the test verifies the ability to use bare NULL as the
3339 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003340 ASSERT_EQ(NULL, p);
3341
3342 // A failure.
3343 static int n = 0;
3344 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3345 "Value of: &n\n");
3346}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003347#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003348
3349// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3350// treated as a null pointer by the compiler, we need to make sure
3351// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3352// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3353TEST(ExpectTest, ASSERT_EQ_0) {
3354 int n = 0;
3355
3356 // A success.
3357 ASSERT_EQ(0, n);
3358
3359 // A failure.
3360 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3361 "Expected: 0");
3362}
3363
3364// Tests ASSERT_NE.
3365TEST(AssertionTest, ASSERT_NE) {
3366 ASSERT_NE(6, 7);
3367 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3368 "Expected: ('a') != ('a'), "
3369 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3370}
3371
3372// Tests ASSERT_LE.
3373TEST(AssertionTest, ASSERT_LE) {
3374 ASSERT_LE(2, 3);
3375 ASSERT_LE(2, 2);
3376 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3377 "Expected: (2) <= (0), actual: 2 vs 0");
3378}
3379
3380// Tests ASSERT_LT.
3381TEST(AssertionTest, ASSERT_LT) {
3382 ASSERT_LT(2, 3);
3383 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3384 "Expected: (2) < (2), actual: 2 vs 2");
3385}
3386
3387// Tests ASSERT_GE.
3388TEST(AssertionTest, ASSERT_GE) {
3389 ASSERT_GE(2, 1);
3390 ASSERT_GE(2, 2);
3391 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3392 "Expected: (2) >= (3), actual: 2 vs 3");
3393}
3394
3395// Tests ASSERT_GT.
3396TEST(AssertionTest, ASSERT_GT) {
3397 ASSERT_GT(2, 1);
3398 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3399 "Expected: (2) > (2), actual: 2 vs 2");
3400}
3401
shiqian9204c8e2008-09-12 20:57:22 +00003402#if GTEST_HAS_EXCEPTIONS
3403
zhanyong.wanac60cef2009-02-08 04:53:35 +00003404void ThrowNothing() {}
3405
shiqian9204c8e2008-09-12 20:57:22 +00003406// Tests ASSERT_THROW.
3407TEST(AssertionTest, ASSERT_THROW) {
3408 ASSERT_THROW(ThrowAnInteger(), int);
zhanyong.wan98efcc42009-04-28 00:28:09 +00003409#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 || defined(_DEBUG)
3410 // ICE's in C++Builder 2007 (Release build).
zhanyong.wanac60cef2009-02-08 04:53:35 +00003411 EXPECT_FATAL_FAILURE(
3412 ASSERT_THROW(ThrowAnInteger(), bool),
3413 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3414 " Actual: it throws a different type.");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003415#endif
zhanyong.wanac60cef2009-02-08 04:53:35 +00003416 EXPECT_FATAL_FAILURE(
3417 ASSERT_THROW(ThrowNothing(), bool),
3418 "Expected: ThrowNothing() throws an exception of type bool.\n"
3419 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003420}
3421
3422// Tests ASSERT_NO_THROW.
3423TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003424 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003425 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003426 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003427 "\n Actual: it throws.");
3428}
3429
3430// Tests ASSERT_ANY_THROW.
3431TEST(AssertionTest, ASSERT_ANY_THROW) {
3432 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003433 EXPECT_FATAL_FAILURE(
3434 ASSERT_ANY_THROW(ThrowNothing()),
3435 "Expected: ThrowNothing() throws an exception.\n"
3436 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003437}
3438
3439#endif // GTEST_HAS_EXCEPTIONS
3440
shiqian4b6829f2008-07-03 22:38:12 +00003441// Makes sure we deal with the precedence of <<. This test should
3442// compile.
3443TEST(AssertionTest, AssertPrecedence) {
3444 ASSERT_EQ(1 < 2, true);
3445 ASSERT_EQ(true && false, false);
3446}
3447
3448// A subroutine used by the following test.
3449void TestEq1(int x) {
3450 ASSERT_EQ(1, x);
3451}
3452
3453// Tests calling a test subroutine that's not part of a fixture.
3454TEST(AssertionTest, NonFixtureSubroutine) {
3455 EXPECT_FATAL_FAILURE(TestEq1(2),
3456 "Value of: x");
3457}
3458
3459// An uncopyable class.
3460class Uncopyable {
3461 public:
3462 explicit Uncopyable(int value) : value_(value) {}
3463
3464 int value() const { return value_; }
3465 bool operator==(const Uncopyable& rhs) const {
3466 return value() == rhs.value();
3467 }
3468 private:
3469 // This constructor deliberately has no implementation, as we don't
3470 // want this class to be copyable.
3471 Uncopyable(const Uncopyable&); // NOLINT
3472
3473 int value_;
3474};
3475
3476::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3477 return os << value.value();
3478}
3479
3480
3481bool IsPositiveUncopyable(const Uncopyable& x) {
3482 return x.value() > 0;
3483}
3484
3485// A subroutine used by the following test.
3486void TestAssertNonPositive() {
3487 Uncopyable y(-1);
3488 ASSERT_PRED1(IsPositiveUncopyable, y);
3489}
3490// A subroutine used by the following test.
3491void TestAssertEqualsUncopyable() {
3492 Uncopyable x(5);
3493 Uncopyable y(-1);
3494 ASSERT_EQ(x, y);
3495}
3496
3497// Tests that uncopyable objects can be used in assertions.
3498TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3499 Uncopyable x(5);
3500 ASSERT_PRED1(IsPositiveUncopyable, x);
3501 ASSERT_EQ(x, x);
3502 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3503 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3504 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3505 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3506}
3507
3508// Tests that uncopyable objects can be used in expects.
3509TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3510 Uncopyable x(5);
3511 EXPECT_PRED1(IsPositiveUncopyable, x);
3512 Uncopyable y(-1);
3513 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3514 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3515 EXPECT_EQ(x, x);
3516 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3517 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3518}
3519
3520
3521// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003522// anonymous enums in assertions. Therefore the following test is not
3523// done on Mac.
3524#if !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003525
3526// Tests using assertions with anonymous enums.
3527enum {
3528 CASE_A = -1,
zhanyong.wan4cd62602009-02-23 23:21:55 +00003529#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003530 // We want to test the case where the size of the anonymous enum is
3531 // larger than sizeof(int), to make sure our implementation of the
3532 // assertions doesn't truncate the enums. However, MSVC
3533 // (incorrectly) doesn't allow an enum value to exceed the range of
3534 // an int, so this has to be conditionally compiled.
3535 //
3536 // On Linux, CASE_B and CASE_A have the same value when truncated to
3537 // int size. We want to test whether this will confuse the
3538 // assertions.
shiqian760af5c2008-08-06 21:43:15 +00003539 CASE_B = testing::internal::kMaxBiggestInt,
shiqian4b6829f2008-07-03 22:38:12 +00003540#else
3541 CASE_B = INT_MAX,
3542#endif // GTEST_OS_LINUX
3543};
3544
3545TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00003546#if GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003547 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
3548#endif // GTEST_OS_LINUX
3549
3550 EXPECT_EQ(CASE_A, CASE_A);
3551 EXPECT_NE(CASE_A, CASE_B);
3552 EXPECT_LT(CASE_A, CASE_B);
3553 EXPECT_LE(CASE_A, CASE_B);
3554 EXPECT_GT(CASE_B, CASE_A);
3555 EXPECT_GE(CASE_A, CASE_A);
3556 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
3557 "(CASE_A) >= (CASE_B)");
3558
3559 ASSERT_EQ(CASE_A, CASE_A);
3560 ASSERT_NE(CASE_A, CASE_B);
3561 ASSERT_LT(CASE_A, CASE_B);
3562 ASSERT_LE(CASE_A, CASE_B);
3563 ASSERT_GT(CASE_B, CASE_A);
3564 ASSERT_GE(CASE_A, CASE_A);
3565 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
3566 "Value of: CASE_B");
3567}
3568
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003569#endif // !GTEST_OS_MAC
shiqian4b6829f2008-07-03 22:38:12 +00003570
zhanyong.wan4cd62602009-02-23 23:21:55 +00003571#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003572
3573static HRESULT UnexpectedHRESULTFailure() {
3574 return E_UNEXPECTED;
3575}
3576
3577static HRESULT OkHRESULTSuccess() {
3578 return S_OK;
3579}
3580
3581static HRESULT FalseHRESULTSuccess() {
3582 return S_FALSE;
3583}
3584
3585// HRESULT assertion tests test both zero and non-zero
3586// success codes as well as failure message for each.
3587//
3588// Windows CE doesn't support message texts.
3589TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3590 EXPECT_HRESULT_SUCCEEDED(S_OK);
3591 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3592
shiqian4b6829f2008-07-03 22:38:12 +00003593 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003594 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3595 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003596}
3597
3598TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3599 ASSERT_HRESULT_SUCCEEDED(S_OK);
3600 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3601
shiqian4b6829f2008-07-03 22:38:12 +00003602 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003603 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3604 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003605}
3606
3607TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3608 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3609
shiqian4b6829f2008-07-03 22:38:12 +00003610 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003611 "Expected: (OkHRESULTSuccess()) fails.\n"
3612 " Actual: 0x00000000");
shiqian4b6829f2008-07-03 22:38:12 +00003613 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003614 "Expected: (FalseHRESULTSuccess()) fails.\n"
3615 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003616}
3617
3618TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3619 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3620
zhanyong.wan98efcc42009-04-28 00:28:09 +00003621#ifndef __BORLANDC__
3622 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003623 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003624 "Expected: (OkHRESULTSuccess()) fails.\n"
3625 " Actual: 0x00000000");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003626#endif
shiqian4b6829f2008-07-03 22:38:12 +00003627 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003628 "Expected: (FalseHRESULTSuccess()) fails.\n"
3629 " Actual: 0x00000001");
shiqian4b6829f2008-07-03 22:38:12 +00003630}
3631
3632// Tests that streaming to the HRESULT macros works.
3633TEST(HRESULTAssertionTest, Streaming) {
3634 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3635 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3636 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3637 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3638
3639 EXPECT_NONFATAL_FAILURE(
3640 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3641 "expected failure");
3642
zhanyong.wan98efcc42009-04-28 00:28:09 +00003643#ifndef __BORLANDC__
3644 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003645 EXPECT_FATAL_FAILURE(
3646 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3647 "expected failure");
zhanyong.wan98efcc42009-04-28 00:28:09 +00003648#endif
shiqian4b6829f2008-07-03 22:38:12 +00003649
3650 EXPECT_NONFATAL_FAILURE(
3651 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3652 "expected failure");
3653
3654 EXPECT_FATAL_FAILURE(
3655 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3656 "expected failure");
3657}
3658
zhanyong.wan4cd62602009-02-23 23:21:55 +00003659#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003660
zhanyong.wan98efcc42009-04-28 00:28:09 +00003661#ifdef __BORLANDC__
3662// Silences warnings: "Condition is always true", "Unreachable code"
3663#pragma option push -w-ccc -w-rch
3664#endif
3665
shiqian4b6829f2008-07-03 22:38:12 +00003666// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003667TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
shiqian4b6829f2008-07-03 22:38:12 +00003668 if (false)
3669 ASSERT_TRUE(false) << "This should never be executed; "
3670 "It's a compilation test only.";
3671
3672 if (true)
3673 EXPECT_FALSE(false);
3674 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003675 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003676
3677 if (false)
3678 ASSERT_LT(1, 3);
3679
3680 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003681 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003682 else
3683 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00003684}
shiqian9204c8e2008-09-12 20:57:22 +00003685
3686#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00003687// Tests that the compiler will not complain about unreachable code in the
3688// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3689TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3690 int n = 0;
3691
3692 EXPECT_THROW(throw 1, int);
3693 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3694 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3695 EXPECT_NO_THROW(n++);
3696 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3697 EXPECT_ANY_THROW(throw 1);
3698 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3699}
3700
shiqiane44602e2008-10-11 07:20:02 +00003701TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
shiqian9204c8e2008-09-12 20:57:22 +00003702 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003703 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00003704
3705 if (true)
3706 EXPECT_THROW(ThrowAnInteger(), int);
3707 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003708 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003709
3710 if (false)
3711 EXPECT_NO_THROW(ThrowAnInteger());
3712
3713 if (true)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003714 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003715 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003716 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00003717
3718 if (false)
zhanyong.wanac60cef2009-02-08 04:53:35 +00003719 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003720
3721 if (true)
3722 EXPECT_ANY_THROW(ThrowAnInteger());
3723 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003724 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003725}
shiqian9204c8e2008-09-12 20:57:22 +00003726#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00003727
3728TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
3729 if (false)
3730 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
3731 << "It's a compilation test only.";
3732 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003733 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003734
3735 if (false)
3736 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
3737 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003738 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003739
3740 if (true)
3741 EXPECT_NO_FATAL_FAILURE(SUCCEED());
3742 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003743 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003744
3745 if (false)
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003746 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00003747 else
3748 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00003749}
3750
3751// Tests that the assertion macros work well with switch statements.
3752TEST(AssertionSyntaxTest, WorksWithSwitch) {
3753 switch (0) {
3754 case 1:
3755 break;
3756 default:
3757 ASSERT_TRUE(true);
3758 }
3759
3760 switch (0)
3761 case 0:
3762 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
3763
3764 // Binary assertions are implemented using a different code path
3765 // than the Boolean assertions. Hence we test them separately.
3766 switch (0) {
3767 case 1:
3768 default:
3769 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
3770 }
3771
3772 switch (0)
3773 case 0:
3774 EXPECT_NE(1, 2);
3775}
3776
shiqian9204c8e2008-09-12 20:57:22 +00003777#if GTEST_HAS_EXCEPTIONS
3778
3779void ThrowAString() {
3780 throw "String";
3781}
3782
3783// Test that the exception assertion macros compile and work with const
3784// type qualifier.
3785TEST(AssertionSyntaxTest, WorksWithConst) {
3786 ASSERT_THROW(ThrowAString(), const char*);
3787
3788 EXPECT_THROW(ThrowAString(), const char*);
3789}
3790
3791#endif // GTEST_HAS_EXCEPTIONS
3792
shiqian4b6829f2008-07-03 22:38:12 +00003793} // namespace
3794
shiqian4b6829f2008-07-03 22:38:12 +00003795namespace testing {
3796
3797// Tests that Google Test tracks SUCCEED*.
3798TEST(SuccessfulAssertionTest, SUCCEED) {
3799 SUCCEED();
3800 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003801 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003802}
3803
3804// Tests that Google Test doesn't track successful EXPECT_*.
3805TEST(SuccessfulAssertionTest, EXPECT) {
3806 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003807 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003808}
3809
3810// Tests that Google Test doesn't track successful EXPECT_STR*.
3811TEST(SuccessfulAssertionTest, EXPECT_STR) {
3812 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003813 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003814}
3815
3816// Tests that Google Test doesn't track successful ASSERT_*.
3817TEST(SuccessfulAssertionTest, ASSERT) {
3818 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003819 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003820}
3821
3822// Tests that Google Test doesn't track successful ASSERT_STR*.
3823TEST(SuccessfulAssertionTest, ASSERT_STR) {
3824 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00003825 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00003826}
3827
3828} // namespace testing
3829
3830namespace {
3831
3832// Tests EXPECT_TRUE.
3833TEST(ExpectTest, EXPECT_TRUE) {
3834 EXPECT_TRUE(2 > 1); // NOLINT
3835 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
3836 "Value of: 2 < 1\n"
3837 " Actual: false\n"
3838 "Expected: true");
3839 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
3840 "2 > 3");
3841}
3842
3843// Tests EXPECT_FALSE.
3844TEST(ExpectTest, EXPECT_FALSE) {
3845 EXPECT_FALSE(2 < 1); // NOLINT
3846 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
3847 "Value of: 2 > 1\n"
3848 " Actual: true\n"
3849 "Expected: false");
3850 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
3851 "2 < 3");
3852}
3853
zhanyong.wan98efcc42009-04-28 00:28:09 +00003854#ifdef __BORLANDC__
3855// Restores warnings after previous "#pragma option push" supressed them
3856#pragma option pop
3857#endif
3858
shiqian4b6829f2008-07-03 22:38:12 +00003859// Tests EXPECT_EQ.
3860TEST(ExpectTest, EXPECT_EQ) {
3861 EXPECT_EQ(5, 2 + 3);
3862 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
3863 "Value of: 2*3\n"
3864 " Actual: 6\n"
3865 "Expected: 5");
3866 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
3867 "2 - 3");
3868}
3869
3870// Tests using EXPECT_EQ on double values. The purpose is to make
3871// sure that the specialization we did for integer and anonymous enums
3872// isn't used for double arguments.
3873TEST(ExpectTest, EXPECT_EQ_Double) {
3874 // A success.
3875 EXPECT_EQ(5.6, 5.6);
3876
3877 // A failure.
3878 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
3879 "5.1");
3880}
3881
zhanyong.wan4cd62602009-02-23 23:21:55 +00003882#if !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003883// Tests EXPECT_EQ(NULL, pointer).
3884TEST(ExpectTest, EXPECT_EQ_NULL) {
3885 // A success.
3886 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003887 // Some older GCC versions may issue a spurious waring in this or the next
3888 // assertion statement. This warning should not be suppressed with
3889 // static_cast since the test verifies the ability to use bare NULL as the
3890 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003891 EXPECT_EQ(NULL, p);
3892
3893 // A failure.
3894 int n = 0;
3895 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
3896 "Value of: &n\n");
3897}
zhanyong.wan4cd62602009-02-23 23:21:55 +00003898#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003899
3900// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
3901// treated as a null pointer by the compiler, we need to make sure
3902// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
3903// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
3904TEST(ExpectTest, EXPECT_EQ_0) {
3905 int n = 0;
3906
3907 // A success.
3908 EXPECT_EQ(0, n);
3909
3910 // A failure.
3911 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
3912 "Expected: 0");
3913}
3914
3915// Tests EXPECT_NE.
3916TEST(ExpectTest, EXPECT_NE) {
3917 EXPECT_NE(6, 7);
3918
3919 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
3920 "Expected: ('a') != ('a'), "
3921 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3922 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
3923 "2");
3924 char* const p0 = NULL;
3925 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
3926 "p0");
3927 // Only way to get the Nokia compiler to compile the cast
3928 // is to have a separate void* variable first. Putting
3929 // the two casts on the same line doesn't work, neither does
3930 // a direct C-style to char*.
3931 void* pv1 = (void*)0x1234; // NOLINT
3932 char* const p1 = reinterpret_cast<char*>(pv1);
3933 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
3934 "p1");
3935}
3936
3937// Tests EXPECT_LE.
3938TEST(ExpectTest, EXPECT_LE) {
3939 EXPECT_LE(2, 3);
3940 EXPECT_LE(2, 2);
3941 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
3942 "Expected: (2) <= (0), actual: 2 vs 0");
3943 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
3944 "(1.1) <= (0.9)");
3945}
3946
3947// Tests EXPECT_LT.
3948TEST(ExpectTest, EXPECT_LT) {
3949 EXPECT_LT(2, 3);
3950 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
3951 "Expected: (2) < (2), actual: 2 vs 2");
3952 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
3953 "(2) < (1)");
3954}
3955
3956// Tests EXPECT_GE.
3957TEST(ExpectTest, EXPECT_GE) {
3958 EXPECT_GE(2, 1);
3959 EXPECT_GE(2, 2);
3960 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
3961 "Expected: (2) >= (3), actual: 2 vs 3");
3962 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
3963 "(0.9) >= (1.1)");
3964}
3965
3966// Tests EXPECT_GT.
3967TEST(ExpectTest, EXPECT_GT) {
3968 EXPECT_GT(2, 1);
3969 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
3970 "Expected: (2) > (2), actual: 2 vs 2");
3971 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
3972 "(2) > (3)");
3973}
3974
shiqian9204c8e2008-09-12 20:57:22 +00003975#if GTEST_HAS_EXCEPTIONS
3976
3977// Tests EXPECT_THROW.
3978TEST(ExpectTest, EXPECT_THROW) {
3979 EXPECT_THROW(ThrowAnInteger(), int);
3980 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003981 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00003982 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00003983 EXPECT_NONFATAL_FAILURE(
3984 EXPECT_THROW(ThrowNothing(), bool),
3985 "Expected: ThrowNothing() throws an exception of type bool.\n"
3986 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003987}
3988
3989// Tests EXPECT_NO_THROW.
3990TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003991 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003992 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003993 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00003994 "exception.\n Actual: it throws.");
3995}
3996
3997// Tests EXPECT_ANY_THROW.
3998TEST(ExpectTest, EXPECT_ANY_THROW) {
3999 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004000 EXPECT_NONFATAL_FAILURE(
4001 EXPECT_ANY_THROW(ThrowNothing()),
4002 "Expected: ThrowNothing() throws an exception.\n"
4003 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004004}
4005
4006#endif // GTEST_HAS_EXCEPTIONS
4007
shiqian4b6829f2008-07-03 22:38:12 +00004008// Make sure we deal with the precedence of <<.
4009TEST(ExpectTest, ExpectPrecedence) {
4010 EXPECT_EQ(1 < 2, true);
4011 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4012 "Value of: true && false");
4013}
4014
4015
4016// Tests the StreamableToString() function.
4017
4018// Tests using StreamableToString() on a scalar.
4019TEST(StreamableToStringTest, Scalar) {
4020 EXPECT_STREQ("5", StreamableToString(5).c_str());
4021}
4022
4023// Tests using StreamableToString() on a non-char pointer.
4024TEST(StreamableToStringTest, Pointer) {
4025 int n = 0;
4026 int* p = &n;
4027 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4028}
4029
4030// Tests using StreamableToString() on a NULL non-char pointer.
4031TEST(StreamableToStringTest, NullPointer) {
4032 int* p = NULL;
4033 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4034}
4035
4036// Tests using StreamableToString() on a C string.
4037TEST(StreamableToStringTest, CString) {
4038 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4039}
4040
4041// Tests using StreamableToString() on a NULL C string.
4042TEST(StreamableToStringTest, NullCString) {
4043 char* p = NULL;
4044 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4045}
4046
4047// Tests using streamable values as assertion messages.
4048
4049#if GTEST_HAS_STD_STRING
4050// Tests using std::string as an assertion message.
4051TEST(StreamableTest, string) {
4052 static const std::string str(
4053 "This failure message is a std::string, and is expected.");
4054 EXPECT_FATAL_FAILURE(FAIL() << str,
4055 str.c_str());
4056}
4057
4058// Tests that we can output strings containing embedded NULs.
4059// Limited to Linux because we can only do this with std::string's.
4060TEST(StreamableTest, stringWithEmbeddedNUL) {
4061 static const char char_array_with_nul[] =
4062 "Here's a NUL\0 and some more string";
4063 static const std::string string_with_nul(char_array_with_nul,
4064 sizeof(char_array_with_nul)
4065 - 1); // drops the trailing NUL
4066 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4067 "Here's a NUL\\0 and some more string");
4068}
4069
4070#endif // GTEST_HAS_STD_STRING
4071
4072// Tests that we can output a NUL char.
4073TEST(StreamableTest, NULChar) {
4074 EXPECT_FATAL_FAILURE({ // NOLINT
4075 FAIL() << "A NUL" << '\0' << " and some more string";
4076 }, "A NUL\\0 and some more string");
4077}
4078
4079// Tests using int as an assertion message.
4080TEST(StreamableTest, int) {
4081 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4082 "900913");
4083}
4084
4085// Tests using NULL char pointer as an assertion message.
4086//
4087// In MSVC, streaming a NULL char * causes access violation. Google Test
4088// implemented a workaround (substituting "(null)" for NULL). This
4089// tests whether the workaround works.
4090TEST(StreamableTest, NullCharPtr) {
4091 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4092 "(null)");
4093}
4094
4095// Tests that basic IO manipulators (endl, ends, and flush) can be
4096// streamed to testing::Message.
4097TEST(StreamableTest, BasicIoManip) {
4098 EXPECT_FATAL_FAILURE({ // NOLINT
4099 FAIL() << "Line 1." << std::endl
4100 << "A NUL char " << std::ends << std::flush << " in line 2.";
4101 }, "Line 1.\nA NUL char \\0 in line 2.");
4102}
4103
shiqian4b6829f2008-07-03 22:38:12 +00004104// Tests the macros that haven't been covered so far.
4105
4106void AddFailureHelper(bool* aborted) {
4107 *aborted = true;
4108 ADD_FAILURE() << "Failure";
4109 *aborted = false;
4110}
4111
4112// Tests ADD_FAILURE.
4113TEST(MacroTest, ADD_FAILURE) {
4114 bool aborted = true;
4115 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4116 "Failure");
4117 EXPECT_FALSE(aborted);
4118}
4119
4120// Tests FAIL.
4121TEST(MacroTest, FAIL) {
4122 EXPECT_FATAL_FAILURE(FAIL(),
4123 "Failed");
4124 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4125 "Intentional failure.");
4126}
4127
4128// Tests SUCCEED
4129TEST(MacroTest, SUCCEED) {
4130 SUCCEED();
4131 SUCCEED() << "Explicit success.";
4132}
4133
4134
4135// Tests for EXPECT_EQ() and ASSERT_EQ().
4136//
4137// These tests fail *intentionally*, s.t. the failure messages can be
4138// generated and tested.
4139//
4140// We have different tests for different argument types.
4141
4142// Tests using bool values in {EXPECT|ASSERT}_EQ.
4143TEST(EqAssertionTest, Bool) {
4144 EXPECT_EQ(true, true);
4145 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4146 "Value of: true");
4147}
4148
4149// Tests using int values in {EXPECT|ASSERT}_EQ.
4150TEST(EqAssertionTest, Int) {
4151 ASSERT_EQ(32, 32);
4152 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4153 "33");
4154}
4155
4156// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4157TEST(EqAssertionTest, Time_T) {
4158 EXPECT_EQ(static_cast<time_t>(0),
4159 static_cast<time_t>(0));
4160 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4161 static_cast<time_t>(1234)),
4162 "1234");
4163}
4164
4165// Tests using char values in {EXPECT|ASSERT}_EQ.
4166TEST(EqAssertionTest, Char) {
4167 ASSERT_EQ('z', 'z');
4168 const char ch = 'b';
4169 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4170 "ch");
4171 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4172 "ch");
4173}
4174
4175// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4176TEST(EqAssertionTest, WideChar) {
4177 EXPECT_EQ(L'b', L'b');
4178
4179 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4180 "Value of: L'x'\n"
4181 " Actual: L'x' (120, 0x78)\n"
4182 "Expected: L'\0'\n"
4183 "Which is: L'\0' (0, 0x0)");
4184
4185 static wchar_t wchar;
4186 wchar = L'b';
4187 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4188 "wchar");
4189 wchar = L'\x8119';
4190 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4191 "Value of: wchar");
4192}
4193
4194#if GTEST_HAS_STD_STRING
4195// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4196TEST(EqAssertionTest, StdString) {
4197 // Compares a const char* to an std::string that has identical
4198 // content.
4199 ASSERT_EQ("Test", ::std::string("Test"));
4200
4201 // Compares two identical std::strings.
4202 static const ::std::string str1("A * in the middle");
4203 static const ::std::string str2(str1);
4204 EXPECT_EQ(str1, str2);
4205
4206 // Compares a const char* to an std::string that has different
4207 // content
4208 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4209 "::std::string(\"test\")");
4210
4211 // Compares an std::string to a char* that has different content.
4212 char* const p1 = const_cast<char*>("foo");
4213 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4214 "p1");
4215
4216 // Compares two std::strings that have different contents, one of
4217 // which having a NUL character in the middle. This should fail.
4218 static ::std::string str3(str1);
4219 str3.at(2) = '\0';
4220 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4221 "Value of: str3\n"
4222 " Actual: \"A \\0 in the middle\"");
4223}
4224
4225#endif // GTEST_HAS_STD_STRING
4226
4227#if GTEST_HAS_STD_WSTRING
4228
4229// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4230TEST(EqAssertionTest, StdWideString) {
4231 // Compares an std::wstring to a const wchar_t* that has identical
4232 // content.
4233 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4234
4235 // Compares two identical std::wstrings.
4236 const ::std::wstring wstr1(L"A * in the middle");
4237 const ::std::wstring wstr2(wstr1);
4238 ASSERT_EQ(wstr1, wstr2);
4239
4240 // Compares an std::wstring to a const wchar_t* that has different
4241 // content.
4242 EXPECT_NONFATAL_FAILURE({ // NOLINT
4243 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4244 }, "L\"Test\\x8120\"");
4245
4246 // Compares two std::wstrings that have different contents, one of
4247 // which having a NUL character in the middle.
4248 ::std::wstring wstr3(wstr1);
4249 wstr3.at(2) = L'\0';
4250 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4251 "wstr3");
4252
4253 // Compares a wchar_t* to an std::wstring that has different
4254 // content.
4255 EXPECT_FATAL_FAILURE({ // NOLINT
4256 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4257 }, "");
4258}
4259
4260#endif // GTEST_HAS_STD_WSTRING
4261
4262#if GTEST_HAS_GLOBAL_STRING
4263// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4264TEST(EqAssertionTest, GlobalString) {
4265 // Compares a const char* to a ::string that has identical content.
4266 EXPECT_EQ("Test", ::string("Test"));
4267
4268 // Compares two identical ::strings.
4269 const ::string str1("A * in the middle");
4270 const ::string str2(str1);
4271 ASSERT_EQ(str1, str2);
4272
4273 // Compares a ::string to a const char* that has different content.
4274 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4275 "test");
4276
4277 // Compares two ::strings that have different contents, one of which
4278 // having a NUL character in the middle.
4279 ::string str3(str1);
4280 str3.at(2) = '\0';
4281 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4282 "str3");
4283
4284 // Compares a ::string to a char* that has different content.
4285 EXPECT_FATAL_FAILURE({ // NOLINT
4286 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4287 }, "");
4288}
4289
4290#endif // GTEST_HAS_GLOBAL_STRING
4291
4292#if GTEST_HAS_GLOBAL_WSTRING
4293
4294// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4295TEST(EqAssertionTest, GlobalWideString) {
4296 // Compares a const wchar_t* to a ::wstring that has identical content.
4297 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4298
4299 // Compares two identical ::wstrings.
4300 static const ::wstring wstr1(L"A * in the middle");
4301 static const ::wstring wstr2(wstr1);
4302 EXPECT_EQ(wstr1, wstr2);
4303
4304 // Compares a const wchar_t* to a ::wstring that has different
4305 // content.
4306 EXPECT_NONFATAL_FAILURE({ // NOLINT
4307 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4308 }, "Test\\x8119");
4309
4310 // Compares a wchar_t* to a ::wstring that has different content.
4311 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4312 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4313 "bar");
4314
4315 // Compares two ::wstrings that have different contents, one of which
4316 // having a NUL character in the middle.
4317 static ::wstring wstr3;
4318 wstr3 = wstr1;
4319 wstr3.at(2) = L'\0';
4320 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4321 "wstr3");
4322}
4323
4324#endif // GTEST_HAS_GLOBAL_WSTRING
4325
4326// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4327TEST(EqAssertionTest, CharPointer) {
4328 char* const p0 = NULL;
4329 // Only way to get the Nokia compiler to compile the cast
4330 // is to have a separate void* variable first. Putting
4331 // the two casts on the same line doesn't work, neither does
4332 // a direct C-style to char*.
4333 void* pv1 = (void*)0x1234; // NOLINT
4334 void* pv2 = (void*)0xABC0; // NOLINT
4335 char* const p1 = reinterpret_cast<char*>(pv1);
4336 char* const p2 = reinterpret_cast<char*>(pv2);
4337 ASSERT_EQ(p1, p1);
4338
4339 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4340 "Value of: p2");
4341 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4342 "p2");
4343 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4344 reinterpret_cast<char*>(0xABC0)),
4345 "ABC0");
4346}
4347
4348// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4349TEST(EqAssertionTest, WideCharPointer) {
4350 wchar_t* const p0 = NULL;
4351 // Only way to get the Nokia compiler to compile the cast
4352 // is to have a separate void* variable first. Putting
4353 // the two casts on the same line doesn't work, neither does
4354 // a direct C-style to char*.
4355 void* pv1 = (void*)0x1234; // NOLINT
4356 void* pv2 = (void*)0xABC0; // NOLINT
4357 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4358 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4359 EXPECT_EQ(p0, p0);
4360
4361 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4362 "Value of: p2");
4363 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4364 "p2");
4365 void* pv3 = (void*)0x1234; // NOLINT
4366 void* pv4 = (void*)0xABC0; // NOLINT
4367 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4368 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4369 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4370 "p4");
4371}
4372
4373// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4374TEST(EqAssertionTest, OtherPointer) {
4375 ASSERT_EQ(static_cast<const int*>(NULL),
4376 static_cast<const int*>(NULL));
4377 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4378 reinterpret_cast<const int*>(0x1234)),
4379 "0x1234");
4380}
4381
4382// Tests the FRIEND_TEST macro.
4383
4384// This class has a private member we want to test. We will test it
4385// both in a TEST and in a TEST_F.
4386class Foo {
4387 public:
4388 Foo() {}
4389
4390 private:
4391 int Bar() const { return 1; }
4392
4393 // Declares the friend tests that can access the private member
4394 // Bar().
4395 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4396 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4397};
4398
4399// Tests that the FRIEND_TEST declaration allows a TEST to access a
4400// class's private members. This should compile.
4401TEST(FRIEND_TEST_Test, TEST) {
4402 ASSERT_EQ(1, Foo().Bar());
4403}
4404
4405// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004406class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004407 protected:
4408 Foo foo;
4409};
4410
4411// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4412// class's private members. This should compile.
4413TEST_F(FRIEND_TEST_Test2, TEST_F) {
4414 ASSERT_EQ(1, foo.Bar());
4415}
4416
4417// Tests the life cycle of Test objects.
4418
4419// The test fixture for testing the life cycle of Test objects.
4420//
4421// This class counts the number of live test objects that uses this
4422// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004423class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004424 protected:
4425 // Constructor. Increments the number of test objects that uses
4426 // this fixture.
4427 TestLifeCycleTest() { count_++; }
4428
4429 // Destructor. Decrements the number of test objects that uses this
4430 // fixture.
4431 ~TestLifeCycleTest() { count_--; }
4432
4433 // Returns the number of live test objects that uses this fixture.
4434 int count() const { return count_; }
4435
4436 private:
4437 static int count_;
4438};
4439
4440int TestLifeCycleTest::count_ = 0;
4441
4442// Tests the life cycle of test objects.
4443TEST_F(TestLifeCycleTest, Test1) {
4444 // There should be only one test object in this test case that's
4445 // currently alive.
4446 ASSERT_EQ(1, count());
4447}
4448
4449// Tests the life cycle of test objects.
4450TEST_F(TestLifeCycleTest, Test2) {
4451 // After Test1 is done and Test2 is started, there should still be
4452 // only one live test object, as the object for Test1 should've been
4453 // deleted.
4454 ASSERT_EQ(1, count());
4455}
4456
4457} // namespace
4458
4459// Tests streaming a user type whose definition and operator << are
4460// both in the global namespace.
4461class Base {
4462 public:
4463 explicit Base(int x) : x_(x) {}
4464 int x() const { return x_; }
4465 private:
4466 int x_;
4467};
4468std::ostream& operator<<(std::ostream& os,
4469 const Base& val) {
4470 return os << val.x();
4471}
4472std::ostream& operator<<(std::ostream& os,
4473 const Base* pointer) {
4474 return os << "(" << pointer->x() << ")";
4475}
4476
4477TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004478 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004479 Base a(1);
4480
4481 msg << a << &a; // Uses ::operator<<.
4482 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4483}
4484
4485// Tests streaming a user type whose definition and operator<< are
4486// both in an unnamed namespace.
4487namespace {
4488class MyTypeInUnnamedNameSpace : public Base {
4489 public:
4490 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {}
4491};
4492std::ostream& operator<<(std::ostream& os,
4493 const MyTypeInUnnamedNameSpace& val) {
4494 return os << val.x();
4495}
4496std::ostream& operator<<(std::ostream& os,
4497 const MyTypeInUnnamedNameSpace* pointer) {
4498 return os << "(" << pointer->x() << ")";
4499}
4500} // namespace
4501
4502TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004503 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004504 MyTypeInUnnamedNameSpace a(1);
4505
4506 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4507 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4508}
4509
4510// Tests streaming a user type whose definition and operator<< are
4511// both in a user namespace.
4512namespace namespace1 {
4513class MyTypeInNameSpace1 : public Base {
4514 public:
4515 explicit MyTypeInNameSpace1(int x): Base(x) {}
4516};
4517std::ostream& operator<<(std::ostream& os,
4518 const MyTypeInNameSpace1& val) {
4519 return os << val.x();
4520}
4521std::ostream& operator<<(std::ostream& os,
4522 const MyTypeInNameSpace1* pointer) {
4523 return os << "(" << pointer->x() << ")";
4524}
4525} // namespace namespace1
4526
4527TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00004528 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004529 namespace1::MyTypeInNameSpace1 a(1);
4530
4531 msg << a << &a; // Uses namespace1::operator<<.
4532 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4533}
4534
4535// Tests streaming a user type whose definition is in a user namespace
4536// but whose operator<< is in the global namespace.
4537namespace namespace2 {
4538class MyTypeInNameSpace2 : public ::Base {
4539 public:
4540 explicit MyTypeInNameSpace2(int x): Base(x) {}
4541};
4542} // namespace namespace2
4543std::ostream& operator<<(std::ostream& os,
4544 const namespace2::MyTypeInNameSpace2& val) {
4545 return os << val.x();
4546}
4547std::ostream& operator<<(std::ostream& os,
4548 const namespace2::MyTypeInNameSpace2* pointer) {
4549 return os << "(" << pointer->x() << ")";
4550}
4551
4552TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00004553 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004554 namespace2::MyTypeInNameSpace2 a(1);
4555
4556 msg << a << &a; // Uses ::operator<<.
4557 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4558}
4559
4560// Tests streaming NULL pointers to testing::Message.
4561TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00004562 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00004563 char* const p1 = NULL;
4564 unsigned char* const p2 = NULL;
4565 int* p3 = NULL;
4566 double* p4 = NULL;
4567 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00004568 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004569
4570 msg << p1 << p2 << p3 << p4 << p5 << p6;
4571 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4572 msg.GetString().c_str());
4573}
4574
4575// Tests streaming wide strings to testing::Message.
4576TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00004577 // Streams a NULL of type const wchar_t*.
4578 const wchar_t* const_wstr = NULL;
4579 EXPECT_STREQ("(null)",
4580 (Message() << const_wstr).GetString().c_str());
4581
4582 // Streams a NULL of type wchar_t*.
4583 wchar_t* wstr = NULL;
4584 EXPECT_STREQ("(null)",
4585 (Message() << wstr).GetString().c_str());
4586
4587 // Streams a non-NULL of type const wchar_t*.
4588 const_wstr = L"abc\x8119";
4589 EXPECT_STREQ("abc\xe8\x84\x99",
4590 (Message() << const_wstr).GetString().c_str());
4591
4592 // Streams a non-NULL of type wchar_t*.
4593 wstr = const_cast<wchar_t*>(const_wstr);
4594 EXPECT_STREQ("abc\xe8\x84\x99",
4595 (Message() << wstr).GetString().c_str());
4596}
4597
4598
4599// This line tests that we can define tests in the testing namespace.
4600namespace testing {
4601
4602// Tests the TestInfo class.
4603
shiqian760af5c2008-08-06 21:43:15 +00004604class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004605 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004606 static const TestInfo* GetTestInfo(const char* test_name) {
4607 const TestCase* const test_case = GetUnitTestImpl()->
4608 GetTestCase("TestInfoTest", "", NULL, NULL);
4609
4610 for (int i = 0; i < test_case->total_test_count(); ++i) {
4611 const TestInfo* const test_info = test_case->GetTestInfo(i);
4612 if (strcmp(test_name, test_info->name()) == 0)
4613 return test_info;
4614 }
4615 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00004616 }
4617
4618 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00004619 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00004620 return test_info->result();
4621 }
4622};
4623
4624// Tests TestInfo::test_case_name() and TestInfo::name().
4625TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004626 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00004627
4628 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
4629 ASSERT_STREQ("Names", test_info->name());
4630}
4631
4632// Tests TestInfo::result().
4633TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004634 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00004635
4636 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004637 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004638
4639 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00004640 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004641}
4642
4643// Tests setting up and tearing down a test case.
4644
shiqian760af5c2008-08-06 21:43:15 +00004645class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004646 protected:
4647 // This will be called once before the first test in this test case
4648 // is run.
4649 static void SetUpTestCase() {
4650 printf("Setting up the test case . . .\n");
4651
4652 // Initializes some shared resource. In this simple example, we
4653 // just create a C string. More complex stuff can be done if
4654 // desired.
4655 shared_resource_ = "123";
4656
4657 // Increments the number of test cases that have been set up.
4658 counter_++;
4659
4660 // SetUpTestCase() should be called only once.
4661 EXPECT_EQ(1, counter_);
4662 }
4663
4664 // This will be called once after the last test in this test case is
4665 // run.
4666 static void TearDownTestCase() {
4667 printf("Tearing down the test case . . .\n");
4668
4669 // Decrements the number of test cases that have been set up.
4670 counter_--;
4671
4672 // TearDownTestCase() should be called only once.
4673 EXPECT_EQ(0, counter_);
4674
4675 // Cleans up the shared resource.
4676 shared_resource_ = NULL;
4677 }
4678
4679 // This will be called before each test in this test case.
4680 virtual void SetUp() {
4681 // SetUpTestCase() should be called only once, so counter_ should
4682 // always be 1.
4683 EXPECT_EQ(1, counter_);
4684 }
4685
4686 // Number of test cases that have been set up.
4687 static int counter_;
4688
4689 // Some resource to be shared by all tests in this test case.
4690 static const char* shared_resource_;
4691};
4692
4693int SetUpTestCaseTest::counter_ = 0;
4694const char* SetUpTestCaseTest::shared_resource_ = NULL;
4695
4696// A test that uses the shared resource.
4697TEST_F(SetUpTestCaseTest, Test1) {
4698 EXPECT_STRNE(NULL, shared_resource_);
4699}
4700
4701// Another test that uses the shared resource.
4702TEST_F(SetUpTestCaseTest, Test2) {
4703 EXPECT_STREQ("123", shared_resource_);
4704}
4705
4706// The InitGoogleTestTest test case tests testing::InitGoogleTest().
4707
4708// The Flags struct stores a copy of all Google Test flags.
4709struct Flags {
4710 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00004711 Flags() : also_run_disabled_tests(false),
4712 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00004713 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00004714 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00004715 filter(""),
4716 list_tests(false),
4717 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00004718 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004719 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004720 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004721 shuffle(false),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004722 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00004723
4724 // Factory methods.
4725
shiqianca6949f2009-01-10 01:16:33 +00004726 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
4727 // the given value.
4728 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
4729 Flags flags;
4730 flags.also_run_disabled_tests = also_run_disabled_tests;
4731 return flags;
4732 }
4733
shiqian4b6829f2008-07-03 22:38:12 +00004734 // Creates a Flags struct where the gtest_break_on_failure flag has
4735 // the given value.
4736 static Flags BreakOnFailure(bool break_on_failure) {
4737 Flags flags;
4738 flags.break_on_failure = break_on_failure;
4739 return flags;
4740 }
4741
4742 // Creates a Flags struct where the gtest_catch_exceptions flag has
4743 // the given value.
4744 static Flags CatchExceptions(bool catch_exceptions) {
4745 Flags flags;
4746 flags.catch_exceptions = catch_exceptions;
4747 return flags;
4748 }
4749
shiqian21d43d12009-01-08 01:10:31 +00004750 // Creates a Flags struct where the gtest_death_test_use_fork flag has
4751 // the given value.
4752 static Flags DeathTestUseFork(bool death_test_use_fork) {
4753 Flags flags;
4754 flags.death_test_use_fork = death_test_use_fork;
4755 return flags;
4756 }
4757
shiqian4b6829f2008-07-03 22:38:12 +00004758 // Creates a Flags struct where the gtest_filter flag has the given
4759 // value.
4760 static Flags Filter(const char* filter) {
4761 Flags flags;
4762 flags.filter = filter;
4763 return flags;
4764 }
4765
4766 // Creates a Flags struct where the gtest_list_tests flag has the
4767 // given value.
4768 static Flags ListTests(bool list_tests) {
4769 Flags flags;
4770 flags.list_tests = list_tests;
4771 return flags;
4772 }
4773
4774 // Creates a Flags struct where the gtest_output flag has the given
4775 // value.
4776 static Flags Output(const char* output) {
4777 Flags flags;
4778 flags.output = output;
4779 return flags;
4780 }
4781
shiqiand981cee2008-07-25 04:06:16 +00004782 // Creates a Flags struct where the gtest_print_time flag has the given
4783 // value.
4784 static Flags PrintTime(bool print_time) {
4785 Flags flags;
4786 flags.print_time = print_time;
4787 return flags;
4788 }
4789
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004790 // Creates a Flags struct where the gtest_random_seed flag has
4791 // the given value.
4792 static Flags RandomSeed(Int32 random_seed) {
4793 Flags flags;
4794 flags.random_seed = random_seed;
4795 return flags;
4796 }
4797
shiqian4b6829f2008-07-03 22:38:12 +00004798 // Creates a Flags struct where the gtest_repeat flag has the given
4799 // value.
4800 static Flags Repeat(Int32 repeat) {
4801 Flags flags;
4802 flags.repeat = repeat;
4803 return flags;
4804 }
4805
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004806 // Creates a Flags struct where the gtest_shuffle flag has
4807 // the given value.
4808 static Flags Shuffle(bool shuffle) {
4809 Flags flags;
4810 flags.shuffle = shuffle;
4811 return flags;
4812 }
4813
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004814 // Creates a Flags struct where the gtest_throw_on_failure flag has
4815 // the given value.
4816 static Flags ThrowOnFailure(bool throw_on_failure) {
4817 Flags flags;
4818 flags.throw_on_failure = throw_on_failure;
4819 return flags;
4820 }
4821
shiqian4b6829f2008-07-03 22:38:12 +00004822 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00004823 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00004824 bool break_on_failure;
4825 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00004826 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00004827 const char* filter;
4828 bool list_tests;
4829 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00004830 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004831 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00004832 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004833 bool shuffle;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004834 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00004835};
4836
4837// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00004838class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004839 protected:
4840 // Clears the flags before each test.
4841 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00004842 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004843 GTEST_FLAG(break_on_failure) = false;
4844 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00004845 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004846 GTEST_FLAG(filter) = "";
4847 GTEST_FLAG(list_tests) = false;
4848 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00004849 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004850 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00004851 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004852 GTEST_FLAG(shuffle) = false;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004853 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00004854 }
4855
4856 // Asserts that two narrow or wide string arrays are equal.
4857 template <typename CharType>
4858 static void AssertStringArrayEq(size_t size1, CharType** array1,
4859 size_t size2, CharType** array2) {
4860 ASSERT_EQ(size1, size2) << " Array sizes different.";
4861
4862 for (size_t i = 0; i != size1; i++) {
4863 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
4864 }
4865 }
4866
4867 // Verifies that the flag values match the expected values.
4868 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00004869 EXPECT_EQ(expected.also_run_disabled_tests,
4870 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00004871 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
4872 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00004873 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00004874 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
4875 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
4876 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00004877 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004878 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00004879 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004880 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00004881 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00004882 }
4883
4884 // Parses a command line (specified by argc1 and argv1), then
4885 // verifies that the flag values are expected and that the
4886 // recognized flags are removed from the command line.
4887 template <typename CharType>
4888 static void TestParsingFlags(int argc1, const CharType** argv1,
4889 int argc2, const CharType** argv2,
4890 const Flags& expected) {
4891 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00004892 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00004893
4894 // Verifies the flag values.
4895 CheckFlags(expected);
4896
4897 // Verifies that the recognized flags are removed from the command
4898 // line.
4899 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
4900 }
4901
4902 // This macro wraps TestParsingFlags s.t. the user doesn't need
4903 // to specify the array sizes.
zhanyong.wan4cd62602009-02-23 23:21:55 +00004904#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected) \
shiqian4b6829f2008-07-03 22:38:12 +00004905 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
4906 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected)
4907};
4908
4909// Tests parsing an empty command line.
4910TEST_F(InitGoogleTestTest, Empty) {
4911 const char* argv[] = {
4912 NULL
4913 };
4914
4915 const char* argv2[] = {
4916 NULL
4917 };
4918
zhanyong.wan4cd62602009-02-23 23:21:55 +00004919 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00004920}
4921
4922// Tests parsing a command line that has no flag.
4923TEST_F(InitGoogleTestTest, NoFlag) {
4924 const char* argv[] = {
4925 "foo.exe",
4926 NULL
4927 };
4928
4929 const char* argv2[] = {
4930 "foo.exe",
4931 NULL
4932 };
4933
zhanyong.wan4cd62602009-02-23 23:21:55 +00004934 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00004935}
4936
4937// Tests parsing a bad --gtest_filter flag.
4938TEST_F(InitGoogleTestTest, FilterBad) {
4939 const char* argv[] = {
4940 "foo.exe",
4941 "--gtest_filter",
4942 NULL
4943 };
4944
4945 const char* argv2[] = {
4946 "foo.exe",
4947 "--gtest_filter",
4948 NULL
4949 };
4950
zhanyong.wan4cd62602009-02-23 23:21:55 +00004951 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00004952}
4953
4954// Tests parsing an empty --gtest_filter flag.
4955TEST_F(InitGoogleTestTest, FilterEmpty) {
4956 const char* argv[] = {
4957 "foo.exe",
4958 "--gtest_filter=",
4959 NULL
4960 };
4961
4962 const char* argv2[] = {
4963 "foo.exe",
4964 NULL
4965 };
4966
zhanyong.wan4cd62602009-02-23 23:21:55 +00004967 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
shiqian4b6829f2008-07-03 22:38:12 +00004968}
4969
4970// Tests parsing a non-empty --gtest_filter flag.
4971TEST_F(InitGoogleTestTest, FilterNonEmpty) {
4972 const char* argv[] = {
4973 "foo.exe",
4974 "--gtest_filter=abc",
4975 NULL
4976 };
4977
4978 const char* argv2[] = {
4979 "foo.exe",
4980 NULL
4981 };
4982
zhanyong.wan4cd62602009-02-23 23:21:55 +00004983 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"));
shiqian4b6829f2008-07-03 22:38:12 +00004984}
4985
4986// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00004987TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00004988 const char* argv[] = {
4989 "foo.exe",
4990 "--gtest_break_on_failure",
4991 NULL
4992};
4993
4994 const char* argv2[] = {
4995 "foo.exe",
4996 NULL
4997 };
4998
zhanyong.wan4cd62602009-02-23 23:21:55 +00004999 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00005000}
5001
5002// Tests parsing --gtest_break_on_failure=0.
5003TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5004 const char* argv[] = {
5005 "foo.exe",
5006 "--gtest_break_on_failure=0",
5007 NULL
5008 };
5009
5010 const char* argv2[] = {
5011 "foo.exe",
5012 NULL
5013 };
5014
zhanyong.wan4cd62602009-02-23 23:21:55 +00005015 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005016}
5017
5018// Tests parsing --gtest_break_on_failure=f.
5019TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5020 const char* argv[] = {
5021 "foo.exe",
5022 "--gtest_break_on_failure=f",
5023 NULL
5024 };
5025
5026 const char* argv2[] = {
5027 "foo.exe",
5028 NULL
5029 };
5030
zhanyong.wan4cd62602009-02-23 23:21:55 +00005031 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005032}
5033
5034// Tests parsing --gtest_break_on_failure=F.
5035TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5036 const char* argv[] = {
5037 "foo.exe",
5038 "--gtest_break_on_failure=F",
5039 NULL
5040 };
5041
5042 const char* argv2[] = {
5043 "foo.exe",
5044 NULL
5045 };
5046
zhanyong.wan4cd62602009-02-23 23:21:55 +00005047 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
shiqian4b6829f2008-07-03 22:38:12 +00005048}
5049
5050// Tests parsing a --gtest_break_on_failure flag that has a "true"
5051// definition.
5052TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5053 const char* argv[] = {
5054 "foo.exe",
5055 "--gtest_break_on_failure=1",
5056 NULL
5057 };
5058
5059 const char* argv2[] = {
5060 "foo.exe",
5061 NULL
5062 };
5063
zhanyong.wan4cd62602009-02-23 23:21:55 +00005064 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
shiqian4b6829f2008-07-03 22:38:12 +00005065}
5066
5067// Tests parsing --gtest_catch_exceptions.
5068TEST_F(InitGoogleTestTest, CatchExceptions) {
5069 const char* argv[] = {
5070 "foo.exe",
5071 "--gtest_catch_exceptions",
5072 NULL
5073 };
5074
5075 const char* argv2[] = {
5076 "foo.exe",
5077 NULL
5078 };
5079
zhanyong.wan4cd62602009-02-23 23:21:55 +00005080 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true));
shiqian4b6829f2008-07-03 22:38:12 +00005081}
5082
shiqian21d43d12009-01-08 01:10:31 +00005083// Tests parsing --gtest_death_test_use_fork.
5084TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5085 const char* argv[] = {
5086 "foo.exe",
5087 "--gtest_death_test_use_fork",
5088 NULL
5089 };
5090
5091 const char* argv2[] = {
5092 "foo.exe",
5093 NULL
5094 };
5095
zhanyong.wan4cd62602009-02-23 23:21:55 +00005096 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true));
shiqian21d43d12009-01-08 01:10:31 +00005097}
5098
shiqian4b6829f2008-07-03 22:38:12 +00005099// Tests having the same flag twice with different values. The
5100// expected behavior is that the one coming last takes precedence.
5101TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5102 const char* argv[] = {
5103 "foo.exe",
5104 "--gtest_filter=a",
5105 "--gtest_filter=b",
5106 NULL
5107 };
5108
5109 const char* argv2[] = {
5110 "foo.exe",
5111 NULL
5112 };
5113
zhanyong.wan4cd62602009-02-23 23:21:55 +00005114 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"));
shiqian4b6829f2008-07-03 22:38:12 +00005115}
5116
5117// Tests having an unrecognized flag on the command line.
5118TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5119 const char* argv[] = {
5120 "foo.exe",
5121 "--gtest_break_on_failure",
5122 "bar", // Unrecognized by Google Test.
5123 "--gtest_filter=b",
5124 NULL
5125 };
5126
5127 const char* argv2[] = {
5128 "foo.exe",
5129 "bar",
5130 NULL
5131 };
5132
5133 Flags flags;
5134 flags.break_on_failure = true;
5135 flags.filter = "b";
zhanyong.wan4cd62602009-02-23 23:21:55 +00005136 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags);
shiqian4b6829f2008-07-03 22:38:12 +00005137}
5138
5139// Tests having a --gtest_list_tests flag
5140TEST_F(InitGoogleTestTest, ListTestsFlag) {
5141 const char* argv[] = {
5142 "foo.exe",
5143 "--gtest_list_tests",
5144 NULL
5145 };
5146
5147 const char* argv2[] = {
5148 "foo.exe",
5149 NULL
5150 };
5151
zhanyong.wan4cd62602009-02-23 23:21:55 +00005152 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005153}
5154
5155// Tests having a --gtest_list_tests flag with a "true" value
5156TEST_F(InitGoogleTestTest, ListTestsTrue) {
5157 const char* argv[] = {
5158 "foo.exe",
5159 "--gtest_list_tests=1",
5160 NULL
5161 };
5162
5163 const char* argv2[] = {
5164 "foo.exe",
5165 NULL
5166 };
5167
zhanyong.wan4cd62602009-02-23 23:21:55 +00005168 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
shiqian4b6829f2008-07-03 22:38:12 +00005169}
5170
5171// Tests having a --gtest_list_tests flag with a "false" value
5172TEST_F(InitGoogleTestTest, ListTestsFalse) {
5173 const char* argv[] = {
5174 "foo.exe",
5175 "--gtest_list_tests=0",
5176 NULL
5177 };
5178
5179 const char* argv2[] = {
5180 "foo.exe",
5181 NULL
5182 };
5183
zhanyong.wan4cd62602009-02-23 23:21:55 +00005184 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005185}
5186
5187// Tests parsing --gtest_list_tests=f.
5188TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5189 const char* argv[] = {
5190 "foo.exe",
5191 "--gtest_list_tests=f",
5192 NULL
5193 };
5194
5195 const char* argv2[] = {
5196 "foo.exe",
5197 NULL
5198 };
5199
zhanyong.wan4cd62602009-02-23 23:21:55 +00005200 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005201}
5202
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005203// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005204TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5205 const char* argv[] = {
5206 "foo.exe",
5207 "--gtest_list_tests=F",
5208 NULL
5209 };
5210
5211 const char* argv2[] = {
5212 "foo.exe",
5213 NULL
5214 };
5215
zhanyong.wan4cd62602009-02-23 23:21:55 +00005216 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
shiqian4b6829f2008-07-03 22:38:12 +00005217}
5218
5219// Tests parsing --gtest_output (invalid).
5220TEST_F(InitGoogleTestTest, OutputEmpty) {
5221 const char* argv[] = {
5222 "foo.exe",
5223 "--gtest_output",
5224 NULL
5225 };
5226
5227 const char* argv2[] = {
5228 "foo.exe",
5229 "--gtest_output",
5230 NULL
5231 };
5232
zhanyong.wan4cd62602009-02-23 23:21:55 +00005233 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
shiqian4b6829f2008-07-03 22:38:12 +00005234}
5235
5236// Tests parsing --gtest_output=xml
5237TEST_F(InitGoogleTestTest, OutputXml) {
5238 const char* argv[] = {
5239 "foo.exe",
5240 "--gtest_output=xml",
5241 NULL
5242 };
5243
5244 const char* argv2[] = {
5245 "foo.exe",
5246 NULL
5247 };
5248
zhanyong.wan4cd62602009-02-23 23:21:55 +00005249 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"));
shiqian4b6829f2008-07-03 22:38:12 +00005250}
5251
5252// Tests parsing --gtest_output=xml:file
5253TEST_F(InitGoogleTestTest, OutputXmlFile) {
5254 const char* argv[] = {
5255 "foo.exe",
5256 "--gtest_output=xml:file",
5257 NULL
5258 };
5259
5260 const char* argv2[] = {
5261 "foo.exe",
5262 NULL
5263 };
5264
zhanyong.wan4cd62602009-02-23 23:21:55 +00005265 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"));
shiqian4b6829f2008-07-03 22:38:12 +00005266}
5267
5268// Tests parsing --gtest_output=xml:directory/path/
5269TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5270 const char* argv[] = {
5271 "foo.exe",
5272 "--gtest_output=xml:directory/path/",
5273 NULL
5274 };
5275
5276 const char* argv2[] = {
5277 "foo.exe",
5278 NULL
5279 };
5280
zhanyong.wan4cd62602009-02-23 23:21:55 +00005281 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"));
shiqian4b6829f2008-07-03 22:38:12 +00005282}
5283
shiqiand981cee2008-07-25 04:06:16 +00005284// Tests having a --gtest_print_time flag
5285TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5286 const char* argv[] = {
5287 "foo.exe",
5288 "--gtest_print_time",
5289 NULL
5290 };
5291
5292 const char* argv2[] = {
5293 "foo.exe",
5294 NULL
5295 };
5296
zhanyong.wan4cd62602009-02-23 23:21:55 +00005297 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005298}
5299
5300// Tests having a --gtest_print_time flag with a "true" value
5301TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5302 const char* argv[] = {
5303 "foo.exe",
5304 "--gtest_print_time=1",
5305 NULL
5306 };
5307
5308 const char* argv2[] = {
5309 "foo.exe",
5310 NULL
5311 };
5312
zhanyong.wan4cd62602009-02-23 23:21:55 +00005313 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
shiqiand981cee2008-07-25 04:06:16 +00005314}
5315
5316// Tests having a --gtest_print_time flag with a "false" value
5317TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5318 const char* argv[] = {
5319 "foo.exe",
5320 "--gtest_print_time=0",
5321 NULL
5322 };
5323
5324 const char* argv2[] = {
5325 "foo.exe",
5326 NULL
5327 };
5328
zhanyong.wan4cd62602009-02-23 23:21:55 +00005329 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005330}
5331
5332// Tests parsing --gtest_print_time=f.
5333TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5334 const char* argv[] = {
5335 "foo.exe",
5336 "--gtest_print_time=f",
5337 NULL
5338 };
5339
5340 const char* argv2[] = {
5341 "foo.exe",
5342 NULL
5343 };
5344
zhanyong.wan4cd62602009-02-23 23:21:55 +00005345 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005346}
5347
5348// Tests parsing --gtest_print_time=F.
5349TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5350 const char* argv[] = {
5351 "foo.exe",
5352 "--gtest_print_time=F",
5353 NULL
5354 };
5355
5356 const char* argv2[] = {
5357 "foo.exe",
5358 NULL
5359 };
5360
zhanyong.wan4cd62602009-02-23 23:21:55 +00005361 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
shiqiand981cee2008-07-25 04:06:16 +00005362}
5363
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005364// Tests parsing --gtest_random_seed=number
5365TEST_F(InitGoogleTestTest, RandomSeed) {
5366 const char* argv[] = {
5367 "foo.exe",
5368 "--gtest_random_seed=1000",
5369 NULL
5370 };
5371
5372 const char* argv2[] = {
5373 "foo.exe",
5374 NULL
5375 };
5376
5377 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000));
5378}
5379
shiqian4b6829f2008-07-03 22:38:12 +00005380// Tests parsing --gtest_repeat=number
5381TEST_F(InitGoogleTestTest, Repeat) {
5382 const char* argv[] = {
5383 "foo.exe",
5384 "--gtest_repeat=1000",
5385 NULL
5386 };
5387
5388 const char* argv2[] = {
5389 "foo.exe",
5390 NULL
5391 };
5392
zhanyong.wan4cd62602009-02-23 23:21:55 +00005393 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000));
shiqian4b6829f2008-07-03 22:38:12 +00005394}
5395
shiqianca6949f2009-01-10 01:16:33 +00005396// Tests having a --gtest_also_run_disabled_tests flag
5397TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5398 const char* argv[] = {
5399 "foo.exe",
5400 "--gtest_also_run_disabled_tests",
5401 NULL
5402 };
5403
5404 const char* argv2[] = {
5405 "foo.exe",
5406 NULL
5407 };
5408
zhanyong.wan4cd62602009-02-23 23:21:55 +00005409 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005410}
5411
5412// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5413TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5414 const char* argv[] = {
5415 "foo.exe",
5416 "--gtest_also_run_disabled_tests=1",
5417 NULL
5418 };
5419
5420 const char* argv2[] = {
5421 "foo.exe",
5422 NULL
5423 };
5424
zhanyong.wan4cd62602009-02-23 23:21:55 +00005425 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
shiqianca6949f2009-01-10 01:16:33 +00005426}
5427
5428// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5429TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5430 const char* argv[] = {
5431 "foo.exe",
5432 "--gtest_also_run_disabled_tests=0",
5433 NULL
5434 };
5435
5436 const char* argv2[] = {
5437 "foo.exe",
5438 NULL
5439 };
5440
zhanyong.wan4cd62602009-02-23 23:21:55 +00005441 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false));
shiqianca6949f2009-01-10 01:16:33 +00005442}
5443
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005444// Tests parsing --gtest_shuffle.
5445TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
5446 const char* argv[] = {
5447 "foo.exe",
5448 "--gtest_shuffle",
5449 NULL
5450};
5451
5452 const char* argv2[] = {
5453 "foo.exe",
5454 NULL
5455 };
5456
5457 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5458}
5459
5460// Tests parsing --gtest_shuffle=0.
5461TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
5462 const char* argv[] = {
5463 "foo.exe",
5464 "--gtest_shuffle=0",
5465 NULL
5466 };
5467
5468 const char* argv2[] = {
5469 "foo.exe",
5470 NULL
5471 };
5472
5473 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false));
5474}
5475
5476// Tests parsing a --gtest_shuffle flag that has a "true"
5477// definition.
5478TEST_F(InitGoogleTestTest, ShuffleTrue) {
5479 const char* argv[] = {
5480 "foo.exe",
5481 "--gtest_shuffle=1",
5482 NULL
5483 };
5484
5485 const char* argv2[] = {
5486 "foo.exe",
5487 NULL
5488 };
5489
5490 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true));
5491}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005492
5493// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005494TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005495 const char* argv[] = {
5496 "foo.exe",
5497 "--gtest_throw_on_failure",
5498 NULL
5499};
5500
5501 const char* argv2[] = {
5502 "foo.exe",
5503 NULL
5504 };
5505
5506 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5507}
5508
5509// Tests parsing --gtest_throw_on_failure=0.
5510TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5511 const char* argv[] = {
5512 "foo.exe",
5513 "--gtest_throw_on_failure=0",
5514 NULL
5515 };
5516
5517 const char* argv2[] = {
5518 "foo.exe",
5519 NULL
5520 };
5521
5522 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false));
5523}
5524
5525// Tests parsing a --gtest_throw_on_failure flag that has a "true"
5526// definition.
5527TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
5528 const char* argv[] = {
5529 "foo.exe",
5530 "--gtest_throw_on_failure=1",
5531 NULL
5532 };
5533
5534 const char* argv2[] = {
5535 "foo.exe",
5536 NULL
5537 };
5538
5539 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5540}
5541
zhanyong.wan4cd62602009-02-23 23:21:55 +00005542#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00005543// Tests parsing wide strings.
5544TEST_F(InitGoogleTestTest, WideStrings) {
5545 const wchar_t* argv[] = {
5546 L"foo.exe",
5547 L"--gtest_filter=Foo*",
5548 L"--gtest_list_tests=1",
5549 L"--gtest_break_on_failure",
5550 L"--non_gtest_flag",
5551 NULL
5552 };
5553
5554 const wchar_t* argv2[] = {
5555 L"foo.exe",
5556 L"--non_gtest_flag",
5557 NULL
5558 };
5559
5560 Flags expected_flags;
5561 expected_flags.break_on_failure = true;
5562 expected_flags.filter = "Foo*";
5563 expected_flags.list_tests = true;
5564
zhanyong.wan4cd62602009-02-23 23:21:55 +00005565 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags);
shiqian4b6829f2008-07-03 22:38:12 +00005566}
5567#endif // GTEST_OS_WINDOWS
5568
5569// Tests current_test_info() in UnitTest.
5570class CurrentTestInfoTest : public Test {
5571 protected:
5572 // Tests that current_test_info() returns NULL before the first test in
5573 // the test case is run.
5574 static void SetUpTestCase() {
5575 // There should be no tests running at this point.
5576 const TestInfo* test_info =
5577 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005578 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005579 << "There should be no tests running at this point.";
5580 }
5581
5582 // Tests that current_test_info() returns NULL after the last test in
5583 // the test case has run.
5584 static void TearDownTestCase() {
5585 const TestInfo* test_info =
5586 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00005587 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00005588 << "There should be no tests running at this point.";
5589 }
5590};
5591
5592// Tests that current_test_info() returns TestInfo for currently running
5593// test by checking the expected test name against the actual one.
5594TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
5595 const TestInfo* test_info =
5596 UnitTest::GetInstance()->current_test_info();
5597 ASSERT_TRUE(NULL != test_info)
5598 << "There is a test running so we should have a valid TestInfo.";
5599 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5600 << "Expected the name of the currently running test case.";
5601 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
5602 << "Expected the name of the currently running test.";
5603}
5604
5605// Tests that current_test_info() returns TestInfo for currently running
5606// test by checking the expected test name against the actual one. We
5607// use this test to see that the TestInfo object actually changed from
5608// the previous invocation.
5609TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
5610 const TestInfo* test_info =
5611 UnitTest::GetInstance()->current_test_info();
5612 ASSERT_TRUE(NULL != test_info)
5613 << "There is a test running so we should have a valid TestInfo.";
5614 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5615 << "Expected the name of the currently running test case.";
5616 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
5617 << "Expected the name of the currently running test.";
5618}
5619
5620} // namespace testing
5621
5622// These two lines test that we can define tests in a namespace that
5623// has the name "testing" and is nested in another namespace.
5624namespace my_namespace {
5625namespace testing {
5626
5627// Makes sure that TEST knows to use ::testing::Test instead of
5628// ::my_namespace::testing::Test.
5629class Test {};
5630
5631// Makes sure that an assertion knows to use ::testing::Message instead of
5632// ::my_namespace::testing::Message.
5633class Message {};
5634
5635// Makes sure that an assertion knows to use
5636// ::testing::AssertionResult instead of
5637// ::my_namespace::testing::AssertionResult.
5638class AssertionResult {};
5639
5640// Tests that an assertion that should succeed works as expected.
5641TEST(NestedTestingNamespaceTest, Success) {
5642 EXPECT_EQ(1, 1) << "This shouldn't fail.";
5643}
5644
5645// Tests that an assertion that should fail works as expected.
5646TEST(NestedTestingNamespaceTest, Failure) {
5647 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
5648 "This failure is expected.");
5649}
5650
5651} // namespace testing
5652} // namespace my_namespace
5653
5654// Tests that one can call superclass SetUp and TearDown methods--
5655// that is, that they are not private.
5656// No tests are based on this fixture; the test "passes" if it compiles
5657// successfully.
shiqian760af5c2008-08-06 21:43:15 +00005658class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005659 protected:
5660 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00005661 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00005662 }
5663 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00005664 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00005665 }
5666};
5667
5668// StreamingAssertionsTest tests the streaming versions of a representative
5669// sample of assertions.
5670TEST(StreamingAssertionsTest, Unconditional) {
5671 SUCCEED() << "expected success";
5672 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
5673 "expected failure");
5674 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
5675 "expected failure");
5676}
5677
zhanyong.wan98efcc42009-04-28 00:28:09 +00005678#ifdef __BORLANDC__
5679// Silences warnings: "Condition is always true", "Unreachable code"
5680#pragma option push -w-ccc -w-rch
5681#endif
5682
shiqian4b6829f2008-07-03 22:38:12 +00005683TEST(StreamingAssertionsTest, Truth) {
5684 EXPECT_TRUE(true) << "unexpected failure";
5685 ASSERT_TRUE(true) << "unexpected failure";
5686 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
5687 "expected failure");
5688 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
5689 "expected failure");
5690}
5691
5692TEST(StreamingAssertionsTest, Truth2) {
5693 EXPECT_FALSE(false) << "unexpected failure";
5694 ASSERT_FALSE(false) << "unexpected failure";
5695 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
5696 "expected failure");
5697 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
5698 "expected failure");
5699}
5700
zhanyong.wan98efcc42009-04-28 00:28:09 +00005701#ifdef __BORLANDC__
5702// Restores warnings after previous "#pragma option push" supressed them
5703#pragma option pop
5704#endif
5705
shiqian4b6829f2008-07-03 22:38:12 +00005706TEST(StreamingAssertionsTest, IntegerEquals) {
5707 EXPECT_EQ(1, 1) << "unexpected failure";
5708 ASSERT_EQ(1, 1) << "unexpected failure";
5709 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
5710 "expected failure");
5711 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
5712 "expected failure");
5713}
5714
5715TEST(StreamingAssertionsTest, IntegerLessThan) {
5716 EXPECT_LT(1, 2) << "unexpected failure";
5717 ASSERT_LT(1, 2) << "unexpected failure";
5718 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
5719 "expected failure");
5720 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
5721 "expected failure");
5722}
5723
5724TEST(StreamingAssertionsTest, StringsEqual) {
5725 EXPECT_STREQ("foo", "foo") << "unexpected failure";
5726 ASSERT_STREQ("foo", "foo") << "unexpected failure";
5727 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
5728 "expected failure");
5729 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
5730 "expected failure");
5731}
5732
5733TEST(StreamingAssertionsTest, StringsNotEqual) {
5734 EXPECT_STRNE("foo", "bar") << "unexpected failure";
5735 ASSERT_STRNE("foo", "bar") << "unexpected failure";
5736 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
5737 "expected failure");
5738 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
5739 "expected failure");
5740}
5741
5742TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
5743 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5744 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5745 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
5746 "expected failure");
5747 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
5748 "expected failure");
5749}
5750
5751TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
5752 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
5753 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
5754 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
5755 "expected failure");
5756 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
5757 "expected failure");
5758}
5759
5760TEST(StreamingAssertionsTest, FloatingPointEquals) {
5761 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5762 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5763 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5764 "expected failure");
5765 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5766 "expected failure");
5767}
5768
shiqian9204c8e2008-09-12 20:57:22 +00005769#if GTEST_HAS_EXCEPTIONS
5770
5771TEST(StreamingAssertionsTest, Throw) {
5772 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5773 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5774 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
5775 "expected failure", "expected failure");
5776 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
5777 "expected failure", "expected failure");
5778}
5779
5780TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00005781 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
5782 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00005783 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
5784 "expected failure", "expected failure");
5785 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
5786 "expected failure", "expected failure");
5787}
5788
5789TEST(StreamingAssertionsTest, AnyThrow) {
5790 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
5791 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00005792 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005793 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00005794 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00005795 "expected failure", "expected failure");
5796}
5797
5798#endif // GTEST_HAS_EXCEPTIONS
5799
shiqian4b6829f2008-07-03 22:38:12 +00005800// Tests that Google Test correctly decides whether to use colors in the output.
5801
5802TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
5803 GTEST_FLAG(color) = "yes";
5804
5805 SetEnv("TERM", "xterm"); // TERM supports colors.
5806 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5807 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5808
5809 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5810 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5811 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5812}
5813
5814TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
5815 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5816
5817 GTEST_FLAG(color) = "True";
5818 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5819
5820 GTEST_FLAG(color) = "t";
5821 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5822
5823 GTEST_FLAG(color) = "1";
5824 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5825}
5826
5827TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
5828 GTEST_FLAG(color) = "no";
5829
5830 SetEnv("TERM", "xterm"); // TERM supports colors.
5831 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5832 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5833
5834 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5835 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5836 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5837}
5838
5839TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
5840 SetEnv("TERM", "xterm"); // TERM supports colors.
5841
5842 GTEST_FLAG(color) = "F";
5843 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5844
5845 GTEST_FLAG(color) = "0";
5846 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5847
5848 GTEST_FLAG(color) = "unknown";
5849 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5850}
5851
5852TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
5853 GTEST_FLAG(color) = "auto";
5854
5855 SetEnv("TERM", "xterm"); // TERM supports colors.
5856 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5857 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5858}
5859
5860TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
5861 GTEST_FLAG(color) = "auto";
5862
zhanyong.wan4cd62602009-02-23 23:21:55 +00005863#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00005864 // On Windows, we ignore the TERM variable as it's usually not set.
5865
5866 SetEnv("TERM", "dumb");
5867 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5868
5869 SetEnv("TERM", "");
5870 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5871
5872 SetEnv("TERM", "xterm");
5873 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5874#else
5875 // On non-Windows platforms, we rely on TERM to determine if the
5876 // terminal supports colors.
5877
5878 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5879 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5880
5881 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
5882 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5883
5884 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
5885 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5886
5887 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
5888 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5889
5890 SetEnv("TERM", "xterm"); // TERM supports colors.
5891 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5892
5893 SetEnv("TERM", "xterm-color"); // TERM supports colors.
5894 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00005895
5896 SetEnv("TERM", "linux"); // TERM supports colors.
5897 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00005898#endif // GTEST_OS_WINDOWS
5899}
5900
shiqian21d43d12009-01-08 01:10:31 +00005901// Verifies that StaticAssertTypeEq works in a namespace scope.
5902
5903static bool dummy1 = StaticAssertTypeEq<bool, bool>();
5904static bool dummy2 = StaticAssertTypeEq<const int, const int>();
5905
5906// Verifies that StaticAssertTypeEq works in a class.
5907
5908template <typename T>
5909class StaticAssertTypeEqTestHelper {
5910 public:
5911 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
5912};
5913
5914TEST(StaticAssertTypeEqTest, WorksInClass) {
5915 StaticAssertTypeEqTestHelper<bool>();
5916}
5917
5918// Verifies that StaticAssertTypeEq works inside a function.
5919
5920typedef int IntAlias;
5921
5922TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
5923 StaticAssertTypeEq<int, IntAlias>();
5924 StaticAssertTypeEq<int*, IntAlias*>();
5925}
5926
shiqiane44602e2008-10-11 07:20:02 +00005927TEST(ThreadLocalTest, DefaultConstructor) {
5928 ThreadLocal<int> t1;
5929 EXPECT_EQ(0, t1.get());
5930
5931 ThreadLocal<void*> t2;
5932 EXPECT_TRUE(t2.get() == NULL);
5933}
5934
5935TEST(ThreadLocalTest, Init) {
5936 ThreadLocal<int> t1(123);
5937 EXPECT_EQ(123, t1.get());
5938
5939 int i = 0;
5940 ThreadLocal<int*> t2(&i);
5941 EXPECT_EQ(&i, t2.get());
5942}
5943
vladlosevf904a612008-11-20 01:40:35 +00005944TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
5945 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
5946
5947 // We don't have a stack walker in Google Test yet.
5948 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
5949 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
5950}
zhanyong.wan1b171102009-04-07 21:03:22 +00005951
5952TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
5953 EXPECT_FALSE(HasNonfatalFailure());
5954}
5955
5956static void FailFatally() { FAIL(); }
5957
5958TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
5959 FailFatally();
5960 const bool has_nonfatal_failure = HasNonfatalFailure();
5961 ClearCurrentTestPartResults();
5962 EXPECT_FALSE(has_nonfatal_failure);
5963}
5964
5965TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
5966 ADD_FAILURE();
5967 const bool has_nonfatal_failure = HasNonfatalFailure();
5968 ClearCurrentTestPartResults();
5969 EXPECT_TRUE(has_nonfatal_failure);
5970}
5971
5972TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
5973 FailFatally();
5974 ADD_FAILURE();
5975 const bool has_nonfatal_failure = HasNonfatalFailure();
5976 ClearCurrentTestPartResults();
5977 EXPECT_TRUE(has_nonfatal_failure);
5978}
5979
5980// A wrapper for calling HasNonfatalFailure outside of a test body.
5981static bool HasNonfatalFailureHelper() {
5982 return testing::Test::HasNonfatalFailure();
5983}
5984
5985TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
5986 EXPECT_FALSE(HasNonfatalFailureHelper());
5987}
5988
5989TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
5990 ADD_FAILURE();
5991 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
5992 ClearCurrentTestPartResults();
5993 EXPECT_TRUE(has_nonfatal_failure);
5994}
5995
5996TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
5997 EXPECT_FALSE(HasFailure());
5998}
5999
6000TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6001 FailFatally();
6002 const bool has_failure = HasFailure();
6003 ClearCurrentTestPartResults();
6004 EXPECT_TRUE(has_failure);
6005}
6006
6007TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6008 ADD_FAILURE();
6009 const bool has_failure = HasFailure();
6010 ClearCurrentTestPartResults();
6011 EXPECT_TRUE(has_failure);
6012}
6013
6014TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6015 FailFatally();
6016 ADD_FAILURE();
6017 const bool has_failure = HasFailure();
6018 ClearCurrentTestPartResults();
6019 EXPECT_TRUE(has_failure);
6020}
6021
6022// A wrapper for calling HasFailure outside of a test body.
6023static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6024
6025TEST(HasFailureTest, WorksOutsideOfTestBody) {
6026 EXPECT_FALSE(HasFailureHelper());
6027}
6028
6029TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6030 ADD_FAILURE();
6031 const bool has_failure = HasFailureHelper();
6032 ClearCurrentTestPartResults();
6033 EXPECT_TRUE(has_failure);
6034}