]> git.proxmox.com Git - ceph.git/blame - ceph/src/rapidjson/thirdparty/gtest/googletest/test/gtest_unittest.cc
update sources to v12.1.0
[ceph.git] / ceph / src / rapidjson / thirdparty / gtest / googletest / test / gtest_unittest.cc
CommitLineData
31f18b77
FG
1// 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"
36
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)
49 || testing::GTEST_FLAG(random_seed)
50 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
52 || testing::GTEST_FLAG(shuffle)
53 || testing::GTEST_FLAG(stack_trace_depth) > 0
54 || testing::GTEST_FLAG(stream_result_to) != "unknown"
55 || testing::GTEST_FLAG(throw_on_failure);
56 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
57}
58
59#include <limits.h> // For INT_MAX.
60#include <stdlib.h>
61#include <string.h>
62#include <time.h>
63
64#include <map>
65#include <vector>
66#include <ostream>
67
68#include "gtest/gtest-spi.h"
69
70// Indicates that this translation unit is part of Google Test's
71// implementation. It must come before gtest-internal-inl.h is
72// included, or there will be a compiler error. This trick is to
73// prevent a user from accidentally including gtest-internal-inl.h in
74// his code.
75#define GTEST_IMPLEMENTATION_ 1
76#include "src/gtest-internal-inl.h"
77#undef GTEST_IMPLEMENTATION_
78
79namespace testing {
80namespace internal {
81
82#if GTEST_CAN_STREAM_RESULTS_
83
84class StreamingListenerTest : public Test {
85 public:
86 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
87 public:
88 // Sends a string to the socket.
89 virtual void Send(const string& message) { output_ += message; }
90
91 string output_;
92 };
93
94 StreamingListenerTest()
95 : fake_sock_writer_(new FakeSocketWriter),
96 streamer_(fake_sock_writer_),
97 test_info_obj_("FooTest", "Bar", NULL, NULL,
98 CodeLocation(__FILE__, __LINE__), 0, NULL) {}
99
100 protected:
101 string* output() { return &(fake_sock_writer_->output_); }
102
103 FakeSocketWriter* const fake_sock_writer_;
104 StreamingListener streamer_;
105 UnitTest unit_test_;
106 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
107};
108
109TEST_F(StreamingListenerTest, OnTestProgramEnd) {
110 *output() = "";
111 streamer_.OnTestProgramEnd(unit_test_);
112 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
113}
114
115TEST_F(StreamingListenerTest, OnTestIterationEnd) {
116 *output() = "";
117 streamer_.OnTestIterationEnd(unit_test_, 42);
118 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
119}
120
121TEST_F(StreamingListenerTest, OnTestCaseStart) {
122 *output() = "";
123 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
124 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
125}
126
127TEST_F(StreamingListenerTest, OnTestCaseEnd) {
128 *output() = "";
129 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
130 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
131}
132
133TEST_F(StreamingListenerTest, OnTestStart) {
134 *output() = "";
135 streamer_.OnTestStart(test_info_obj_);
136 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
137}
138
139TEST_F(StreamingListenerTest, OnTestEnd) {
140 *output() = "";
141 streamer_.OnTestEnd(test_info_obj_);
142 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
143}
144
145TEST_F(StreamingListenerTest, OnTestPartResult) {
146 *output() = "";
147 streamer_.OnTestPartResult(TestPartResult(
148 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
149
150 // Meta characters in the failure message should be properly escaped.
151 EXPECT_EQ(
152 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
153 *output());
154}
155
156#endif // GTEST_CAN_STREAM_RESULTS_
157
158// Provides access to otherwise private parts of the TestEventListeners class
159// that are needed to test it.
160class TestEventListenersAccessor {
161 public:
162 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
163 return listeners->repeater();
164 }
165
166 static void SetDefaultResultPrinter(TestEventListeners* listeners,
167 TestEventListener* listener) {
168 listeners->SetDefaultResultPrinter(listener);
169 }
170 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
171 TestEventListener* listener) {
172 listeners->SetDefaultXmlGenerator(listener);
173 }
174
175 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
176 return listeners.EventForwardingEnabled();
177 }
178
179 static void SuppressEventForwarding(TestEventListeners* listeners) {
180 listeners->SuppressEventForwarding();
181 }
182};
183
184class UnitTestRecordPropertyTestHelper : public Test {
185 protected:
186 UnitTestRecordPropertyTestHelper() {}
187
188 // Forwards to UnitTest::RecordProperty() to bypass access controls.
189 void UnitTestRecordProperty(const char* key, const std::string& value) {
190 unit_test_.RecordProperty(key, value);
191 }
192
193 UnitTest unit_test_;
194};
195
196} // namespace internal
197} // namespace testing
198
199using testing::AssertionFailure;
200using testing::AssertionResult;
201using testing::AssertionSuccess;
202using testing::DoubleLE;
203using testing::EmptyTestEventListener;
204using testing::Environment;
205using testing::FloatLE;
206using testing::GTEST_FLAG(also_run_disabled_tests);
207using testing::GTEST_FLAG(break_on_failure);
208using testing::GTEST_FLAG(catch_exceptions);
209using testing::GTEST_FLAG(color);
210using testing::GTEST_FLAG(death_test_use_fork);
211using testing::GTEST_FLAG(filter);
212using testing::GTEST_FLAG(list_tests);
213using testing::GTEST_FLAG(output);
214using testing::GTEST_FLAG(print_time);
215using testing::GTEST_FLAG(random_seed);
216using testing::GTEST_FLAG(repeat);
217using testing::GTEST_FLAG(show_internal_stack_frames);
218using testing::GTEST_FLAG(shuffle);
219using testing::GTEST_FLAG(stack_trace_depth);
220using testing::GTEST_FLAG(stream_result_to);
221using testing::GTEST_FLAG(throw_on_failure);
222using testing::IsNotSubstring;
223using testing::IsSubstring;
224using testing::Message;
225using testing::ScopedFakeTestPartResultReporter;
226using testing::StaticAssertTypeEq;
227using testing::Test;
228using testing::TestCase;
229using testing::TestEventListeners;
230using testing::TestInfo;
231using testing::TestPartResult;
232using testing::TestPartResultArray;
233using testing::TestProperty;
234using testing::TestResult;
235using testing::TimeInMillis;
236using testing::UnitTest;
237using testing::internal::AddReference;
238using testing::internal::AlwaysFalse;
239using testing::internal::AlwaysTrue;
240using testing::internal::AppendUserMessage;
241using testing::internal::ArrayAwareFind;
242using testing::internal::ArrayEq;
243using testing::internal::CodePointToUtf8;
244using testing::internal::CompileAssertTypesEqual;
245using testing::internal::CopyArray;
246using testing::internal::CountIf;
247using testing::internal::EqFailure;
248using testing::internal::FloatingPoint;
249using testing::internal::ForEach;
250using testing::internal::FormatEpochTimeInMillisAsIso8601;
251using testing::internal::FormatTimeInMillisAsSeconds;
252using testing::internal::GTestFlagSaver;
253using testing::internal::GetCurrentOsStackTraceExceptTop;
254using testing::internal::GetElementOr;
255using testing::internal::GetNextRandomSeed;
256using testing::internal::GetRandomSeedFromFlag;
257using testing::internal::GetTestTypeId;
258using testing::internal::GetTimeInMillis;
259using testing::internal::GetTypeId;
260using testing::internal::GetUnitTestImpl;
261using testing::internal::ImplicitlyConvertible;
262using testing::internal::Int32;
263using testing::internal::Int32FromEnvOrDie;
264using testing::internal::IsAProtocolMessage;
265using testing::internal::IsContainer;
266using testing::internal::IsContainerTest;
267using testing::internal::IsNotContainer;
268using testing::internal::NativeArray;
269using testing::internal::ParseInt32Flag;
270using testing::internal::RelationToSourceCopy;
271using testing::internal::RelationToSourceReference;
272using testing::internal::RemoveConst;
273using testing::internal::RemoveReference;
274using testing::internal::ShouldRunTestOnShard;
275using testing::internal::ShouldShard;
276using testing::internal::ShouldUseColor;
277using testing::internal::Shuffle;
278using testing::internal::ShuffleRange;
279using testing::internal::SkipPrefix;
280using testing::internal::StreamableToString;
281using testing::internal::String;
282using testing::internal::TestEventListenersAccessor;
283using testing::internal::TestResultAccessor;
284using testing::internal::UInt32;
285using testing::internal::WideStringToUtf8;
286using testing::internal::edit_distance::CalculateOptimalEdits;
287using testing::internal::edit_distance::CreateUnifiedDiff;
288using testing::internal::edit_distance::EditType;
289using testing::internal::kMaxRandomSeed;
290using testing::internal::kTestTypeIdInGoogleTest;
291using testing::kMaxStackTraceDepth;
292
293#if GTEST_HAS_STREAM_REDIRECTION
294using testing::internal::CaptureStdout;
295using testing::internal::GetCapturedStdout;
296#endif
297
298#if GTEST_IS_THREADSAFE
299using testing::internal::ThreadWithParam;
300#endif
301
302class TestingVector : public std::vector<int> {
303};
304
305::std::ostream& operator<<(::std::ostream& os,
306 const TestingVector& vector) {
307 os << "{ ";
308 for (size_t i = 0; i < vector.size(); i++) {
309 os << vector[i] << " ";
310 }
311 os << "}";
312 return os;
313}
314
315// This line tests that we can define tests in an unnamed namespace.
316namespace {
317
318TEST(GetRandomSeedFromFlagTest, HandlesZero) {
319 const int seed = GetRandomSeedFromFlag(0);
320 EXPECT_LE(1, seed);
321 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
322}
323
324TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
325 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
326 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
327 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
328 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
329 GetRandomSeedFromFlag(kMaxRandomSeed));
330}
331
332TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
333 const int seed1 = GetRandomSeedFromFlag(-1);
334 EXPECT_LE(1, seed1);
335 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
336
337 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
338 EXPECT_LE(1, seed2);
339 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
340}
341
342TEST(GetNextRandomSeedTest, WorksForValidInput) {
343 EXPECT_EQ(2, GetNextRandomSeed(1));
344 EXPECT_EQ(3, GetNextRandomSeed(2));
345 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
346 GetNextRandomSeed(kMaxRandomSeed - 1));
347 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
348
349 // We deliberately don't test GetNextRandomSeed() with invalid
350 // inputs, as that requires death tests, which are expensive. This
351 // is fine as GetNextRandomSeed() is internal and has a
352 // straightforward definition.
353}
354
355static void ClearCurrentTestPartResults() {
356 TestResultAccessor::ClearTestPartResults(
357 GetUnitTestImpl()->current_test_result());
358}
359
360// Tests GetTypeId.
361
362TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
363 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
364 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
365}
366
367class SubClassOfTest : public Test {};
368class AnotherSubClassOfTest : public Test {};
369
370TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
371 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
372 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
373 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
374 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
375 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
376 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
377}
378
379// Verifies that GetTestTypeId() returns the same value, no matter it
380// is called from inside Google Test or outside of it.
381TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
382 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
383}
384
385// Tests FormatTimeInMillisAsSeconds().
386
387TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
388 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
389}
390
391TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
392 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
393 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
394 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
395 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
396 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
397}
398
399TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
400 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
401 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
402 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
403 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
404 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
405}
406
407// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
408// for particular dates below was verified in Python using
409// datetime.datetime.fromutctimestamp(<timetamp>/1000).
410
411// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
412// have to set up a particular timezone to obtain predictable results.
413class FormatEpochTimeInMillisAsIso8601Test : public Test {
414 public:
415 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
416 // 32 bits, even when 64-bit integer types are available. We have to
417 // force the constants to have a 64-bit type here.
418 static const TimeInMillis kMillisPerSec = 1000;
419
420 private:
421 virtual void SetUp() {
422 saved_tz_ = NULL;
423
424 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */)
425 if (getenv("TZ"))
426 saved_tz_ = strdup(getenv("TZ"));
427 GTEST_DISABLE_MSC_WARNINGS_POP_()
428
429 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
430 // cannot use the local time zone because the function's output depends
431 // on the time zone.
432 SetTimeZone("UTC+00");
433 }
434
435 virtual void TearDown() {
436 SetTimeZone(saved_tz_);
437 free(const_cast<char*>(saved_tz_));
438 saved_tz_ = NULL;
439 }
440
441 static void SetTimeZone(const char* time_zone) {
442 // tzset() distinguishes between the TZ variable being present and empty
443 // and not being present, so we have to consider the case of time_zone
444 // being NULL.
445#if _MSC_VER
446 // ...Unless it's MSVC, whose standard library's _putenv doesn't
447 // distinguish between an empty and a missing variable.
448 const std::string env_var =
449 std::string("TZ=") + (time_zone ? time_zone : "");
450 _putenv(env_var.c_str());
451 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
452 tzset();
453 GTEST_DISABLE_MSC_WARNINGS_POP_()
454#else
455 if (time_zone) {
456 setenv(("TZ"), time_zone, 1);
457 } else {
458 unsetenv("TZ");
459 }
460 tzset();
461#endif
462 }
463
464 const char* saved_tz_;
465};
466
467const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
468
469TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
470 EXPECT_EQ("2011-10-31T18:52:42",
471 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
472}
473
474TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
475 EXPECT_EQ(
476 "2011-10-31T18:52:42",
477 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
478}
479
480TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
481 EXPECT_EQ("2011-09-03T05:07:02",
482 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
483}
484
485TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
486 EXPECT_EQ("2011-09-28T17:08:22",
487 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
488}
489
490TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
491 EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
492}
493
494#if GTEST_CAN_COMPARE_NULL
495
496# ifdef __BORLANDC__
497// Silences warnings: "Condition is always true", "Unreachable code"
498# pragma option push -w-ccc -w-rch
499# endif
500
501// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
502// pointer literal.
503TEST(NullLiteralTest, IsTrueForNullLiterals) {
504 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
505 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
506 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
507 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
508}
509
510// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
511// pointer literal.
512TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
513 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
514 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
515 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
516 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
517}
518
519# ifdef __BORLANDC__
520// Restores warnings after previous "#pragma option push" suppressed them.
521# pragma option pop
522# endif
523
524#endif // GTEST_CAN_COMPARE_NULL
525//
526// Tests CodePointToUtf8().
527
528// Tests that the NUL character L'\0' is encoded correctly.
529TEST(CodePointToUtf8Test, CanEncodeNul) {
530 EXPECT_EQ("", CodePointToUtf8(L'\0'));
531}
532
533// Tests that ASCII characters are encoded correctly.
534TEST(CodePointToUtf8Test, CanEncodeAscii) {
535 EXPECT_EQ("a", CodePointToUtf8(L'a'));
536 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
537 EXPECT_EQ("&", CodePointToUtf8(L'&'));
538 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
539}
540
541// Tests that Unicode code-points that have 8 to 11 bits are encoded
542// as 110xxxxx 10xxxxxx.
543TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
544 // 000 1101 0011 => 110-00011 10-010011
545 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
546
547 // 101 0111 0110 => 110-10101 10-110110
548 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
549 // in wide strings and wide chars. In order to accomodate them, we have to
550 // introduce such character constants as integers.
551 EXPECT_EQ("\xD5\xB6",
552 CodePointToUtf8(static_cast<wchar_t>(0x576)));
553}
554
555// Tests that Unicode code-points that have 12 to 16 bits are encoded
556// as 1110xxxx 10xxxxxx 10xxxxxx.
557TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
558 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
559 EXPECT_EQ("\xE0\xA3\x93",
560 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
561
562 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
563 EXPECT_EQ("\xEC\x9D\x8D",
564 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
565}
566
567#if !GTEST_WIDE_STRING_USES_UTF16_
568// Tests in this group require a wchar_t to hold > 16 bits, and thus
569// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
570// 16-bit wide. This code may not compile on those systems.
571
572// Tests that Unicode code-points that have 17 to 21 bits are encoded
573// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
574TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
575 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
576 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
577
578 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
579 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
580
581 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
582 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
583}
584
585// Tests that encoding an invalid code-point generates the expected result.
586TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
587 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
588}
589
590#endif // !GTEST_WIDE_STRING_USES_UTF16_
591
592// Tests WideStringToUtf8().
593
594// Tests that the NUL character L'\0' is encoded correctly.
595TEST(WideStringToUtf8Test, CanEncodeNul) {
596 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
597 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
598}
599
600// Tests that ASCII strings are encoded correctly.
601TEST(WideStringToUtf8Test, CanEncodeAscii) {
602 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
603 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
604 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
605 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
606}
607
608// Tests that Unicode code-points that have 8 to 11 bits are encoded
609// as 110xxxxx 10xxxxxx.
610TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
611 // 000 1101 0011 => 110-00011 10-010011
612 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
613 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
614
615 // 101 0111 0110 => 110-10101 10-110110
616 const wchar_t s[] = { 0x576, '\0' };
617 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
618 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
619}
620
621// Tests that Unicode code-points that have 12 to 16 bits are encoded
622// as 1110xxxx 10xxxxxx 10xxxxxx.
623TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
624 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
625 const wchar_t s1[] = { 0x8D3, '\0' };
626 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
627 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
628
629 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
630 const wchar_t s2[] = { 0xC74D, '\0' };
631 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
632 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
633}
634
635// Tests that the conversion stops when the function encounters \0 character.
636TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
637 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
638}
639
640// Tests that the conversion stops when the function reaches the limit
641// specified by the 'length' parameter.
642TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
643 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
644}
645
646#if !GTEST_WIDE_STRING_USES_UTF16_
647// Tests that Unicode code-points that have 17 to 21 bits are encoded
648// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
649// on the systems using UTF-16 encoding.
650TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
651 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
652 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
653 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
654
655 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
656 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
657 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
658}
659
660// Tests that encoding an invalid code-point generates the expected result.
661TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
662 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
663 WideStringToUtf8(L"\xABCDFF", -1).c_str());
664}
665#else // !GTEST_WIDE_STRING_USES_UTF16_
666// Tests that surrogate pairs are encoded correctly on the systems using
667// UTF-16 encoding in the wide strings.
668TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
669 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
670 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
671}
672
673// Tests that encoding an invalid UTF-16 surrogate pair
674// generates the expected result.
675TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
676 // Leading surrogate is at the end of the string.
677 const wchar_t s1[] = { 0xD800, '\0' };
678 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
679 // Leading surrogate is not followed by the trailing surrogate.
680 const wchar_t s2[] = { 0xD800, 'M', '\0' };
681 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
682 // Trailing surrogate appearas without a leading surrogate.
683 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
684 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
685}
686#endif // !GTEST_WIDE_STRING_USES_UTF16_
687
688// Tests that codepoint concatenation works correctly.
689#if !GTEST_WIDE_STRING_USES_UTF16_
690TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
691 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
692 EXPECT_STREQ(
693 "\xF4\x88\x98\xB4"
694 "\xEC\x9D\x8D"
695 "\n"
696 "\xD5\xB6"
697 "\xE0\xA3\x93"
698 "\xF4\x88\x98\xB4",
699 WideStringToUtf8(s, -1).c_str());
700}
701#else
702TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
703 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
704 EXPECT_STREQ(
705 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
706 WideStringToUtf8(s, -1).c_str());
707}
708#endif // !GTEST_WIDE_STRING_USES_UTF16_
709
710// Tests the Random class.
711
712TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
713 testing::internal::Random random(42);
714 EXPECT_DEATH_IF_SUPPORTED(
715 random.Generate(0),
716 "Cannot generate a number in the range \\[0, 0\\)");
717 EXPECT_DEATH_IF_SUPPORTED(
718 random.Generate(testing::internal::Random::kMaxRange + 1),
719 "Generation of a number in \\[0, 2147483649\\) was requested, "
720 "but this can only generate numbers in \\[0, 2147483648\\)");
721}
722
723TEST(RandomTest, GeneratesNumbersWithinRange) {
724 const UInt32 kRange = 10000;
725 testing::internal::Random random(12345);
726 for (int i = 0; i < 10; i++) {
727 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
728 }
729
730 testing::internal::Random random2(testing::internal::Random::kMaxRange);
731 for (int i = 0; i < 10; i++) {
732 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
733 }
734}
735
736TEST(RandomTest, RepeatsWhenReseeded) {
737 const int kSeed = 123;
738 const int kArraySize = 10;
739 const UInt32 kRange = 10000;
740 UInt32 values[kArraySize];
741
742 testing::internal::Random random(kSeed);
743 for (int i = 0; i < kArraySize; i++) {
744 values[i] = random.Generate(kRange);
745 }
746
747 random.Reseed(kSeed);
748 for (int i = 0; i < kArraySize; i++) {
749 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
750 }
751}
752
753// Tests STL container utilities.
754
755// Tests CountIf().
756
757static bool IsPositive(int n) { return n > 0; }
758
759TEST(ContainerUtilityTest, CountIf) {
760 std::vector<int> v;
761 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
762
763 v.push_back(-1);
764 v.push_back(0);
765 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
766
767 v.push_back(2);
768 v.push_back(-10);
769 v.push_back(10);
770 EXPECT_EQ(2, CountIf(v, IsPositive));
771}
772
773// Tests ForEach().
774
775static int g_sum = 0;
776static void Accumulate(int n) { g_sum += n; }
777
778TEST(ContainerUtilityTest, ForEach) {
779 std::vector<int> v;
780 g_sum = 0;
781 ForEach(v, Accumulate);
782 EXPECT_EQ(0, g_sum); // Works for an empty container;
783
784 g_sum = 0;
785 v.push_back(1);
786 ForEach(v, Accumulate);
787 EXPECT_EQ(1, g_sum); // Works for a container with one element.
788
789 g_sum = 0;
790 v.push_back(20);
791 v.push_back(300);
792 ForEach(v, Accumulate);
793 EXPECT_EQ(321, g_sum);
794}
795
796// Tests GetElementOr().
797TEST(ContainerUtilityTest, GetElementOr) {
798 std::vector<char> a;
799 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
800
801 a.push_back('a');
802 a.push_back('b');
803 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
804 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
805 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
806 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
807}
808
809TEST(ContainerUtilityDeathTest, ShuffleRange) {
810 std::vector<int> a;
811 a.push_back(0);
812 a.push_back(1);
813 a.push_back(2);
814 testing::internal::Random random(1);
815
816 EXPECT_DEATH_IF_SUPPORTED(
817 ShuffleRange(&random, -1, 1, &a),
818 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
819 EXPECT_DEATH_IF_SUPPORTED(
820 ShuffleRange(&random, 4, 4, &a),
821 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
822 EXPECT_DEATH_IF_SUPPORTED(
823 ShuffleRange(&random, 3, 2, &a),
824 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
825 EXPECT_DEATH_IF_SUPPORTED(
826 ShuffleRange(&random, 3, 4, &a),
827 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
828}
829
830class VectorShuffleTest : public Test {
831 protected:
832 static const int kVectorSize = 20;
833
834 VectorShuffleTest() : random_(1) {
835 for (int i = 0; i < kVectorSize; i++) {
836 vector_.push_back(i);
837 }
838 }
839
840 static bool VectorIsCorrupt(const TestingVector& vector) {
841 if (kVectorSize != static_cast<int>(vector.size())) {
842 return true;
843 }
844
845 bool found_in_vector[kVectorSize] = { false };
846 for (size_t i = 0; i < vector.size(); i++) {
847 const int e = vector[i];
848 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
849 return true;
850 }
851 found_in_vector[e] = true;
852 }
853
854 // Vector size is correct, elements' range is correct, no
855 // duplicate elements. Therefore no corruption has occurred.
856 return false;
857 }
858
859 static bool VectorIsNotCorrupt(const TestingVector& vector) {
860 return !VectorIsCorrupt(vector);
861 }
862
863 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
864 for (int i = begin; i < end; i++) {
865 if (i != vector[i]) {
866 return true;
867 }
868 }
869 return false;
870 }
871
872 static bool RangeIsUnshuffled(
873 const TestingVector& vector, int begin, int end) {
874 return !RangeIsShuffled(vector, begin, end);
875 }
876
877 static bool VectorIsShuffled(const TestingVector& vector) {
878 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
879 }
880
881 static bool VectorIsUnshuffled(const TestingVector& vector) {
882 return !VectorIsShuffled(vector);
883 }
884
885 testing::internal::Random random_;
886 TestingVector vector_;
887}; // class VectorShuffleTest
888
889const int VectorShuffleTest::kVectorSize;
890
891TEST_F(VectorShuffleTest, HandlesEmptyRange) {
892 // Tests an empty range at the beginning...
893 ShuffleRange(&random_, 0, 0, &vector_);
894 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
895 ASSERT_PRED1(VectorIsUnshuffled, vector_);
896
897 // ...in the middle...
898 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
899 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
900 ASSERT_PRED1(VectorIsUnshuffled, vector_);
901
902 // ...at the end...
903 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
904 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
905 ASSERT_PRED1(VectorIsUnshuffled, vector_);
906
907 // ...and past the end.
908 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
909 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
910 ASSERT_PRED1(VectorIsUnshuffled, vector_);
911}
912
913TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
914 // Tests a size one range at the beginning...
915 ShuffleRange(&random_, 0, 1, &vector_);
916 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
917 ASSERT_PRED1(VectorIsUnshuffled, vector_);
918
919 // ...in the middle...
920 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
921 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
922 ASSERT_PRED1(VectorIsUnshuffled, vector_);
923
924 // ...and at the end.
925 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
926 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
927 ASSERT_PRED1(VectorIsUnshuffled, vector_);
928}
929
930// Because we use our own random number generator and a fixed seed,
931// we can guarantee that the following "random" tests will succeed.
932
933TEST_F(VectorShuffleTest, ShufflesEntireVector) {
934 Shuffle(&random_, &vector_);
935 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
936 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
937
938 // Tests the first and last elements in particular to ensure that
939 // there are no off-by-one problems in our shuffle algorithm.
940 EXPECT_NE(0, vector_[0]);
941 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
942}
943
944TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
945 const int kRangeSize = kVectorSize/2;
946
947 ShuffleRange(&random_, 0, kRangeSize, &vector_);
948
949 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
950 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
951 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
952}
953
954TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
955 const int kRangeSize = kVectorSize / 2;
956 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
957
958 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
959 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
960 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
961}
962
963TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
964 int kRangeSize = kVectorSize/3;
965 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
966
967 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
968 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
969 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
970 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
971}
972
973TEST_F(VectorShuffleTest, ShufflesRepeatably) {
974 TestingVector vector2;
975 for (int i = 0; i < kVectorSize; i++) {
976 vector2.push_back(i);
977 }
978
979 random_.Reseed(1234);
980 Shuffle(&random_, &vector_);
981 random_.Reseed(1234);
982 Shuffle(&random_, &vector2);
983
984 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
985 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
986
987 for (int i = 0; i < kVectorSize; i++) {
988 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
989 }
990}
991
992// Tests the size of the AssertHelper class.
993
994TEST(AssertHelperTest, AssertHelperIsSmall) {
995 // To avoid breaking clients that use lots of assertions in one
996 // function, we cannot grow the size of AssertHelper.
997 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
998}
999
1000// Tests String::EndsWithCaseInsensitive().
1001TEST(StringTest, EndsWithCaseInsensitive) {
1002 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1003 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1004 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1005 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1006
1007 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1008 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1009 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1010}
1011
1012// C++Builder's preprocessor is buggy; it fails to expand macros that
1013// appear in macro parameters after wide char literals. Provide an alias
1014// for NULL as a workaround.
1015static const wchar_t* const kNull = NULL;
1016
1017// Tests String::CaseInsensitiveWideCStringEquals
1018TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1019 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
1020 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1021 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1022 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1023 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1024 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1025 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1026 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1027}
1028
1029#if GTEST_OS_WINDOWS
1030
1031// Tests String::ShowWideCString().
1032TEST(StringTest, ShowWideCString) {
1033 EXPECT_STREQ("(null)",
1034 String::ShowWideCString(NULL).c_str());
1035 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1036 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1037}
1038
1039# if GTEST_OS_WINDOWS_MOBILE
1040TEST(StringTest, AnsiAndUtf16Null) {
1041 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1042 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1043}
1044
1045TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1046 const char* ansi = String::Utf16ToAnsi(L"str");
1047 EXPECT_STREQ("str", ansi);
1048 delete [] ansi;
1049 const WCHAR* utf16 = String::AnsiToUtf16("str");
1050 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1051 delete [] utf16;
1052}
1053
1054TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1055 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1056 EXPECT_STREQ(".:\\ \"*?", ansi);
1057 delete [] ansi;
1058 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1059 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1060 delete [] utf16;
1061}
1062# endif // GTEST_OS_WINDOWS_MOBILE
1063
1064#endif // GTEST_OS_WINDOWS
1065
1066// Tests TestProperty construction.
1067TEST(TestPropertyTest, StringValue) {
1068 TestProperty property("key", "1");
1069 EXPECT_STREQ("key", property.key());
1070 EXPECT_STREQ("1", property.value());
1071}
1072
1073// Tests TestProperty replacing a value.
1074TEST(TestPropertyTest, ReplaceStringValue) {
1075 TestProperty property("key", "1");
1076 EXPECT_STREQ("1", property.value());
1077 property.SetValue("2");
1078 EXPECT_STREQ("2", property.value());
1079}
1080
1081// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1082// functions (i.e. their definitions cannot be inlined at the call
1083// sites), or C++Builder won't compile the code.
1084static void AddFatalFailure() {
1085 FAIL() << "Expected fatal failure.";
1086}
1087
1088static void AddNonfatalFailure() {
1089 ADD_FAILURE() << "Expected non-fatal failure.";
1090}
1091
1092class ScopedFakeTestPartResultReporterTest : public Test {
1093 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1094 enum FailureMode {
1095 FATAL_FAILURE,
1096 NONFATAL_FAILURE
1097 };
1098 static void AddFailure(FailureMode failure) {
1099 if (failure == FATAL_FAILURE) {
1100 AddFatalFailure();
1101 } else {
1102 AddNonfatalFailure();
1103 }
1104 }
1105};
1106
1107// Tests that ScopedFakeTestPartResultReporter intercepts test
1108// failures.
1109TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1110 TestPartResultArray results;
1111 {
1112 ScopedFakeTestPartResultReporter reporter(
1113 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1114 &results);
1115 AddFailure(NONFATAL_FAILURE);
1116 AddFailure(FATAL_FAILURE);
1117 }
1118
1119 EXPECT_EQ(2, results.size());
1120 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1121 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1122}
1123
1124TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1125 TestPartResultArray results;
1126 {
1127 // Tests, that the deprecated constructor still works.
1128 ScopedFakeTestPartResultReporter reporter(&results);
1129 AddFailure(NONFATAL_FAILURE);
1130 }
1131 EXPECT_EQ(1, results.size());
1132}
1133
1134#if GTEST_IS_THREADSAFE
1135
1136class ScopedFakeTestPartResultReporterWithThreadsTest
1137 : public ScopedFakeTestPartResultReporterTest {
1138 protected:
1139 static void AddFailureInOtherThread(FailureMode failure) {
1140 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1141 thread.Join();
1142 }
1143};
1144
1145TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1146 InterceptsTestFailuresInAllThreads) {
1147 TestPartResultArray results;
1148 {
1149 ScopedFakeTestPartResultReporter reporter(
1150 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1151 AddFailure(NONFATAL_FAILURE);
1152 AddFailure(FATAL_FAILURE);
1153 AddFailureInOtherThread(NONFATAL_FAILURE);
1154 AddFailureInOtherThread(FATAL_FAILURE);
1155 }
1156
1157 EXPECT_EQ(4, results.size());
1158 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1159 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1160 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1161 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1162}
1163
1164#endif // GTEST_IS_THREADSAFE
1165
1166// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1167// work even if the failure is generated in a called function rather than
1168// the current context.
1169
1170typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1171
1172TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1173 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1174}
1175
1176#if GTEST_HAS_GLOBAL_STRING
1177TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1178 EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1179}
1180#endif
1181
1182TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1183 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1184 ::std::string("Expected fatal failure."));
1185}
1186
1187TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1188 // We have another test below to verify that the macro catches fatal
1189 // failures generated on another thread.
1190 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1191 "Expected fatal failure.");
1192}
1193
1194#ifdef __BORLANDC__
1195// Silences warnings: "Condition is always true"
1196# pragma option push -w-ccc
1197#endif
1198
1199// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1200// function even when the statement in it contains ASSERT_*.
1201
1202int NonVoidFunction() {
1203 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1204 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1205 return 0;
1206}
1207
1208TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1209 NonVoidFunction();
1210}
1211
1212// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1213// current function even though 'statement' generates a fatal failure.
1214
1215void DoesNotAbortHelper(bool* aborted) {
1216 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1217 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1218
1219 *aborted = false;
1220}
1221
1222#ifdef __BORLANDC__
1223// Restores warnings after previous "#pragma option push" suppressed them.
1224# pragma option pop
1225#endif
1226
1227TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1228 bool aborted = true;
1229 DoesNotAbortHelper(&aborted);
1230 EXPECT_FALSE(aborted);
1231}
1232
1233// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1234// statement that contains a macro which expands to code containing an
1235// unprotected comma.
1236
1237static int global_var = 0;
1238#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1239
1240TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1241#ifndef __BORLANDC__
1242 // ICE's in C++Builder.
1243 EXPECT_FATAL_FAILURE({
1244 GTEST_USE_UNPROTECTED_COMMA_;
1245 AddFatalFailure();
1246 }, "");
1247#endif
1248
1249 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1250 GTEST_USE_UNPROTECTED_COMMA_;
1251 AddFatalFailure();
1252 }, "");
1253}
1254
1255// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1256
1257typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1258
1259TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1260 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1261 "Expected non-fatal failure.");
1262}
1263
1264#if GTEST_HAS_GLOBAL_STRING
1265TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1266 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1267 ::string("Expected non-fatal failure."));
1268}
1269#endif
1270
1271TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1272 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1273 ::std::string("Expected non-fatal failure."));
1274}
1275
1276TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1277 // We have another test below to verify that the macro catches
1278 // non-fatal failures generated on another thread.
1279 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1280 "Expected non-fatal failure.");
1281}
1282
1283// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1284// statement that contains a macro which expands to code containing an
1285// unprotected comma.
1286TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1287 EXPECT_NONFATAL_FAILURE({
1288 GTEST_USE_UNPROTECTED_COMMA_;
1289 AddNonfatalFailure();
1290 }, "");
1291
1292 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1293 GTEST_USE_UNPROTECTED_COMMA_;
1294 AddNonfatalFailure();
1295 }, "");
1296}
1297
1298#if GTEST_IS_THREADSAFE
1299
1300typedef ScopedFakeTestPartResultReporterWithThreadsTest
1301 ExpectFailureWithThreadsTest;
1302
1303TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1304 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1305 "Expected fatal failure.");
1306}
1307
1308TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1309 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1310 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1311}
1312
1313#endif // GTEST_IS_THREADSAFE
1314
1315// Tests the TestProperty class.
1316
1317TEST(TestPropertyTest, ConstructorWorks) {
1318 const TestProperty property("key", "value");
1319 EXPECT_STREQ("key", property.key());
1320 EXPECT_STREQ("value", property.value());
1321}
1322
1323TEST(TestPropertyTest, SetValue) {
1324 TestProperty property("key", "value_1");
1325 EXPECT_STREQ("key", property.key());
1326 property.SetValue("value_2");
1327 EXPECT_STREQ("key", property.key());
1328 EXPECT_STREQ("value_2", property.value());
1329}
1330
1331// Tests the TestResult class
1332
1333// The test fixture for testing TestResult.
1334class TestResultTest : public Test {
1335 protected:
1336 typedef std::vector<TestPartResult> TPRVector;
1337
1338 // We make use of 2 TestPartResult objects,
1339 TestPartResult * pr1, * pr2;
1340
1341 // ... and 3 TestResult objects.
1342 TestResult * r0, * r1, * r2;
1343
1344 virtual void SetUp() {
1345 // pr1 is for success.
1346 pr1 = new TestPartResult(TestPartResult::kSuccess,
1347 "foo/bar.cc",
1348 10,
1349 "Success!");
1350
1351 // pr2 is for fatal failure.
1352 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1353 "foo/bar.cc",
1354 -1, // This line number means "unknown"
1355 "Failure!");
1356
1357 // Creates the TestResult objects.
1358 r0 = new TestResult();
1359 r1 = new TestResult();
1360 r2 = new TestResult();
1361
1362 // In order to test TestResult, we need to modify its internal
1363 // state, in particular the TestPartResult vector it holds.
1364 // test_part_results() returns a const reference to this vector.
1365 // We cast it to a non-const object s.t. it can be modified (yes,
1366 // this is a hack).
1367 TPRVector* results1 = const_cast<TPRVector*>(
1368 &TestResultAccessor::test_part_results(*r1));
1369 TPRVector* results2 = const_cast<TPRVector*>(
1370 &TestResultAccessor::test_part_results(*r2));
1371
1372 // r0 is an empty TestResult.
1373
1374 // r1 contains a single SUCCESS TestPartResult.
1375 results1->push_back(*pr1);
1376
1377 // r2 contains a SUCCESS, and a FAILURE.
1378 results2->push_back(*pr1);
1379 results2->push_back(*pr2);
1380 }
1381
1382 virtual void TearDown() {
1383 delete pr1;
1384 delete pr2;
1385
1386 delete r0;
1387 delete r1;
1388 delete r2;
1389 }
1390
1391 // Helper that compares two two TestPartResults.
1392 static void CompareTestPartResult(const TestPartResult& expected,
1393 const TestPartResult& actual) {
1394 EXPECT_EQ(expected.type(), actual.type());
1395 EXPECT_STREQ(expected.file_name(), actual.file_name());
1396 EXPECT_EQ(expected.line_number(), actual.line_number());
1397 EXPECT_STREQ(expected.summary(), actual.summary());
1398 EXPECT_STREQ(expected.message(), actual.message());
1399 EXPECT_EQ(expected.passed(), actual.passed());
1400 EXPECT_EQ(expected.failed(), actual.failed());
1401 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1402 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1403 }
1404};
1405
1406// Tests TestResult::total_part_count().
1407TEST_F(TestResultTest, total_part_count) {
1408 ASSERT_EQ(0, r0->total_part_count());
1409 ASSERT_EQ(1, r1->total_part_count());
1410 ASSERT_EQ(2, r2->total_part_count());
1411}
1412
1413// Tests TestResult::Passed().
1414TEST_F(TestResultTest, Passed) {
1415 ASSERT_TRUE(r0->Passed());
1416 ASSERT_TRUE(r1->Passed());
1417 ASSERT_FALSE(r2->Passed());
1418}
1419
1420// Tests TestResult::Failed().
1421TEST_F(TestResultTest, Failed) {
1422 ASSERT_FALSE(r0->Failed());
1423 ASSERT_FALSE(r1->Failed());
1424 ASSERT_TRUE(r2->Failed());
1425}
1426
1427// Tests TestResult::GetTestPartResult().
1428
1429typedef TestResultTest TestResultDeathTest;
1430
1431TEST_F(TestResultDeathTest, GetTestPartResult) {
1432 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1433 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1434 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1435 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1436}
1437
1438// Tests TestResult has no properties when none are added.
1439TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1440 TestResult test_result;
1441 ASSERT_EQ(0, test_result.test_property_count());
1442}
1443
1444// Tests TestResult has the expected property when added.
1445TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1446 TestResult test_result;
1447 TestProperty property("key_1", "1");
1448 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1449 ASSERT_EQ(1, test_result.test_property_count());
1450 const TestProperty& actual_property = test_result.GetTestProperty(0);
1451 EXPECT_STREQ("key_1", actual_property.key());
1452 EXPECT_STREQ("1", actual_property.value());
1453}
1454
1455// Tests TestResult has multiple properties when added.
1456TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1457 TestResult test_result;
1458 TestProperty property_1("key_1", "1");
1459 TestProperty property_2("key_2", "2");
1460 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1461 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1462 ASSERT_EQ(2, test_result.test_property_count());
1463 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1464 EXPECT_STREQ("key_1", actual_property_1.key());
1465 EXPECT_STREQ("1", actual_property_1.value());
1466
1467 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1468 EXPECT_STREQ("key_2", actual_property_2.key());
1469 EXPECT_STREQ("2", actual_property_2.value());
1470}
1471
1472// Tests TestResult::RecordProperty() overrides values for duplicate keys.
1473TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1474 TestResult test_result;
1475 TestProperty property_1_1("key_1", "1");
1476 TestProperty property_2_1("key_2", "2");
1477 TestProperty property_1_2("key_1", "12");
1478 TestProperty property_2_2("key_2", "22");
1479 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1480 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1481 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1482 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1483
1484 ASSERT_EQ(2, test_result.test_property_count());
1485 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1486 EXPECT_STREQ("key_1", actual_property_1.key());
1487 EXPECT_STREQ("12", actual_property_1.value());
1488
1489 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1490 EXPECT_STREQ("key_2", actual_property_2.key());
1491 EXPECT_STREQ("22", actual_property_2.value());
1492}
1493
1494// Tests TestResult::GetTestProperty().
1495TEST(TestResultPropertyTest, GetTestProperty) {
1496 TestResult test_result;
1497 TestProperty property_1("key_1", "1");
1498 TestProperty property_2("key_2", "2");
1499 TestProperty property_3("key_3", "3");
1500 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1501 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1502 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1503
1504 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1505 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1506 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1507
1508 EXPECT_STREQ("key_1", fetched_property_1.key());
1509 EXPECT_STREQ("1", fetched_property_1.value());
1510
1511 EXPECT_STREQ("key_2", fetched_property_2.key());
1512 EXPECT_STREQ("2", fetched_property_2.value());
1513
1514 EXPECT_STREQ("key_3", fetched_property_3.key());
1515 EXPECT_STREQ("3", fetched_property_3.value());
1516
1517 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1518 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1519}
1520
1521// Tests the Test class.
1522//
1523// It's difficult to test every public method of this class (we are
1524// already stretching the limit of Google Test by using it to test itself!).
1525// Fortunately, we don't have to do that, as we are already testing
1526// the functionalities of the Test class extensively by using Google Test
1527// alone.
1528//
1529// Therefore, this section only contains one test.
1530
1531// Tests that GTestFlagSaver works on Windows and Mac.
1532
1533class GTestFlagSaverTest : public Test {
1534 protected:
1535 // Saves the Google Test flags such that we can restore them later, and
1536 // then sets them to their default values. This will be called
1537 // before the first test in this test case is run.
1538 static void SetUpTestCase() {
1539 saver_ = new GTestFlagSaver;
1540
1541 GTEST_FLAG(also_run_disabled_tests) = false;
1542 GTEST_FLAG(break_on_failure) = false;
1543 GTEST_FLAG(catch_exceptions) = false;
1544 GTEST_FLAG(death_test_use_fork) = false;
1545 GTEST_FLAG(color) = "auto";
1546 GTEST_FLAG(filter) = "";
1547 GTEST_FLAG(list_tests) = false;
1548 GTEST_FLAG(output) = "";
1549 GTEST_FLAG(print_time) = true;
1550 GTEST_FLAG(random_seed) = 0;
1551 GTEST_FLAG(repeat) = 1;
1552 GTEST_FLAG(shuffle) = false;
1553 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1554 GTEST_FLAG(stream_result_to) = "";
1555 GTEST_FLAG(throw_on_failure) = false;
1556 }
1557
1558 // Restores the Google Test flags that the tests have modified. This will
1559 // be called after the last test in this test case is run.
1560 static void TearDownTestCase() {
1561 delete saver_;
1562 saver_ = NULL;
1563 }
1564
1565 // Verifies that the Google Test flags have their default values, and then
1566 // modifies each of them.
1567 void VerifyAndModifyFlags() {
1568 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1569 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1570 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1571 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1572 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1573 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1574 EXPECT_FALSE(GTEST_FLAG(list_tests));
1575 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1576 EXPECT_TRUE(GTEST_FLAG(print_time));
1577 EXPECT_EQ(0, GTEST_FLAG(random_seed));
1578 EXPECT_EQ(1, GTEST_FLAG(repeat));
1579 EXPECT_FALSE(GTEST_FLAG(shuffle));
1580 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1581 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1582 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1583
1584 GTEST_FLAG(also_run_disabled_tests) = true;
1585 GTEST_FLAG(break_on_failure) = true;
1586 GTEST_FLAG(catch_exceptions) = true;
1587 GTEST_FLAG(color) = "no";
1588 GTEST_FLAG(death_test_use_fork) = true;
1589 GTEST_FLAG(filter) = "abc";
1590 GTEST_FLAG(list_tests) = true;
1591 GTEST_FLAG(output) = "xml:foo.xml";
1592 GTEST_FLAG(print_time) = false;
1593 GTEST_FLAG(random_seed) = 1;
1594 GTEST_FLAG(repeat) = 100;
1595 GTEST_FLAG(shuffle) = true;
1596 GTEST_FLAG(stack_trace_depth) = 1;
1597 GTEST_FLAG(stream_result_to) = "localhost:1234";
1598 GTEST_FLAG(throw_on_failure) = true;
1599 }
1600
1601 private:
1602 // For saving Google Test flags during this test case.
1603 static GTestFlagSaver* saver_;
1604};
1605
1606GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1607
1608// Google Test doesn't guarantee the order of tests. The following two
1609// tests are designed to work regardless of their order.
1610
1611// Modifies the Google Test flags in the test body.
1612TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1613 VerifyAndModifyFlags();
1614}
1615
1616// Verifies that the Google Test flags in the body of the previous test were
1617// restored to their original values.
1618TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1619 VerifyAndModifyFlags();
1620}
1621
1622// Sets an environment variable with the given name to the given
1623// value. If the value argument is "", unsets the environment
1624// variable. The caller must ensure that both arguments are not NULL.
1625static void SetEnv(const char* name, const char* value) {
1626#if GTEST_OS_WINDOWS_MOBILE
1627 // Environment variables are not supported on Windows CE.
1628 return;
1629#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1630 // C++Builder's putenv only stores a pointer to its parameter; we have to
1631 // ensure that the string remains valid as long as it might be needed.
1632 // We use an std::map to do so.
1633 static std::map<std::string, std::string*> added_env;
1634
1635 // Because putenv stores a pointer to the string buffer, we can't delete the
1636 // previous string (if present) until after it's replaced.
1637 std::string *prev_env = NULL;
1638 if (added_env.find(name) != added_env.end()) {
1639 prev_env = added_env[name];
1640 }
1641 added_env[name] = new std::string(
1642 (Message() << name << "=" << value).GetString());
1643
1644 // The standard signature of putenv accepts a 'char*' argument. Other
1645 // implementations, like C++Builder's, accept a 'const char*'.
1646 // We cast away the 'const' since that would work for both variants.
1647 putenv(const_cast<char*>(added_env[name]->c_str()));
1648 delete prev_env;
1649#elif GTEST_OS_WINDOWS // If we are on Windows proper.
1650 _putenv((Message() << name << "=" << value).GetString().c_str());
1651#else
1652 if (*value == '\0') {
1653 unsetenv(name);
1654 } else {
1655 setenv(name, value, 1);
1656 }
1657#endif // GTEST_OS_WINDOWS_MOBILE
1658}
1659
1660#if !GTEST_OS_WINDOWS_MOBILE
1661// Environment variables are not supported on Windows CE.
1662
1663using testing::internal::Int32FromGTestEnv;
1664
1665// Tests Int32FromGTestEnv().
1666
1667// Tests that Int32FromGTestEnv() returns the default value when the
1668// environment variable is not set.
1669TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1670 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1671 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1672}
1673
1674# if !defined(GTEST_GET_INT32_FROM_ENV_)
1675
1676// Tests that Int32FromGTestEnv() returns the default value when the
1677// environment variable overflows as an Int32.
1678TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1679 printf("(expecting 2 warnings)\n");
1680
1681 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1682 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1683
1684 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1685 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1686}
1687
1688// Tests that Int32FromGTestEnv() returns the default value when the
1689// environment variable does not represent a valid decimal integer.
1690TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1691 printf("(expecting 2 warnings)\n");
1692
1693 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1694 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1695
1696 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1697 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1698}
1699
1700# endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1701
1702// Tests that Int32FromGTestEnv() parses and returns the value of the
1703// environment variable when it represents a valid decimal integer in
1704// the range of an Int32.
1705TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1706 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1707 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1708
1709 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1710 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1711}
1712#endif // !GTEST_OS_WINDOWS_MOBILE
1713
1714// Tests ParseInt32Flag().
1715
1716// Tests that ParseInt32Flag() returns false and doesn't change the
1717// output value when the flag has wrong format
1718TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1719 Int32 value = 123;
1720 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1721 EXPECT_EQ(123, value);
1722
1723 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1724 EXPECT_EQ(123, value);
1725}
1726
1727// Tests that ParseInt32Flag() returns false and doesn't change the
1728// output value when the flag overflows as an Int32.
1729TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1730 printf("(expecting 2 warnings)\n");
1731
1732 Int32 value = 123;
1733 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1734 EXPECT_EQ(123, value);
1735
1736 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1737 EXPECT_EQ(123, value);
1738}
1739
1740// Tests that ParseInt32Flag() returns false and doesn't change the
1741// output value when the flag does not represent a valid decimal
1742// integer.
1743TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1744 printf("(expecting 2 warnings)\n");
1745
1746 Int32 value = 123;
1747 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1748 EXPECT_EQ(123, value);
1749
1750 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1751 EXPECT_EQ(123, value);
1752}
1753
1754// Tests that ParseInt32Flag() parses the value of the flag and
1755// returns true when the flag represents a valid decimal integer in
1756// the range of an Int32.
1757TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1758 Int32 value = 123;
1759 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1760 EXPECT_EQ(456, value);
1761
1762 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1763 "abc", &value));
1764 EXPECT_EQ(-789, value);
1765}
1766
1767// Tests that Int32FromEnvOrDie() parses the value of the var or
1768// returns the correct default.
1769// Environment variables are not supported on Windows CE.
1770#if !GTEST_OS_WINDOWS_MOBILE
1771TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1772 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1773 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1774 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1775 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1776 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1777}
1778#endif // !GTEST_OS_WINDOWS_MOBILE
1779
1780// Tests that Int32FromEnvOrDie() aborts with an error message
1781// if the variable is not an Int32.
1782TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1783 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1784 EXPECT_DEATH_IF_SUPPORTED(
1785 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1786 ".*");
1787}
1788
1789// Tests that Int32FromEnvOrDie() aborts with an error message
1790// if the variable cannot be represnted by an Int32.
1791TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1792 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1793 EXPECT_DEATH_IF_SUPPORTED(
1794 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1795 ".*");
1796}
1797
1798// Tests that ShouldRunTestOnShard() selects all tests
1799// where there is 1 shard.
1800TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1801 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1802 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1803 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1804 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1805 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1806}
1807
1808class ShouldShardTest : public testing::Test {
1809 protected:
1810 virtual void SetUp() {
1811 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1812 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1813 }
1814
1815 virtual void TearDown() {
1816 SetEnv(index_var_, "");
1817 SetEnv(total_var_, "");
1818 }
1819
1820 const char* index_var_;
1821 const char* total_var_;
1822};
1823
1824// Tests that sharding is disabled if neither of the environment variables
1825// are set.
1826TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1827 SetEnv(index_var_, "");
1828 SetEnv(total_var_, "");
1829
1830 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1831 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1832}
1833
1834// Tests that sharding is not enabled if total_shards == 1.
1835TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1836 SetEnv(index_var_, "0");
1837 SetEnv(total_var_, "1");
1838 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1839 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1840}
1841
1842// Tests that sharding is enabled if total_shards > 1 and
1843// we are not in a death test subprocess.
1844// Environment variables are not supported on Windows CE.
1845#if !GTEST_OS_WINDOWS_MOBILE
1846TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1847 SetEnv(index_var_, "4");
1848 SetEnv(total_var_, "22");
1849 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1850 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1851
1852 SetEnv(index_var_, "8");
1853 SetEnv(total_var_, "9");
1854 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1855 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1856
1857 SetEnv(index_var_, "0");
1858 SetEnv(total_var_, "9");
1859 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1860 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1861}
1862#endif // !GTEST_OS_WINDOWS_MOBILE
1863
1864// Tests that we exit in error if the sharding values are not valid.
1865
1866typedef ShouldShardTest ShouldShardDeathTest;
1867
1868TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1869 SetEnv(index_var_, "4");
1870 SetEnv(total_var_, "4");
1871 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1872
1873 SetEnv(index_var_, "4");
1874 SetEnv(total_var_, "-2");
1875 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1876
1877 SetEnv(index_var_, "5");
1878 SetEnv(total_var_, "");
1879 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1880
1881 SetEnv(index_var_, "");
1882 SetEnv(total_var_, "5");
1883 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1884}
1885
1886// Tests that ShouldRunTestOnShard is a partition when 5
1887// shards are used.
1888TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1889 // Choose an arbitrary number of tests and shards.
1890 const int num_tests = 17;
1891 const int num_shards = 5;
1892
1893 // Check partitioning: each test should be on exactly 1 shard.
1894 for (int test_id = 0; test_id < num_tests; test_id++) {
1895 int prev_selected_shard_index = -1;
1896 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1897 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1898 if (prev_selected_shard_index < 0) {
1899 prev_selected_shard_index = shard_index;
1900 } else {
1901 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1902 << shard_index << " are both selected to run test " << test_id;
1903 }
1904 }
1905 }
1906 }
1907
1908 // Check balance: This is not required by the sharding protocol, but is a
1909 // desirable property for performance.
1910 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1911 int num_tests_on_shard = 0;
1912 for (int test_id = 0; test_id < num_tests; test_id++) {
1913 num_tests_on_shard +=
1914 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1915 }
1916 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1917 }
1918}
1919
1920// For the same reason we are not explicitly testing everything in the
1921// Test class, there are no separate tests for the following classes
1922// (except for some trivial cases):
1923//
1924// TestCase, UnitTest, UnitTestResultPrinter.
1925//
1926// Similarly, there are no separate tests for the following macros:
1927//
1928// TEST, TEST_F, RUN_ALL_TESTS
1929
1930TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1931 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1932 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1933}
1934
1935TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1936 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1937 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1938}
1939
1940// When a property using a reserved key is supplied to this function, it
1941// tests that a non-fatal failure is added, a fatal failure is not added,
1942// and that the property is not recorded.
1943void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1944 const TestResult& test_result, const char* key) {
1945 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1946 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1947 << "' recorded unexpectedly.";
1948}
1949
1950void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1951 const char* key) {
1952 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1953 ASSERT_TRUE(test_info != NULL);
1954 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1955 key);
1956}
1957
1958void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1959 const char* key) {
1960 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1961 ASSERT_TRUE(test_case != NULL);
1962 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1963 test_case->ad_hoc_test_result(), key);
1964}
1965
1966void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1967 const char* key) {
1968 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1969 UnitTest::GetInstance()->ad_hoc_test_result(), key);
1970}
1971
1972// Tests that property recording functions in UnitTest outside of tests
1973// functions correcly. Creating a separate instance of UnitTest ensures it
1974// is in a state similar to the UnitTest's singleton's between tests.
1975class UnitTestRecordPropertyTest :
1976 public testing::internal::UnitTestRecordPropertyTestHelper {
1977 public:
1978 static void SetUpTestCase() {
1979 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1980 "disabled");
1981 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1982 "errors");
1983 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1984 "failures");
1985 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1986 "name");
1987 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1988 "tests");
1989 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1990 "time");
1991
1992 Test::RecordProperty("test_case_key_1", "1");
1993 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1994 ASSERT_TRUE(test_case != NULL);
1995
1996 ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
1997 EXPECT_STREQ("test_case_key_1",
1998 test_case->ad_hoc_test_result().GetTestProperty(0).key());
1999 EXPECT_STREQ("1",
2000 test_case->ad_hoc_test_result().GetTestProperty(0).value());
2001 }
2002};
2003
2004// Tests TestResult has the expected property when added.
2005TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2006 UnitTestRecordProperty("key_1", "1");
2007
2008 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2009
2010 EXPECT_STREQ("key_1",
2011 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2012 EXPECT_STREQ("1",
2013 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2014}
2015
2016// Tests TestResult has multiple properties when added.
2017TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2018 UnitTestRecordProperty("key_1", "1");
2019 UnitTestRecordProperty("key_2", "2");
2020
2021 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2022
2023 EXPECT_STREQ("key_1",
2024 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2025 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2026
2027 EXPECT_STREQ("key_2",
2028 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2029 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2030}
2031
2032// Tests TestResult::RecordProperty() overrides values for duplicate keys.
2033TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2034 UnitTestRecordProperty("key_1", "1");
2035 UnitTestRecordProperty("key_2", "2");
2036 UnitTestRecordProperty("key_1", "12");
2037 UnitTestRecordProperty("key_2", "22");
2038
2039 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2040
2041 EXPECT_STREQ("key_1",
2042 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2043 EXPECT_STREQ("12",
2044 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2045
2046 EXPECT_STREQ("key_2",
2047 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2048 EXPECT_STREQ("22",
2049 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2050}
2051
2052TEST_F(UnitTestRecordPropertyTest,
2053 AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2054 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2055 "name");
2056 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2057 "value_param");
2058 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2059 "type_param");
2060 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2061 "status");
2062 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2063 "time");
2064 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2065 "classname");
2066}
2067
2068TEST_F(UnitTestRecordPropertyTest,
2069 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2070 EXPECT_NONFATAL_FAILURE(
2071 Test::RecordProperty("name", "1"),
2072 "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
2073 " are reserved");
2074}
2075
2076class UnitTestRecordPropertyTestEnvironment : public Environment {
2077 public:
2078 virtual void TearDown() {
2079 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2080 "tests");
2081 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2082 "failures");
2083 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2084 "disabled");
2085 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2086 "errors");
2087 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2088 "name");
2089 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2090 "timestamp");
2091 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2092 "time");
2093 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2094 "random_seed");
2095 }
2096};
2097
2098// This will test property recording outside of any test or test case.
2099static Environment* record_property_env =
2100 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2101
2102// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2103// of various arities. They do not attempt to be exhaustive. Rather,
2104// view them as smoke tests that can be easily reviewed and verified.
2105// A more complete set of tests for predicate assertions can be found
2106// in gtest_pred_impl_unittest.cc.
2107
2108// First, some predicates and predicate-formatters needed by the tests.
2109
2110// Returns true iff the argument is an even number.
2111bool IsEven(int n) {
2112 return (n % 2) == 0;
2113}
2114
2115// A functor that returns true iff the argument is an even number.
2116struct IsEvenFunctor {
2117 bool operator()(int n) { return IsEven(n); }
2118};
2119
2120// A predicate-formatter function that asserts the argument is an even
2121// number.
2122AssertionResult AssertIsEven(const char* expr, int n) {
2123 if (IsEven(n)) {
2124 return AssertionSuccess();
2125 }
2126
2127 Message msg;
2128 msg << expr << " evaluates to " << n << ", which is not even.";
2129 return AssertionFailure(msg);
2130}
2131
2132// A predicate function that returns AssertionResult for use in
2133// EXPECT/ASSERT_TRUE/FALSE.
2134AssertionResult ResultIsEven(int n) {
2135 if (IsEven(n))
2136 return AssertionSuccess() << n << " is even";
2137 else
2138 return AssertionFailure() << n << " is odd";
2139}
2140
2141// A predicate function that returns AssertionResult but gives no
2142// explanation why it succeeds. Needed for testing that
2143// EXPECT/ASSERT_FALSE handles such functions correctly.
2144AssertionResult ResultIsEvenNoExplanation(int n) {
2145 if (IsEven(n))
2146 return AssertionSuccess();
2147 else
2148 return AssertionFailure() << n << " is odd";
2149}
2150
2151// A predicate-formatter functor that asserts the argument is an even
2152// number.
2153struct AssertIsEvenFunctor {
2154 AssertionResult operator()(const char* expr, int n) {
2155 return AssertIsEven(expr, n);
2156 }
2157};
2158
2159// Returns true iff the sum of the arguments is an even number.
2160bool SumIsEven2(int n1, int n2) {
2161 return IsEven(n1 + n2);
2162}
2163
2164// A functor that returns true iff the sum of the arguments is an even
2165// number.
2166struct SumIsEven3Functor {
2167 bool operator()(int n1, int n2, int n3) {
2168 return IsEven(n1 + n2 + n3);
2169 }
2170};
2171
2172// A predicate-formatter function that asserts the sum of the
2173// arguments is an even number.
2174AssertionResult AssertSumIsEven4(
2175 const char* e1, const char* e2, const char* e3, const char* e4,
2176 int n1, int n2, int n3, int n4) {
2177 const int sum = n1 + n2 + n3 + n4;
2178 if (IsEven(sum)) {
2179 return AssertionSuccess();
2180 }
2181
2182 Message msg;
2183 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2184 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2185 << ") evaluates to " << sum << ", which is not even.";
2186 return AssertionFailure(msg);
2187}
2188
2189// A predicate-formatter functor that asserts the sum of the arguments
2190// is an even number.
2191struct AssertSumIsEven5Functor {
2192 AssertionResult operator()(
2193 const char* e1, const char* e2, const char* e3, const char* e4,
2194 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2195 const int sum = n1 + n2 + n3 + n4 + n5;
2196 if (IsEven(sum)) {
2197 return AssertionSuccess();
2198 }
2199
2200 Message msg;
2201 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2202 << " ("
2203 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2204 << ") evaluates to " << sum << ", which is not even.";
2205 return AssertionFailure(msg);
2206 }
2207};
2208
2209
2210// Tests unary predicate assertions.
2211
2212// Tests unary predicate assertions that don't use a custom formatter.
2213TEST(Pred1Test, WithoutFormat) {
2214 // Success cases.
2215 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2216 ASSERT_PRED1(IsEven, 4);
2217
2218 // Failure cases.
2219 EXPECT_NONFATAL_FAILURE({ // NOLINT
2220 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2221 }, "This failure is expected.");
2222 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2223 "evaluates to false");
2224}
2225
2226// Tests unary predicate assertions that use a custom formatter.
2227TEST(Pred1Test, WithFormat) {
2228 // Success cases.
2229 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2230 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2231 << "This failure is UNEXPECTED!";
2232
2233 // Failure cases.
2234 const int n = 5;
2235 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2236 "n evaluates to 5, which is not even.");
2237 EXPECT_FATAL_FAILURE({ // NOLINT
2238 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2239 }, "This failure is expected.");
2240}
2241
2242// Tests that unary predicate assertions evaluates their arguments
2243// exactly once.
2244TEST(Pred1Test, SingleEvaluationOnFailure) {
2245 // A success case.
2246 static int n = 0;
2247 EXPECT_PRED1(IsEven, n++);
2248 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2249
2250 // A failure case.
2251 EXPECT_FATAL_FAILURE({ // NOLINT
2252 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2253 << "This failure is expected.";
2254 }, "This failure is expected.");
2255 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2256}
2257
2258
2259// Tests predicate assertions whose arity is >= 2.
2260
2261// Tests predicate assertions that don't use a custom formatter.
2262TEST(PredTest, WithoutFormat) {
2263 // Success cases.
2264 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2265 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2266
2267 // Failure cases.
2268 const int n1 = 1;
2269 const int n2 = 2;
2270 EXPECT_NONFATAL_FAILURE({ // NOLINT
2271 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2272 }, "This failure is expected.");
2273 EXPECT_FATAL_FAILURE({ // NOLINT
2274 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2275 }, "evaluates to false");
2276}
2277
2278// Tests predicate assertions that use a custom formatter.
2279TEST(PredTest, WithFormat) {
2280 // Success cases.
2281 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2282 "This failure is UNEXPECTED!";
2283 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2284
2285 // Failure cases.
2286 const int n1 = 1;
2287 const int n2 = 2;
2288 const int n3 = 4;
2289 const int n4 = 6;
2290 EXPECT_NONFATAL_FAILURE({ // NOLINT
2291 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2292 }, "evaluates to 13, which is not even.");
2293 EXPECT_FATAL_FAILURE({ // NOLINT
2294 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2295 << "This failure is expected.";
2296 }, "This failure is expected.");
2297}
2298
2299// Tests that predicate assertions evaluates their arguments
2300// exactly once.
2301TEST(PredTest, SingleEvaluationOnFailure) {
2302 // A success case.
2303 int n1 = 0;
2304 int n2 = 0;
2305 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2306 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2307 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2308
2309 // Another success case.
2310 n1 = n2 = 0;
2311 int n3 = 0;
2312 int n4 = 0;
2313 int n5 = 0;
2314 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2315 n1++, n2++, n3++, n4++, n5++)
2316 << "This failure is UNEXPECTED!";
2317 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2318 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2319 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2320 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2321 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2322
2323 // A failure case.
2324 n1 = n2 = n3 = 0;
2325 EXPECT_NONFATAL_FAILURE({ // NOLINT
2326 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2327 << "This failure is expected.";
2328 }, "This failure is expected.");
2329 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2330 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2331 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2332
2333 // Another failure case.
2334 n1 = n2 = n3 = n4 = 0;
2335 EXPECT_NONFATAL_FAILURE({ // NOLINT
2336 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2337 }, "evaluates to 1, which is not even.");
2338 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2339 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2340 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2341 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2342}
2343
2344
2345// Some helper functions for testing using overloaded/template
2346// functions with ASSERT_PREDn and EXPECT_PREDn.
2347
2348bool IsPositive(double x) {
2349 return x > 0;
2350}
2351
2352template <typename T>
2353bool IsNegative(T x) {
2354 return x < 0;
2355}
2356
2357template <typename T1, typename T2>
2358bool GreaterThan(T1 x1, T2 x2) {
2359 return x1 > x2;
2360}
2361
2362// Tests that overloaded functions can be used in *_PRED* as long as
2363// their types are explicitly specified.
2364TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2365 // C++Builder requires C-style casts rather than static_cast.
2366 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2367 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2368}
2369
2370// Tests that template functions can be used in *_PRED* as long as
2371// their types are explicitly specified.
2372TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2373 EXPECT_PRED1(IsNegative<int>, -5);
2374 // Makes sure that we can handle templates with more than one
2375 // parameter.
2376 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2377}
2378
2379
2380// Some helper functions for testing using overloaded/template
2381// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2382
2383AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2384 return n > 0 ? AssertionSuccess() :
2385 AssertionFailure(Message() << "Failure");
2386}
2387
2388AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2389 return x > 0 ? AssertionSuccess() :
2390 AssertionFailure(Message() << "Failure");
2391}
2392
2393template <typename T>
2394AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2395 return x < 0 ? AssertionSuccess() :
2396 AssertionFailure(Message() << "Failure");
2397}
2398
2399template <typename T1, typename T2>
2400AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2401 const T1& x1, const T2& x2) {
2402 return x1 == x2 ? AssertionSuccess() :
2403 AssertionFailure(Message() << "Failure");
2404}
2405
2406// Tests that overloaded functions can be used in *_PRED_FORMAT*
2407// without explicitly specifying their types.
2408TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2409 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2410 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2411}
2412
2413// Tests that template functions can be used in *_PRED_FORMAT* without
2414// explicitly specifying their types.
2415TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2416 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2417 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2418}
2419
2420
2421// Tests string assertions.
2422
2423// Tests ASSERT_STREQ with non-NULL arguments.
2424TEST(StringAssertionTest, ASSERT_STREQ) {
2425 const char * const p1 = "good";
2426 ASSERT_STREQ(p1, p1);
2427
2428 // Let p2 have the same content as p1, but be at a different address.
2429 const char p2[] = "good";
2430 ASSERT_STREQ(p1, p2);
2431
2432 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2433 "Expected: \"bad\"");
2434}
2435
2436// Tests ASSERT_STREQ with NULL arguments.
2437TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2438 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2439 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2440 "non-null");
2441}
2442
2443// Tests ASSERT_STREQ with NULL arguments.
2444TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2445 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2446 "non-null");
2447}
2448
2449// Tests ASSERT_STRNE.
2450TEST(StringAssertionTest, ASSERT_STRNE) {
2451 ASSERT_STRNE("hi", "Hi");
2452 ASSERT_STRNE("Hi", NULL);
2453 ASSERT_STRNE(NULL, "Hi");
2454 ASSERT_STRNE("", NULL);
2455 ASSERT_STRNE(NULL, "");
2456 ASSERT_STRNE("", "Hi");
2457 ASSERT_STRNE("Hi", "");
2458 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2459 "\"Hi\" vs \"Hi\"");
2460}
2461
2462// Tests ASSERT_STRCASEEQ.
2463TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2464 ASSERT_STRCASEEQ("hi", "Hi");
2465 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2466
2467 ASSERT_STRCASEEQ("", "");
2468 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2469 "Ignoring case");
2470}
2471
2472// Tests ASSERT_STRCASENE.
2473TEST(StringAssertionTest, ASSERT_STRCASENE) {
2474 ASSERT_STRCASENE("hi1", "Hi2");
2475 ASSERT_STRCASENE("Hi", NULL);
2476 ASSERT_STRCASENE(NULL, "Hi");
2477 ASSERT_STRCASENE("", NULL);
2478 ASSERT_STRCASENE(NULL, "");
2479 ASSERT_STRCASENE("", "Hi");
2480 ASSERT_STRCASENE("Hi", "");
2481 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2482 "(ignoring case)");
2483}
2484
2485// Tests *_STREQ on wide strings.
2486TEST(StringAssertionTest, STREQ_Wide) {
2487 // NULL strings.
2488 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2489
2490 // Empty strings.
2491 ASSERT_STREQ(L"", L"");
2492
2493 // Non-null vs NULL.
2494 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2495 "non-null");
2496
2497 // Equal strings.
2498 EXPECT_STREQ(L"Hi", L"Hi");
2499
2500 // Unequal strings.
2501 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2502 "Abc");
2503
2504 // Strings containing wide characters.
2505 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2506 "abc");
2507
2508 // The streaming variation.
2509 EXPECT_NONFATAL_FAILURE({ // NOLINT
2510 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2511 }, "Expected failure");
2512}
2513
2514// Tests *_STRNE on wide strings.
2515TEST(StringAssertionTest, STRNE_Wide) {
2516 // NULL strings.
2517 EXPECT_NONFATAL_FAILURE({ // NOLINT
2518 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2519 }, "");
2520
2521 // Empty strings.
2522 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2523 "L\"\"");
2524
2525 // Non-null vs NULL.
2526 ASSERT_STRNE(L"non-null", NULL);
2527
2528 // Equal strings.
2529 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2530 "L\"Hi\"");
2531
2532 // Unequal strings.
2533 EXPECT_STRNE(L"abc", L"Abc");
2534
2535 // Strings containing wide characters.
2536 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2537 "abc");
2538
2539 // The streaming variation.
2540 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2541}
2542
2543// Tests for ::testing::IsSubstring().
2544
2545// Tests that IsSubstring() returns the correct result when the input
2546// argument type is const char*.
2547TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2548 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2549 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2550 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2551
2552 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2553 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2554}
2555
2556// Tests that IsSubstring() returns the correct result when the input
2557// argument type is const wchar_t*.
2558TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2559 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2560 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2561 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2562
2563 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2564 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2565}
2566
2567// Tests that IsSubstring() generates the correct message when the input
2568// argument type is const char*.
2569TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2570 EXPECT_STREQ("Value of: needle_expr\n"
2571 " Actual: \"needle\"\n"
2572 "Expected: a substring of haystack_expr\n"
2573 "Which is: \"haystack\"",
2574 IsSubstring("needle_expr", "haystack_expr",
2575 "needle", "haystack").failure_message());
2576}
2577
2578// Tests that IsSubstring returns the correct result when the input
2579// argument type is ::std::string.
2580TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2581 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2582 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2583}
2584
2585#if GTEST_HAS_STD_WSTRING
2586// Tests that IsSubstring returns the correct result when the input
2587// argument type is ::std::wstring.
2588TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2589 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2590 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2591}
2592
2593// Tests that IsSubstring() generates the correct message when the input
2594// argument type is ::std::wstring.
2595TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2596 EXPECT_STREQ("Value of: needle_expr\n"
2597 " Actual: L\"needle\"\n"
2598 "Expected: a substring of haystack_expr\n"
2599 "Which is: L\"haystack\"",
2600 IsSubstring(
2601 "needle_expr", "haystack_expr",
2602 ::std::wstring(L"needle"), L"haystack").failure_message());
2603}
2604
2605#endif // GTEST_HAS_STD_WSTRING
2606
2607// Tests for ::testing::IsNotSubstring().
2608
2609// Tests that IsNotSubstring() returns the correct result when the input
2610// argument type is const char*.
2611TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2612 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2613 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2614}
2615
2616// Tests that IsNotSubstring() returns the correct result when the input
2617// argument type is const wchar_t*.
2618TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2619 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2620 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2621}
2622
2623// Tests that IsNotSubstring() generates the correct message when the input
2624// argument type is const wchar_t*.
2625TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2626 EXPECT_STREQ("Value of: needle_expr\n"
2627 " Actual: L\"needle\"\n"
2628 "Expected: not a substring of haystack_expr\n"
2629 "Which is: L\"two needles\"",
2630 IsNotSubstring(
2631 "needle_expr", "haystack_expr",
2632 L"needle", L"two needles").failure_message());
2633}
2634
2635// Tests that IsNotSubstring returns the correct result when the input
2636// argument type is ::std::string.
2637TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2638 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2639 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2640}
2641
2642// Tests that IsNotSubstring() generates the correct message when the input
2643// argument type is ::std::string.
2644TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2645 EXPECT_STREQ("Value of: needle_expr\n"
2646 " Actual: \"needle\"\n"
2647 "Expected: not a substring of haystack_expr\n"
2648 "Which is: \"two needles\"",
2649 IsNotSubstring(
2650 "needle_expr", "haystack_expr",
2651 ::std::string("needle"), "two needles").failure_message());
2652}
2653
2654#if GTEST_HAS_STD_WSTRING
2655
2656// Tests that IsNotSubstring returns the correct result when the input
2657// argument type is ::std::wstring.
2658TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2659 EXPECT_FALSE(
2660 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2661 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2662}
2663
2664#endif // GTEST_HAS_STD_WSTRING
2665
2666// Tests floating-point assertions.
2667
2668template <typename RawType>
2669class FloatingPointTest : public Test {
2670 protected:
2671 // Pre-calculated numbers to be used by the tests.
2672 struct TestValues {
2673 RawType close_to_positive_zero;
2674 RawType close_to_negative_zero;
2675 RawType further_from_negative_zero;
2676
2677 RawType close_to_one;
2678 RawType further_from_one;
2679
2680 RawType infinity;
2681 RawType close_to_infinity;
2682 RawType further_from_infinity;
2683
2684 RawType nan1;
2685 RawType nan2;
2686 };
2687
2688 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2689 typedef typename Floating::Bits Bits;
2690
2691 virtual void SetUp() {
2692 const size_t max_ulps = Floating::kMaxUlps;
2693
2694 // The bits that represent 0.0.
2695 const Bits zero_bits = Floating(0).bits();
2696
2697 // Makes some numbers close to 0.0.
2698 values_.close_to_positive_zero = Floating::ReinterpretBits(
2699 zero_bits + max_ulps/2);
2700 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2701 zero_bits + max_ulps - max_ulps/2);
2702 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2703 zero_bits + max_ulps + 1 - max_ulps/2);
2704
2705 // The bits that represent 1.0.
2706 const Bits one_bits = Floating(1).bits();
2707
2708 // Makes some numbers close to 1.0.
2709 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2710 values_.further_from_one = Floating::ReinterpretBits(
2711 one_bits + max_ulps + 1);
2712
2713 // +infinity.
2714 values_.infinity = Floating::Infinity();
2715
2716 // The bits that represent +infinity.
2717 const Bits infinity_bits = Floating(values_.infinity).bits();
2718
2719 // Makes some numbers close to infinity.
2720 values_.close_to_infinity = Floating::ReinterpretBits(
2721 infinity_bits - max_ulps);
2722 values_.further_from_infinity = Floating::ReinterpretBits(
2723 infinity_bits - max_ulps - 1);
2724
2725 // Makes some NAN's. Sets the most significant bit of the fraction so that
2726 // our NaN's are quiet; trying to process a signaling NaN would raise an
2727 // exception if our environment enables floating point exceptions.
2728 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2729 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2730 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2731 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2732 }
2733
2734 void TestSize() {
2735 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2736 }
2737
2738 static TestValues values_;
2739};
2740
2741template <typename RawType>
2742typename FloatingPointTest<RawType>::TestValues
2743 FloatingPointTest<RawType>::values_;
2744
2745// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2746typedef FloatingPointTest<float> FloatTest;
2747
2748// Tests that the size of Float::Bits matches the size of float.
2749TEST_F(FloatTest, Size) {
2750 TestSize();
2751}
2752
2753// Tests comparing with +0 and -0.
2754TEST_F(FloatTest, Zeros) {
2755 EXPECT_FLOAT_EQ(0.0, -0.0);
2756 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2757 "1.0");
2758 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2759 "1.5");
2760}
2761
2762// Tests comparing numbers close to 0.
2763//
2764// This ensures that *_FLOAT_EQ handles the sign correctly and no
2765// overflow occurs when comparing numbers whose absolute value is very
2766// small.
2767TEST_F(FloatTest, AlmostZeros) {
2768 // In C++Builder, names within local classes (such as used by
2769 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2770 // scoping class. Use a static local alias as a workaround.
2771 // We use the assignment syntax since some compilers, like Sun Studio,
2772 // don't allow initializing references using construction syntax
2773 // (parentheses).
2774 static const FloatTest::TestValues& v = this->values_;
2775
2776 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2777 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2778 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2779
2780 EXPECT_FATAL_FAILURE({ // NOLINT
2781 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2782 v.further_from_negative_zero);
2783 }, "v.further_from_negative_zero");
2784}
2785
2786// Tests comparing numbers close to each other.
2787TEST_F(FloatTest, SmallDiff) {
2788 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2789 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2790 "values_.further_from_one");
2791}
2792
2793// Tests comparing numbers far apart.
2794TEST_F(FloatTest, LargeDiff) {
2795 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2796 "3.0");
2797}
2798
2799// Tests comparing with infinity.
2800//
2801// This ensures that no overflow occurs when comparing numbers whose
2802// absolute value is very large.
2803TEST_F(FloatTest, Infinity) {
2804 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2805 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2806#if !GTEST_OS_SYMBIAN
2807 // Nokia's STLport crashes if we try to output infinity or NaN.
2808 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2809 "-values_.infinity");
2810
2811 // This is interesting as the representations of infinity and nan1
2812 // are only 1 DLP apart.
2813 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2814 "values_.nan1");
2815#endif // !GTEST_OS_SYMBIAN
2816}
2817
2818// Tests that comparing with NAN always returns false.
2819TEST_F(FloatTest, NaN) {
2820#if !GTEST_OS_SYMBIAN
2821// Nokia's STLport crashes if we try to output infinity or NaN.
2822
2823 // In C++Builder, names within local classes (such as used by
2824 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2825 // scoping class. Use a static local alias as a workaround.
2826 // We use the assignment syntax since some compilers, like Sun Studio,
2827 // don't allow initializing references using construction syntax
2828 // (parentheses).
2829 static const FloatTest::TestValues& v = this->values_;
2830
2831 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2832 "v.nan1");
2833 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2834 "v.nan2");
2835 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2836 "v.nan1");
2837
2838 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2839 "v.infinity");
2840#endif // !GTEST_OS_SYMBIAN
2841}
2842
2843// Tests that *_FLOAT_EQ are reflexive.
2844TEST_F(FloatTest, Reflexive) {
2845 EXPECT_FLOAT_EQ(0.0, 0.0);
2846 EXPECT_FLOAT_EQ(1.0, 1.0);
2847 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2848}
2849
2850// Tests that *_FLOAT_EQ are commutative.
2851TEST_F(FloatTest, Commutative) {
2852 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2853 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2854
2855 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2856 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2857 "1.0");
2858}
2859
2860// Tests EXPECT_NEAR.
2861TEST_F(FloatTest, EXPECT_NEAR) {
2862 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2863 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2864 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2865 "The difference between 1.0f and 1.5f is 0.5, "
2866 "which exceeds 0.25f");
2867 // To work around a bug in gcc 2.95.0, there is intentionally no
2868 // space after the first comma in the previous line.
2869}
2870
2871// Tests ASSERT_NEAR.
2872TEST_F(FloatTest, ASSERT_NEAR) {
2873 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2874 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2875 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2876 "The difference between 1.0f and 1.5f is 0.5, "
2877 "which exceeds 0.25f");
2878 // To work around a bug in gcc 2.95.0, there is intentionally no
2879 // space after the first comma in the previous line.
2880}
2881
2882// Tests the cases where FloatLE() should succeed.
2883TEST_F(FloatTest, FloatLESucceeds) {
2884 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2885 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2886
2887 // or when val1 is greater than, but almost equals to, val2.
2888 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2889}
2890
2891// Tests the cases where FloatLE() should fail.
2892TEST_F(FloatTest, FloatLEFails) {
2893 // When val1 is greater than val2 by a large margin,
2894 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2895 "(2.0f) <= (1.0f)");
2896
2897 // or by a small yet non-negligible margin,
2898 EXPECT_NONFATAL_FAILURE({ // NOLINT
2899 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2900 }, "(values_.further_from_one) <= (1.0f)");
2901
2902#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2903 // Nokia's STLport crashes if we try to output infinity or NaN.
2904 // C++Builder gives bad results for ordered comparisons involving NaNs
2905 // due to compiler bugs.
2906 EXPECT_NONFATAL_FAILURE({ // NOLINT
2907 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2908 }, "(values_.nan1) <= (values_.infinity)");
2909 EXPECT_NONFATAL_FAILURE({ // NOLINT
2910 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2911 }, "(-values_.infinity) <= (values_.nan1)");
2912 EXPECT_FATAL_FAILURE({ // NOLINT
2913 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2914 }, "(values_.nan1) <= (values_.nan1)");
2915#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2916}
2917
2918// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2919typedef FloatingPointTest<double> DoubleTest;
2920
2921// Tests that the size of Double::Bits matches the size of double.
2922TEST_F(DoubleTest, Size) {
2923 TestSize();
2924}
2925
2926// Tests comparing with +0 and -0.
2927TEST_F(DoubleTest, Zeros) {
2928 EXPECT_DOUBLE_EQ(0.0, -0.0);
2929 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2930 "1.0");
2931 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2932 "1.0");
2933}
2934
2935// Tests comparing numbers close to 0.
2936//
2937// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2938// overflow occurs when comparing numbers whose absolute value is very
2939// small.
2940TEST_F(DoubleTest, AlmostZeros) {
2941 // In C++Builder, names within local classes (such as used by
2942 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2943 // scoping class. Use a static local alias as a workaround.
2944 // We use the assignment syntax since some compilers, like Sun Studio,
2945 // don't allow initializing references using construction syntax
2946 // (parentheses).
2947 static const DoubleTest::TestValues& v = this->values_;
2948
2949 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2950 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2951 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2952
2953 EXPECT_FATAL_FAILURE({ // NOLINT
2954 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2955 v.further_from_negative_zero);
2956 }, "v.further_from_negative_zero");
2957}
2958
2959// Tests comparing numbers close to each other.
2960TEST_F(DoubleTest, SmallDiff) {
2961 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2962 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2963 "values_.further_from_one");
2964}
2965
2966// Tests comparing numbers far apart.
2967TEST_F(DoubleTest, LargeDiff) {
2968 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2969 "3.0");
2970}
2971
2972// Tests comparing with infinity.
2973//
2974// This ensures that no overflow occurs when comparing numbers whose
2975// absolute value is very large.
2976TEST_F(DoubleTest, Infinity) {
2977 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2978 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
2979#if !GTEST_OS_SYMBIAN
2980 // Nokia's STLport crashes if we try to output infinity or NaN.
2981 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2982 "-values_.infinity");
2983
2984 // This is interesting as the representations of infinity_ and nan1_
2985 // are only 1 DLP apart.
2986 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2987 "values_.nan1");
2988#endif // !GTEST_OS_SYMBIAN
2989}
2990
2991// Tests that comparing with NAN always returns false.
2992TEST_F(DoubleTest, NaN) {
2993#if !GTEST_OS_SYMBIAN
2994 // In C++Builder, names within local classes (such as used by
2995 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2996 // scoping class. Use a static local alias as a workaround.
2997 // We use the assignment syntax since some compilers, like Sun Studio,
2998 // don't allow initializing references using construction syntax
2999 // (parentheses).
3000 static const DoubleTest::TestValues& v = this->values_;
3001
3002 // Nokia's STLport crashes if we try to output infinity or NaN.
3003 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3004 "v.nan1");
3005 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3006 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3007 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3008 "v.infinity");
3009#endif // !GTEST_OS_SYMBIAN
3010}
3011
3012// Tests that *_DOUBLE_EQ are reflexive.
3013TEST_F(DoubleTest, Reflexive) {
3014 EXPECT_DOUBLE_EQ(0.0, 0.0);
3015 EXPECT_DOUBLE_EQ(1.0, 1.0);
3016#if !GTEST_OS_SYMBIAN
3017 // Nokia's STLport crashes if we try to output infinity or NaN.
3018 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3019#endif // !GTEST_OS_SYMBIAN
3020}
3021
3022// Tests that *_DOUBLE_EQ are commutative.
3023TEST_F(DoubleTest, Commutative) {
3024 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3025 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3026
3027 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3028 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3029 "1.0");
3030}
3031
3032// Tests EXPECT_NEAR.
3033TEST_F(DoubleTest, EXPECT_NEAR) {
3034 EXPECT_NEAR(-1.0, -1.1, 0.2);
3035 EXPECT_NEAR(2.0, 3.0, 1.0);
3036 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3037 "The difference between 1.0 and 1.5 is 0.5, "
3038 "which exceeds 0.25");
3039 // To work around a bug in gcc 2.95.0, there is intentionally no
3040 // space after the first comma in the previous statement.
3041}
3042
3043// Tests ASSERT_NEAR.
3044TEST_F(DoubleTest, ASSERT_NEAR) {
3045 ASSERT_NEAR(-1.0, -1.1, 0.2);
3046 ASSERT_NEAR(2.0, 3.0, 1.0);
3047 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3048 "The difference between 1.0 and 1.5 is 0.5, "
3049 "which exceeds 0.25");
3050 // To work around a bug in gcc 2.95.0, there is intentionally no
3051 // space after the first comma in the previous statement.
3052}
3053
3054// Tests the cases where DoubleLE() should succeed.
3055TEST_F(DoubleTest, DoubleLESucceeds) {
3056 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3057 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3058
3059 // or when val1 is greater than, but almost equals to, val2.
3060 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3061}
3062
3063// Tests the cases where DoubleLE() should fail.
3064TEST_F(DoubleTest, DoubleLEFails) {
3065 // When val1 is greater than val2 by a large margin,
3066 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3067 "(2.0) <= (1.0)");
3068
3069 // or by a small yet non-negligible margin,
3070 EXPECT_NONFATAL_FAILURE({ // NOLINT
3071 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3072 }, "(values_.further_from_one) <= (1.0)");
3073
3074#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3075 // Nokia's STLport crashes if we try to output infinity or NaN.
3076 // C++Builder gives bad results for ordered comparisons involving NaNs
3077 // due to compiler bugs.
3078 EXPECT_NONFATAL_FAILURE({ // NOLINT
3079 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3080 }, "(values_.nan1) <= (values_.infinity)");
3081 EXPECT_NONFATAL_FAILURE({ // NOLINT
3082 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3083 }, " (-values_.infinity) <= (values_.nan1)");
3084 EXPECT_FATAL_FAILURE({ // NOLINT
3085 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3086 }, "(values_.nan1) <= (values_.nan1)");
3087#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3088}
3089
3090
3091// Verifies that a test or test case whose name starts with DISABLED_ is
3092// not run.
3093
3094// A test whose name starts with DISABLED_.
3095// Should not run.
3096TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3097 FAIL() << "Unexpected failure: Disabled test should not be run.";
3098}
3099
3100// A test whose name does not start with DISABLED_.
3101// Should run.
3102TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3103 EXPECT_EQ(1, 1);
3104}
3105
3106// A test case whose name starts with DISABLED_.
3107// Should not run.
3108TEST(DISABLED_TestCase, TestShouldNotRun) {
3109 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3110}
3111
3112// A test case and test whose names start with DISABLED_.
3113// Should not run.
3114TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3115 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3116}
3117
3118// Check that when all tests in a test case are disabled, SetupTestCase() and
3119// TearDownTestCase() are not called.
3120class DisabledTestsTest : public Test {
3121 protected:
3122 static void SetUpTestCase() {
3123 FAIL() << "Unexpected failure: All tests disabled in test case. "
3124 "SetupTestCase() should not be called.";
3125 }
3126
3127 static void TearDownTestCase() {
3128 FAIL() << "Unexpected failure: All tests disabled in test case. "
3129 "TearDownTestCase() should not be called.";
3130 }
3131};
3132
3133TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3134 FAIL() << "Unexpected failure: Disabled test should not be run.";
3135}
3136
3137TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3138 FAIL() << "Unexpected failure: Disabled test should not be run.";
3139}
3140
3141// Tests that disabled typed tests aren't run.
3142
3143#if GTEST_HAS_TYPED_TEST
3144
3145template <typename T>
3146class TypedTest : public Test {
3147};
3148
3149typedef testing::Types<int, double> NumericTypes;
3150TYPED_TEST_CASE(TypedTest, NumericTypes);
3151
3152TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3153 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3154}
3155
3156template <typename T>
3157class DISABLED_TypedTest : public Test {
3158};
3159
3160TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3161
3162TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3163 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3164}
3165
3166#endif // GTEST_HAS_TYPED_TEST
3167
3168// Tests that disabled type-parameterized tests aren't run.
3169
3170#if GTEST_HAS_TYPED_TEST_P
3171
3172template <typename T>
3173class TypedTestP : public Test {
3174};
3175
3176TYPED_TEST_CASE_P(TypedTestP);
3177
3178TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3179 FAIL() << "Unexpected failure: "
3180 << "Disabled type-parameterized test should not run.";
3181}
3182
3183REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3184
3185INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3186
3187template <typename T>
3188class DISABLED_TypedTestP : public Test {
3189};
3190
3191TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3192
3193TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3194 FAIL() << "Unexpected failure: "
3195 << "Disabled type-parameterized test should not run.";
3196}
3197
3198REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3199
3200INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3201
3202#endif // GTEST_HAS_TYPED_TEST_P
3203
3204// Tests that assertion macros evaluate their arguments exactly once.
3205
3206class SingleEvaluationTest : public Test {
3207 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3208 // This helper function is needed by the FailedASSERT_STREQ test
3209 // below. It's public to work around C++Builder's bug with scoping local
3210 // classes.
3211 static void CompareAndIncrementCharPtrs() {
3212 ASSERT_STREQ(p1_++, p2_++);
3213 }
3214
3215 // This helper function is needed by the FailedASSERT_NE test below. It's
3216 // public to work around C++Builder's bug with scoping local classes.
3217 static void CompareAndIncrementInts() {
3218 ASSERT_NE(a_++, b_++);
3219 }
3220
3221 protected:
3222 SingleEvaluationTest() {
3223 p1_ = s1_;
3224 p2_ = s2_;
3225 a_ = 0;
3226 b_ = 0;
3227 }
3228
3229 static const char* const s1_;
3230 static const char* const s2_;
3231 static const char* p1_;
3232 static const char* p2_;
3233
3234 static int a_;
3235 static int b_;
3236};
3237
3238const char* const SingleEvaluationTest::s1_ = "01234";
3239const char* const SingleEvaluationTest::s2_ = "abcde";
3240const char* SingleEvaluationTest::p1_;
3241const char* SingleEvaluationTest::p2_;
3242int SingleEvaluationTest::a_;
3243int SingleEvaluationTest::b_;
3244
3245// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3246// exactly once.
3247TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3248 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3249 "p2_++");
3250 EXPECT_EQ(s1_ + 1, p1_);
3251 EXPECT_EQ(s2_ + 1, p2_);
3252}
3253
3254// Tests that string assertion arguments are evaluated exactly once.
3255TEST_F(SingleEvaluationTest, ASSERT_STR) {
3256 // successful EXPECT_STRNE
3257 EXPECT_STRNE(p1_++, p2_++);
3258 EXPECT_EQ(s1_ + 1, p1_);
3259 EXPECT_EQ(s2_ + 1, p2_);
3260
3261 // failed EXPECT_STRCASEEQ
3262 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3263 "Ignoring case");
3264 EXPECT_EQ(s1_ + 2, p1_);
3265 EXPECT_EQ(s2_ + 2, p2_);
3266}
3267
3268// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3269// once.
3270TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3271 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3272 "(a_++) != (b_++)");
3273 EXPECT_EQ(1, a_);
3274 EXPECT_EQ(1, b_);
3275}
3276
3277// Tests that assertion arguments are evaluated exactly once.
3278TEST_F(SingleEvaluationTest, OtherCases) {
3279 // successful EXPECT_TRUE
3280 EXPECT_TRUE(0 == a_++); // NOLINT
3281 EXPECT_EQ(1, a_);
3282
3283 // failed EXPECT_TRUE
3284 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3285 EXPECT_EQ(2, a_);
3286
3287 // successful EXPECT_GT
3288 EXPECT_GT(a_++, b_++);
3289 EXPECT_EQ(3, a_);
3290 EXPECT_EQ(1, b_);
3291
3292 // failed EXPECT_LT
3293 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3294 EXPECT_EQ(4, a_);
3295 EXPECT_EQ(2, b_);
3296
3297 // successful ASSERT_TRUE
3298 ASSERT_TRUE(0 < a_++); // NOLINT
3299 EXPECT_EQ(5, a_);
3300
3301 // successful ASSERT_GT
3302 ASSERT_GT(a_++, b_++);
3303 EXPECT_EQ(6, a_);
3304 EXPECT_EQ(3, b_);
3305}
3306
3307#if GTEST_HAS_EXCEPTIONS
3308
3309void ThrowAnInteger() {
3310 throw 1;
3311}
3312
3313// Tests that assertion arguments are evaluated exactly once.
3314TEST_F(SingleEvaluationTest, ExceptionTests) {
3315 // successful EXPECT_THROW
3316 EXPECT_THROW({ // NOLINT
3317 a_++;
3318 ThrowAnInteger();
3319 }, int);
3320 EXPECT_EQ(1, a_);
3321
3322 // failed EXPECT_THROW, throws different
3323 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3324 a_++;
3325 ThrowAnInteger();
3326 }, bool), "throws a different type");
3327 EXPECT_EQ(2, a_);
3328
3329 // failed EXPECT_THROW, throws nothing
3330 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3331 EXPECT_EQ(3, a_);
3332
3333 // successful EXPECT_NO_THROW
3334 EXPECT_NO_THROW(a_++);
3335 EXPECT_EQ(4, a_);
3336
3337 // failed EXPECT_NO_THROW
3338 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3339 a_++;
3340 ThrowAnInteger();
3341 }), "it throws");
3342 EXPECT_EQ(5, a_);
3343
3344 // successful EXPECT_ANY_THROW
3345 EXPECT_ANY_THROW({ // NOLINT
3346 a_++;
3347 ThrowAnInteger();
3348 });
3349 EXPECT_EQ(6, a_);
3350
3351 // failed EXPECT_ANY_THROW
3352 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3353 EXPECT_EQ(7, a_);
3354}
3355
3356#endif // GTEST_HAS_EXCEPTIONS
3357
3358// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3359class NoFatalFailureTest : public Test {
3360 protected:
3361 void Succeeds() {}
3362 void FailsNonFatal() {
3363 ADD_FAILURE() << "some non-fatal failure";
3364 }
3365 void Fails() {
3366 FAIL() << "some fatal failure";
3367 }
3368
3369 void DoAssertNoFatalFailureOnFails() {
3370 ASSERT_NO_FATAL_FAILURE(Fails());
3371 ADD_FAILURE() << "shold not reach here.";
3372 }
3373
3374 void DoExpectNoFatalFailureOnFails() {
3375 EXPECT_NO_FATAL_FAILURE(Fails());
3376 ADD_FAILURE() << "other failure";
3377 }
3378};
3379
3380TEST_F(NoFatalFailureTest, NoFailure) {
3381 EXPECT_NO_FATAL_FAILURE(Succeeds());
3382 ASSERT_NO_FATAL_FAILURE(Succeeds());
3383}
3384
3385TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3386 EXPECT_NONFATAL_FAILURE(
3387 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3388 "some non-fatal failure");
3389 EXPECT_NONFATAL_FAILURE(
3390 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3391 "some non-fatal failure");
3392}
3393
3394TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3395 TestPartResultArray gtest_failures;
3396 {
3397 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3398 DoAssertNoFatalFailureOnFails();
3399 }
3400 ASSERT_EQ(2, gtest_failures.size());
3401 EXPECT_EQ(TestPartResult::kFatalFailure,
3402 gtest_failures.GetTestPartResult(0).type());
3403 EXPECT_EQ(TestPartResult::kFatalFailure,
3404 gtest_failures.GetTestPartResult(1).type());
3405 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3406 gtest_failures.GetTestPartResult(0).message());
3407 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3408 gtest_failures.GetTestPartResult(1).message());
3409}
3410
3411TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3412 TestPartResultArray gtest_failures;
3413 {
3414 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3415 DoExpectNoFatalFailureOnFails();
3416 }
3417 ASSERT_EQ(3, gtest_failures.size());
3418 EXPECT_EQ(TestPartResult::kFatalFailure,
3419 gtest_failures.GetTestPartResult(0).type());
3420 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3421 gtest_failures.GetTestPartResult(1).type());
3422 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3423 gtest_failures.GetTestPartResult(2).type());
3424 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3425 gtest_failures.GetTestPartResult(0).message());
3426 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3427 gtest_failures.GetTestPartResult(1).message());
3428 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3429 gtest_failures.GetTestPartResult(2).message());
3430}
3431
3432TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3433 TestPartResultArray gtest_failures;
3434 {
3435 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3436 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3437 }
3438 ASSERT_EQ(2, gtest_failures.size());
3439 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3440 gtest_failures.GetTestPartResult(0).type());
3441 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3442 gtest_failures.GetTestPartResult(1).type());
3443 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3444 gtest_failures.GetTestPartResult(0).message());
3445 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3446 gtest_failures.GetTestPartResult(1).message());
3447}
3448
3449// Tests non-string assertions.
3450
3451std::string EditsToString(const std::vector<EditType>& edits) {
3452 std::string out;
3453 for (size_t i = 0; i < edits.size(); ++i) {
3454 static const char kEdits[] = " +-/";
3455 out.append(1, kEdits[edits[i]]);
3456 }
3457 return out;
3458}
3459
3460std::vector<size_t> CharsToIndices(const std::string& str) {
3461 std::vector<size_t> out;
3462 for (size_t i = 0; i < str.size(); ++i) {
3463 out.push_back(str[i]);
3464 }
3465 return out;
3466}
3467
3468std::vector<std::string> CharsToLines(const std::string& str) {
3469 std::vector<std::string> out;
3470 for (size_t i = 0; i < str.size(); ++i) {
3471 out.push_back(str.substr(i, 1));
3472 }
3473 return out;
3474}
3475
3476TEST(EditDistance, TestCases) {
3477 struct Case {
3478 int line;
3479 const char* left;
3480 const char* right;
3481 const char* expected_edits;
3482 const char* expected_diff;
3483 };
3484 static const Case kCases[] = {
3485 // No change.
3486 {__LINE__, "A", "A", " ", ""},
3487 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3488 // Simple adds.
3489 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3490 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3491 // Simple removes.
3492 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3493 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3494 // Simple replaces.
3495 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3496 {__LINE__, "ABCD", "abcd", "////",
3497 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3498 // Path finding.
3499 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3500 "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
3501 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3502 "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
3503 {__LINE__, "ABCDE", "BCDCD", "- +/",
3504 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3505 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3506 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3507 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3508 {}};
3509 for (const Case* c = kCases; c->left; ++c) {
3510 EXPECT_TRUE(c->expected_edits ==
3511 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3512 CharsToIndices(c->right))))
3513 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3514 << EditsToString(CalculateOptimalEdits(
3515 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3516 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3517 CharsToLines(c->right)))
3518 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3519 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3520 << ">";
3521 }
3522}
3523
3524// Tests EqFailure(), used for implementing *EQ* assertions.
3525TEST(AssertionTest, EqFailure) {
3526 const std::string foo_val("5"), bar_val("6");
3527 const std::string msg1(
3528 EqFailure("foo", "bar", foo_val, bar_val, false)
3529 .failure_message());
3530 EXPECT_STREQ(
3531 " Expected: foo\n"
3532 " Which is: 5\n"
3533 "To be equal to: bar\n"
3534 " Which is: 6",
3535 msg1.c_str());
3536
3537 const std::string msg2(
3538 EqFailure("foo", "6", foo_val, bar_val, false)
3539 .failure_message());
3540 EXPECT_STREQ(
3541 " Expected: foo\n"
3542 " Which is: 5\n"
3543 "To be equal to: 6",
3544 msg2.c_str());
3545
3546 const std::string msg3(
3547 EqFailure("5", "bar", foo_val, bar_val, false)
3548 .failure_message());
3549 EXPECT_STREQ(
3550 " Expected: 5\n"
3551 "To be equal to: bar\n"
3552 " Which is: 6",
3553 msg3.c_str());
3554
3555 const std::string msg4(
3556 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3557 EXPECT_STREQ(
3558 " Expected: 5\n"
3559 "To be equal to: 6",
3560 msg4.c_str());
3561
3562 const std::string msg5(
3563 EqFailure("foo", "bar",
3564 std::string("\"x\""), std::string("\"y\""),
3565 true).failure_message());
3566 EXPECT_STREQ(
3567 " Expected: foo\n"
3568 " Which is: \"x\"\n"
3569 "To be equal to: bar\n"
3570 " Which is: \"y\"\n"
3571 "Ignoring case",
3572 msg5.c_str());
3573}
3574
3575TEST(AssertionTest, EqFailureWithDiff) {
3576 const std::string left(
3577 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3578 const std::string right(
3579 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3580 const std::string msg1(
3581 EqFailure("left", "right", left, right, false).failure_message());
3582 EXPECT_STREQ(
3583 " Expected: left\n"
3584 " Which is: "
3585 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3586 "To be equal to: right\n"
3587 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3588 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3589 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3590 msg1.c_str());
3591}
3592
3593// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3594TEST(AssertionTest, AppendUserMessage) {
3595 const std::string foo("foo");
3596
3597 Message msg;
3598 EXPECT_STREQ("foo",
3599 AppendUserMessage(foo, msg).c_str());
3600
3601 msg << "bar";
3602 EXPECT_STREQ("foo\nbar",
3603 AppendUserMessage(foo, msg).c_str());
3604}
3605
3606#ifdef __BORLANDC__
3607// Silences warnings: "Condition is always true", "Unreachable code"
3608# pragma option push -w-ccc -w-rch
3609#endif
3610
3611// Tests ASSERT_TRUE.
3612TEST(AssertionTest, ASSERT_TRUE) {
3613 ASSERT_TRUE(2 > 1); // NOLINT
3614 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3615 "2 < 1");
3616}
3617
3618// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3619TEST(AssertionTest, AssertTrueWithAssertionResult) {
3620 ASSERT_TRUE(ResultIsEven(2));
3621#ifndef __BORLANDC__
3622 // ICE's in C++Builder.
3623 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3624 "Value of: ResultIsEven(3)\n"
3625 " Actual: false (3 is odd)\n"
3626 "Expected: true");
3627#endif
3628 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3629 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3630 "Value of: ResultIsEvenNoExplanation(3)\n"
3631 " Actual: false (3 is odd)\n"
3632 "Expected: true");
3633}
3634
3635// Tests ASSERT_FALSE.
3636TEST(AssertionTest, ASSERT_FALSE) {
3637 ASSERT_FALSE(2 < 1); // NOLINT
3638 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3639 "Value of: 2 > 1\n"
3640 " Actual: true\n"
3641 "Expected: false");
3642}
3643
3644// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3645TEST(AssertionTest, AssertFalseWithAssertionResult) {
3646 ASSERT_FALSE(ResultIsEven(3));
3647#ifndef __BORLANDC__
3648 // ICE's in C++Builder.
3649 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3650 "Value of: ResultIsEven(2)\n"
3651 " Actual: true (2 is even)\n"
3652 "Expected: false");
3653#endif
3654 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3655 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3656 "Value of: ResultIsEvenNoExplanation(2)\n"
3657 " Actual: true\n"
3658 "Expected: false");
3659}
3660
3661#ifdef __BORLANDC__
3662// Restores warnings after previous "#pragma option push" supressed them
3663# pragma option pop
3664#endif
3665
3666// Tests using ASSERT_EQ on double values. The purpose is to make
3667// sure that the specialization we did for integer and anonymous enums
3668// isn't used for double arguments.
3669TEST(ExpectTest, ASSERT_EQ_Double) {
3670 // A success.
3671 ASSERT_EQ(5.6, 5.6);
3672
3673 // A failure.
3674 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3675 "5.1");
3676}
3677
3678// Tests ASSERT_EQ.
3679TEST(AssertionTest, ASSERT_EQ) {
3680 ASSERT_EQ(5, 2 + 3);
3681 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3682 " Expected: 5\n"
3683 "To be equal to: 2*3\n"
3684 " Which is: 6");
3685}
3686
3687// Tests ASSERT_EQ(NULL, pointer).
3688#if GTEST_CAN_COMPARE_NULL
3689TEST(AssertionTest, ASSERT_EQ_NULL) {
3690 // A success.
3691 const char* p = NULL;
3692 // Some older GCC versions may issue a spurious waring in this or the next
3693 // assertion statement. This warning should not be suppressed with
3694 // static_cast since the test verifies the ability to use bare NULL as the
3695 // expected parameter to the macro.
3696 ASSERT_EQ(NULL, p);
3697
3698 // A failure.
3699 static int n = 0;
3700 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3701 "To be equal to: &n\n");
3702}
3703#endif // GTEST_CAN_COMPARE_NULL
3704
3705// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3706// treated as a null pointer by the compiler, we need to make sure
3707// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3708// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3709TEST(ExpectTest, ASSERT_EQ_0) {
3710 int n = 0;
3711
3712 // A success.
3713 ASSERT_EQ(0, n);
3714
3715 // A failure.
3716 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3717 "Expected: 0");
3718}
3719
3720// Tests ASSERT_NE.
3721TEST(AssertionTest, ASSERT_NE) {
3722 ASSERT_NE(6, 7);
3723 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3724 "Expected: ('a') != ('a'), "
3725 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3726}
3727
3728// Tests ASSERT_LE.
3729TEST(AssertionTest, ASSERT_LE) {
3730 ASSERT_LE(2, 3);
3731 ASSERT_LE(2, 2);
3732 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3733 "Expected: (2) <= (0), actual: 2 vs 0");
3734}
3735
3736// Tests ASSERT_LT.
3737TEST(AssertionTest, ASSERT_LT) {
3738 ASSERT_LT(2, 3);
3739 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3740 "Expected: (2) < (2), actual: 2 vs 2");
3741}
3742
3743// Tests ASSERT_GE.
3744TEST(AssertionTest, ASSERT_GE) {
3745 ASSERT_GE(2, 1);
3746 ASSERT_GE(2, 2);
3747 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3748 "Expected: (2) >= (3), actual: 2 vs 3");
3749}
3750
3751// Tests ASSERT_GT.
3752TEST(AssertionTest, ASSERT_GT) {
3753 ASSERT_GT(2, 1);
3754 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3755 "Expected: (2) > (2), actual: 2 vs 2");
3756}
3757
3758#if GTEST_HAS_EXCEPTIONS
3759
3760void ThrowNothing() {}
3761
3762// Tests ASSERT_THROW.
3763TEST(AssertionTest, ASSERT_THROW) {
3764 ASSERT_THROW(ThrowAnInteger(), int);
3765
3766# ifndef __BORLANDC__
3767
3768 // ICE's in C++Builder 2007 and 2009.
3769 EXPECT_FATAL_FAILURE(
3770 ASSERT_THROW(ThrowAnInteger(), bool),
3771 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3772 " Actual: it throws a different type.");
3773# endif
3774
3775 EXPECT_FATAL_FAILURE(
3776 ASSERT_THROW(ThrowNothing(), bool),
3777 "Expected: ThrowNothing() throws an exception of type bool.\n"
3778 " Actual: it throws nothing.");
3779}
3780
3781// Tests ASSERT_NO_THROW.
3782TEST(AssertionTest, ASSERT_NO_THROW) {
3783 ASSERT_NO_THROW(ThrowNothing());
3784 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3785 "Expected: ThrowAnInteger() doesn't throw an exception."
3786 "\n Actual: it throws.");
3787}
3788
3789// Tests ASSERT_ANY_THROW.
3790TEST(AssertionTest, ASSERT_ANY_THROW) {
3791 ASSERT_ANY_THROW(ThrowAnInteger());
3792 EXPECT_FATAL_FAILURE(
3793 ASSERT_ANY_THROW(ThrowNothing()),
3794 "Expected: ThrowNothing() throws an exception.\n"
3795 " Actual: it doesn't.");
3796}
3797
3798#endif // GTEST_HAS_EXCEPTIONS
3799
3800// Makes sure we deal with the precedence of <<. This test should
3801// compile.
3802TEST(AssertionTest, AssertPrecedence) {
3803 ASSERT_EQ(1 < 2, true);
3804 bool false_value = false;
3805 ASSERT_EQ(true && false_value, false);
3806}
3807
3808// A subroutine used by the following test.
3809void TestEq1(int x) {
3810 ASSERT_EQ(1, x);
3811}
3812
3813// Tests calling a test subroutine that's not part of a fixture.
3814TEST(AssertionTest, NonFixtureSubroutine) {
3815 EXPECT_FATAL_FAILURE(TestEq1(2),
3816 "To be equal to: x");
3817}
3818
3819// An uncopyable class.
3820class Uncopyable {
3821 public:
3822 explicit Uncopyable(int a_value) : value_(a_value) {}
3823
3824 int value() const { return value_; }
3825 bool operator==(const Uncopyable& rhs) const {
3826 return value() == rhs.value();
3827 }
3828 private:
3829 // This constructor deliberately has no implementation, as we don't
3830 // want this class to be copyable.
3831 Uncopyable(const Uncopyable&); // NOLINT
3832
3833 int value_;
3834};
3835
3836::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3837 return os << value.value();
3838}
3839
3840
3841bool IsPositiveUncopyable(const Uncopyable& x) {
3842 return x.value() > 0;
3843}
3844
3845// A subroutine used by the following test.
3846void TestAssertNonPositive() {
3847 Uncopyable y(-1);
3848 ASSERT_PRED1(IsPositiveUncopyable, y);
3849}
3850// A subroutine used by the following test.
3851void TestAssertEqualsUncopyable() {
3852 Uncopyable x(5);
3853 Uncopyable y(-1);
3854 ASSERT_EQ(x, y);
3855}
3856
3857// Tests that uncopyable objects can be used in assertions.
3858TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3859 Uncopyable x(5);
3860 ASSERT_PRED1(IsPositiveUncopyable, x);
3861 ASSERT_EQ(x, x);
3862 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3863 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3864 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3865 "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
3866}
3867
3868// Tests that uncopyable objects can be used in expects.
3869TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3870 Uncopyable x(5);
3871 EXPECT_PRED1(IsPositiveUncopyable, x);
3872 Uncopyable y(-1);
3873 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3874 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3875 EXPECT_EQ(x, x);
3876 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3877 "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
3878}
3879
3880enum NamedEnum {
3881 kE1 = 0,
3882 kE2 = 1
3883};
3884
3885TEST(AssertionTest, NamedEnum) {
3886 EXPECT_EQ(kE1, kE1);
3887 EXPECT_LT(kE1, kE2);
3888 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3889 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3890}
3891
3892// The version of gcc used in XCode 2.2 has a bug and doesn't allow
3893// anonymous enums in assertions. Therefore the following test is not
3894// done on Mac.
3895// Sun Studio and HP aCC also reject this code.
3896#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3897
3898// Tests using assertions with anonymous enums.
3899enum {
3900 kCaseA = -1,
3901
3902# if GTEST_OS_LINUX
3903
3904 // We want to test the case where the size of the anonymous enum is
3905 // larger than sizeof(int), to make sure our implementation of the
3906 // assertions doesn't truncate the enums. However, MSVC
3907 // (incorrectly) doesn't allow an enum value to exceed the range of
3908 // an int, so this has to be conditionally compiled.
3909 //
3910 // On Linux, kCaseB and kCaseA have the same value when truncated to
3911 // int size. We want to test whether this will confuse the
3912 // assertions.
3913 kCaseB = testing::internal::kMaxBiggestInt,
3914
3915# else
3916
3917 kCaseB = INT_MAX,
3918
3919# endif // GTEST_OS_LINUX
3920
3921 kCaseC = 42
3922};
3923
3924TEST(AssertionTest, AnonymousEnum) {
3925# if GTEST_OS_LINUX
3926
3927 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3928
3929# endif // GTEST_OS_LINUX
3930
3931 EXPECT_EQ(kCaseA, kCaseA);
3932 EXPECT_NE(kCaseA, kCaseB);
3933 EXPECT_LT(kCaseA, kCaseB);
3934 EXPECT_LE(kCaseA, kCaseB);
3935 EXPECT_GT(kCaseB, kCaseA);
3936 EXPECT_GE(kCaseA, kCaseA);
3937 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3938 "(kCaseA) >= (kCaseB)");
3939 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3940 "-1 vs 42");
3941
3942 ASSERT_EQ(kCaseA, kCaseA);
3943 ASSERT_NE(kCaseA, kCaseB);
3944 ASSERT_LT(kCaseA, kCaseB);
3945 ASSERT_LE(kCaseA, kCaseB);
3946 ASSERT_GT(kCaseB, kCaseA);
3947 ASSERT_GE(kCaseA, kCaseA);
3948
3949# ifndef __BORLANDC__
3950
3951 // ICE's in C++Builder.
3952 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3953 "To be equal to: kCaseB");
3954 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3955 "Which is: 42");
3956# endif
3957
3958 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3959 "Which is: -1");
3960}
3961
3962#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3963
3964#if GTEST_OS_WINDOWS
3965
3966static HRESULT UnexpectedHRESULTFailure() {
3967 return E_UNEXPECTED;
3968}
3969
3970static HRESULT OkHRESULTSuccess() {
3971 return S_OK;
3972}
3973
3974static HRESULT FalseHRESULTSuccess() {
3975 return S_FALSE;
3976}
3977
3978// HRESULT assertion tests test both zero and non-zero
3979// success codes as well as failure message for each.
3980//
3981// Windows CE doesn't support message texts.
3982TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3983 EXPECT_HRESULT_SUCCEEDED(S_OK);
3984 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3985
3986 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3987 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3988 " Actual: 0x8000FFFF");
3989}
3990
3991TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3992 ASSERT_HRESULT_SUCCEEDED(S_OK);
3993 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3994
3995 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3996 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3997 " Actual: 0x8000FFFF");
3998}
3999
4000TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4001 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4002
4003 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4004 "Expected: (OkHRESULTSuccess()) fails.\n"
4005 " Actual: 0x0");
4006 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4007 "Expected: (FalseHRESULTSuccess()) fails.\n"
4008 " Actual: 0x1");
4009}
4010
4011TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4012 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4013
4014# ifndef __BORLANDC__
4015
4016 // ICE's in C++Builder 2007 and 2009.
4017 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4018 "Expected: (OkHRESULTSuccess()) fails.\n"
4019 " Actual: 0x0");
4020# endif
4021
4022 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4023 "Expected: (FalseHRESULTSuccess()) fails.\n"
4024 " Actual: 0x1");
4025}
4026
4027// Tests that streaming to the HRESULT macros works.
4028TEST(HRESULTAssertionTest, Streaming) {
4029 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4030 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4031 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4032 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4033
4034 EXPECT_NONFATAL_FAILURE(
4035 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4036 "expected failure");
4037
4038# ifndef __BORLANDC__
4039
4040 // ICE's in C++Builder 2007 and 2009.
4041 EXPECT_FATAL_FAILURE(
4042 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4043 "expected failure");
4044# endif
4045
4046 EXPECT_NONFATAL_FAILURE(
4047 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4048 "expected failure");
4049
4050 EXPECT_FATAL_FAILURE(
4051 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4052 "expected failure");
4053}
4054
4055#endif // GTEST_OS_WINDOWS
4056
4057#ifdef __BORLANDC__
4058// Silences warnings: "Condition is always true", "Unreachable code"
4059# pragma option push -w-ccc -w-rch
4060#endif
4061
4062// Tests that the assertion macros behave like single statements.
4063TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4064 if (AlwaysFalse())
4065 ASSERT_TRUE(false) << "This should never be executed; "
4066 "It's a compilation test only.";
4067
4068 if (AlwaysTrue())
4069 EXPECT_FALSE(false);
4070 else
4071 ; // NOLINT
4072
4073 if (AlwaysFalse())
4074 ASSERT_LT(1, 3);
4075
4076 if (AlwaysFalse())
4077 ; // NOLINT
4078 else
4079 EXPECT_GT(3, 2) << "";
4080}
4081
4082#if GTEST_HAS_EXCEPTIONS
4083// Tests that the compiler will not complain about unreachable code in the
4084// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4085TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4086 int n = 0;
4087
4088 EXPECT_THROW(throw 1, int);
4089 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4090 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4091 EXPECT_NO_THROW(n++);
4092 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4093 EXPECT_ANY_THROW(throw 1);
4094 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4095}
4096
4097TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4098 if (AlwaysFalse())
4099 EXPECT_THROW(ThrowNothing(), bool);
4100
4101 if (AlwaysTrue())
4102 EXPECT_THROW(ThrowAnInteger(), int);
4103 else
4104 ; // NOLINT
4105
4106 if (AlwaysFalse())
4107 EXPECT_NO_THROW(ThrowAnInteger());
4108
4109 if (AlwaysTrue())
4110 EXPECT_NO_THROW(ThrowNothing());
4111 else
4112 ; // NOLINT
4113
4114 if (AlwaysFalse())
4115 EXPECT_ANY_THROW(ThrowNothing());
4116
4117 if (AlwaysTrue())
4118 EXPECT_ANY_THROW(ThrowAnInteger());
4119 else
4120 ; // NOLINT
4121}
4122#endif // GTEST_HAS_EXCEPTIONS
4123
4124TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4125 if (AlwaysFalse())
4126 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4127 << "It's a compilation test only.";
4128 else
4129 ; // NOLINT
4130
4131 if (AlwaysFalse())
4132 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4133 else
4134 ; // NOLINT
4135
4136 if (AlwaysTrue())
4137 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4138 else
4139 ; // NOLINT
4140
4141 if (AlwaysFalse())
4142 ; // NOLINT
4143 else
4144 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4145}
4146
4147// Tests that the assertion macros work well with switch statements.
4148TEST(AssertionSyntaxTest, WorksWithSwitch) {
4149 switch (0) {
4150 case 1:
4151 break;
4152 default:
4153 ASSERT_TRUE(true);
4154 }
4155
4156 switch (0)
4157 case 0:
4158 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4159
4160 // Binary assertions are implemented using a different code path
4161 // than the Boolean assertions. Hence we test them separately.
4162 switch (0) {
4163 case 1:
4164 default:
4165 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4166 }
4167
4168 switch (0)
4169 case 0:
4170 EXPECT_NE(1, 2);
4171}
4172
4173#if GTEST_HAS_EXCEPTIONS
4174
4175void ThrowAString() {
4176 throw "std::string";
4177}
4178
4179// Test that the exception assertion macros compile and work with const
4180// type qualifier.
4181TEST(AssertionSyntaxTest, WorksWithConst) {
4182 ASSERT_THROW(ThrowAString(), const char*);
4183
4184 EXPECT_THROW(ThrowAString(), const char*);
4185}
4186
4187#endif // GTEST_HAS_EXCEPTIONS
4188
4189} // namespace
4190
4191namespace testing {
4192
4193// Tests that Google Test tracks SUCCEED*.
4194TEST(SuccessfulAssertionTest, SUCCEED) {
4195 SUCCEED();
4196 SUCCEED() << "OK";
4197 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4198}
4199
4200// Tests that Google Test doesn't track successful EXPECT_*.
4201TEST(SuccessfulAssertionTest, EXPECT) {
4202 EXPECT_TRUE(true);
4203 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4204}
4205
4206// Tests that Google Test doesn't track successful EXPECT_STR*.
4207TEST(SuccessfulAssertionTest, EXPECT_STR) {
4208 EXPECT_STREQ("", "");
4209 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4210}
4211
4212// Tests that Google Test doesn't track successful ASSERT_*.
4213TEST(SuccessfulAssertionTest, ASSERT) {
4214 ASSERT_TRUE(true);
4215 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4216}
4217
4218// Tests that Google Test doesn't track successful ASSERT_STR*.
4219TEST(SuccessfulAssertionTest, ASSERT_STR) {
4220 ASSERT_STREQ("", "");
4221 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4222}
4223
4224} // namespace testing
4225
4226namespace {
4227
4228// Tests the message streaming variation of assertions.
4229
4230TEST(AssertionWithMessageTest, EXPECT) {
4231 EXPECT_EQ(1, 1) << "This should succeed.";
4232 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4233 "Expected failure #1");
4234 EXPECT_LE(1, 2) << "This should succeed.";
4235 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4236 "Expected failure #2.");
4237 EXPECT_GE(1, 0) << "This should succeed.";
4238 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4239 "Expected failure #3.");
4240
4241 EXPECT_STREQ("1", "1") << "This should succeed.";
4242 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4243 "Expected failure #4.");
4244 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4245 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4246 "Expected failure #5.");
4247
4248 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4249 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4250 "Expected failure #6.");
4251 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4252}
4253
4254TEST(AssertionWithMessageTest, ASSERT) {
4255 ASSERT_EQ(1, 1) << "This should succeed.";
4256 ASSERT_NE(1, 2) << "This should succeed.";
4257 ASSERT_LE(1, 2) << "This should succeed.";
4258 ASSERT_LT(1, 2) << "This should succeed.";
4259 ASSERT_GE(1, 0) << "This should succeed.";
4260 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4261 "Expected failure.");
4262}
4263
4264TEST(AssertionWithMessageTest, ASSERT_STR) {
4265 ASSERT_STREQ("1", "1") << "This should succeed.";
4266 ASSERT_STRNE("1", "2") << "This should succeed.";
4267 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4268 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4269 "Expected failure.");
4270}
4271
4272TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4273 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4274 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4275 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
4276 "Expect failure.");
4277 // To work around a bug in gcc 2.95.0, there is intentionally no
4278 // space after the first comma in the previous statement.
4279}
4280
4281// Tests using ASSERT_FALSE with a streamed message.
4282TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4283 ASSERT_FALSE(false) << "This shouldn't fail.";
4284 EXPECT_FATAL_FAILURE({ // NOLINT
4285 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4286 << " evaluates to " << true;
4287 }, "Expected failure");
4288}
4289
4290// Tests using FAIL with a streamed message.
4291TEST(AssertionWithMessageTest, FAIL) {
4292 EXPECT_FATAL_FAILURE(FAIL() << 0,
4293 "0");
4294}
4295
4296// Tests using SUCCEED with a streamed message.
4297TEST(AssertionWithMessageTest, SUCCEED) {
4298 SUCCEED() << "Success == " << 1;
4299}
4300
4301// Tests using ASSERT_TRUE with a streamed message.
4302TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4303 ASSERT_TRUE(true) << "This should succeed.";
4304 ASSERT_TRUE(true) << true;
4305 EXPECT_FATAL_FAILURE({ // NOLINT
4306 ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4307 << static_cast<char *>(NULL);
4308 }, "(null)(null)");
4309}
4310
4311#if GTEST_OS_WINDOWS
4312// Tests using wide strings in assertion messages.
4313TEST(AssertionWithMessageTest, WideStringMessage) {
4314 EXPECT_NONFATAL_FAILURE({ // NOLINT
4315 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4316 }, "This failure is expected.");
4317 EXPECT_FATAL_FAILURE({ // NOLINT
4318 ASSERT_EQ(1, 2) << "This failure is "
4319 << L"expected too.\x8120";
4320 }, "This failure is expected too.");
4321}
4322#endif // GTEST_OS_WINDOWS
4323
4324// Tests EXPECT_TRUE.
4325TEST(ExpectTest, EXPECT_TRUE) {
4326 EXPECT_TRUE(true) << "Intentional success";
4327 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4328 "Intentional failure #1.");
4329 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4330 "Intentional failure #2.");
4331 EXPECT_TRUE(2 > 1); // NOLINT
4332 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4333 "Value of: 2 < 1\n"
4334 " Actual: false\n"
4335 "Expected: true");
4336 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4337 "2 > 3");
4338}
4339
4340// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4341TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4342 EXPECT_TRUE(ResultIsEven(2));
4343 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4344 "Value of: ResultIsEven(3)\n"
4345 " Actual: false (3 is odd)\n"
4346 "Expected: true");
4347 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4348 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4349 "Value of: ResultIsEvenNoExplanation(3)\n"
4350 " Actual: false (3 is odd)\n"
4351 "Expected: true");
4352}
4353
4354// Tests EXPECT_FALSE with a streamed message.
4355TEST(ExpectTest, EXPECT_FALSE) {
4356 EXPECT_FALSE(2 < 1); // NOLINT
4357 EXPECT_FALSE(false) << "Intentional success";
4358 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4359 "Intentional failure #1.");
4360 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4361 "Intentional failure #2.");
4362 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4363 "Value of: 2 > 1\n"
4364 " Actual: true\n"
4365 "Expected: false");
4366 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4367 "2 < 3");
4368}
4369
4370// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4371TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4372 EXPECT_FALSE(ResultIsEven(3));
4373 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4374 "Value of: ResultIsEven(2)\n"
4375 " Actual: true (2 is even)\n"
4376 "Expected: false");
4377 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4378 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4379 "Value of: ResultIsEvenNoExplanation(2)\n"
4380 " Actual: true\n"
4381 "Expected: false");
4382}
4383
4384#ifdef __BORLANDC__
4385// Restores warnings after previous "#pragma option push" supressed them
4386# pragma option pop
4387#endif
4388
4389// Tests EXPECT_EQ.
4390TEST(ExpectTest, EXPECT_EQ) {
4391 EXPECT_EQ(5, 2 + 3);
4392 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4393 " Expected: 5\n"
4394 "To be equal to: 2*3\n"
4395 " Which is: 6");
4396 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4397 "2 - 3");
4398}
4399
4400// Tests using EXPECT_EQ on double values. The purpose is to make
4401// sure that the specialization we did for integer and anonymous enums
4402// isn't used for double arguments.
4403TEST(ExpectTest, EXPECT_EQ_Double) {
4404 // A success.
4405 EXPECT_EQ(5.6, 5.6);
4406
4407 // A failure.
4408 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4409 "5.1");
4410}
4411
4412#if GTEST_CAN_COMPARE_NULL
4413// Tests EXPECT_EQ(NULL, pointer).
4414TEST(ExpectTest, EXPECT_EQ_NULL) {
4415 // A success.
4416 const char* p = NULL;
4417 // Some older GCC versions may issue a spurious warning in this or the next
4418 // assertion statement. This warning should not be suppressed with
4419 // static_cast since the test verifies the ability to use bare NULL as the
4420 // expected parameter to the macro.
4421 EXPECT_EQ(NULL, p);
4422
4423 // A failure.
4424 int n = 0;
4425 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4426 "To be equal to: &n\n");
4427}
4428#endif // GTEST_CAN_COMPARE_NULL
4429
4430// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4431// treated as a null pointer by the compiler, we need to make sure
4432// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4433// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4434TEST(ExpectTest, EXPECT_EQ_0) {
4435 int n = 0;
4436
4437 // A success.
4438 EXPECT_EQ(0, n);
4439
4440 // A failure.
4441 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4442 "Expected: 0");
4443}
4444
4445// Tests EXPECT_NE.
4446TEST(ExpectTest, EXPECT_NE) {
4447 EXPECT_NE(6, 7);
4448
4449 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4450 "Expected: ('a') != ('a'), "
4451 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4452 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4453 "2");
4454 char* const p0 = NULL;
4455 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4456 "p0");
4457 // Only way to get the Nokia compiler to compile the cast
4458 // is to have a separate void* variable first. Putting
4459 // the two casts on the same line doesn't work, neither does
4460 // a direct C-style to char*.
4461 void* pv1 = (void*)0x1234; // NOLINT
4462 char* const p1 = reinterpret_cast<char*>(pv1);
4463 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4464 "p1");
4465}
4466
4467// Tests EXPECT_LE.
4468TEST(ExpectTest, EXPECT_LE) {
4469 EXPECT_LE(2, 3);
4470 EXPECT_LE(2, 2);
4471 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4472 "Expected: (2) <= (0), actual: 2 vs 0");
4473 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4474 "(1.1) <= (0.9)");
4475}
4476
4477// Tests EXPECT_LT.
4478TEST(ExpectTest, EXPECT_LT) {
4479 EXPECT_LT(2, 3);
4480 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4481 "Expected: (2) < (2), actual: 2 vs 2");
4482 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4483 "(2) < (1)");
4484}
4485
4486// Tests EXPECT_GE.
4487TEST(ExpectTest, EXPECT_GE) {
4488 EXPECT_GE(2, 1);
4489 EXPECT_GE(2, 2);
4490 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4491 "Expected: (2) >= (3), actual: 2 vs 3");
4492 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4493 "(0.9) >= (1.1)");
4494}
4495
4496// Tests EXPECT_GT.
4497TEST(ExpectTest, EXPECT_GT) {
4498 EXPECT_GT(2, 1);
4499 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4500 "Expected: (2) > (2), actual: 2 vs 2");
4501 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4502 "(2) > (3)");
4503}
4504
4505#if GTEST_HAS_EXCEPTIONS
4506
4507// Tests EXPECT_THROW.
4508TEST(ExpectTest, EXPECT_THROW) {
4509 EXPECT_THROW(ThrowAnInteger(), int);
4510 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4511 "Expected: ThrowAnInteger() throws an exception of "
4512 "type bool.\n Actual: it throws a different type.");
4513 EXPECT_NONFATAL_FAILURE(
4514 EXPECT_THROW(ThrowNothing(), bool),
4515 "Expected: ThrowNothing() throws an exception of type bool.\n"
4516 " Actual: it throws nothing.");
4517}
4518
4519// Tests EXPECT_NO_THROW.
4520TEST(ExpectTest, EXPECT_NO_THROW) {
4521 EXPECT_NO_THROW(ThrowNothing());
4522 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4523 "Expected: ThrowAnInteger() doesn't throw an "
4524 "exception.\n Actual: it throws.");
4525}
4526
4527// Tests EXPECT_ANY_THROW.
4528TEST(ExpectTest, EXPECT_ANY_THROW) {
4529 EXPECT_ANY_THROW(ThrowAnInteger());
4530 EXPECT_NONFATAL_FAILURE(
4531 EXPECT_ANY_THROW(ThrowNothing()),
4532 "Expected: ThrowNothing() throws an exception.\n"
4533 " Actual: it doesn't.");
4534}
4535
4536#endif // GTEST_HAS_EXCEPTIONS
4537
4538// Make sure we deal with the precedence of <<.
4539TEST(ExpectTest, ExpectPrecedence) {
4540 EXPECT_EQ(1 < 2, true);
4541 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4542 "To be equal to: true && false");
4543}
4544
4545
4546// Tests the StreamableToString() function.
4547
4548// Tests using StreamableToString() on a scalar.
4549TEST(StreamableToStringTest, Scalar) {
4550 EXPECT_STREQ("5", StreamableToString(5).c_str());
4551}
4552
4553// Tests using StreamableToString() on a non-char pointer.
4554TEST(StreamableToStringTest, Pointer) {
4555 int n = 0;
4556 int* p = &n;
4557 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4558}
4559
4560// Tests using StreamableToString() on a NULL non-char pointer.
4561TEST(StreamableToStringTest, NullPointer) {
4562 int* p = NULL;
4563 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4564}
4565
4566// Tests using StreamableToString() on a C string.
4567TEST(StreamableToStringTest, CString) {
4568 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4569}
4570
4571// Tests using StreamableToString() on a NULL C string.
4572TEST(StreamableToStringTest, NullCString) {
4573 char* p = NULL;
4574 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4575}
4576
4577// Tests using streamable values as assertion messages.
4578
4579// Tests using std::string as an assertion message.
4580TEST(StreamableTest, string) {
4581 static const std::string str(
4582 "This failure message is a std::string, and is expected.");
4583 EXPECT_FATAL_FAILURE(FAIL() << str,
4584 str.c_str());
4585}
4586
4587// Tests that we can output strings containing embedded NULs.
4588// Limited to Linux because we can only do this with std::string's.
4589TEST(StreamableTest, stringWithEmbeddedNUL) {
4590 static const char char_array_with_nul[] =
4591 "Here's a NUL\0 and some more string";
4592 static const std::string string_with_nul(char_array_with_nul,
4593 sizeof(char_array_with_nul)
4594 - 1); // drops the trailing NUL
4595 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4596 "Here's a NUL\\0 and some more string");
4597}
4598
4599// Tests that we can output a NUL char.
4600TEST(StreamableTest, NULChar) {
4601 EXPECT_FATAL_FAILURE({ // NOLINT
4602 FAIL() << "A NUL" << '\0' << " and some more string";
4603 }, "A NUL\\0 and some more string");
4604}
4605
4606// Tests using int as an assertion message.
4607TEST(StreamableTest, int) {
4608 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4609 "900913");
4610}
4611
4612// Tests using NULL char pointer as an assertion message.
4613//
4614// In MSVC, streaming a NULL char * causes access violation. Google Test
4615// implemented a workaround (substituting "(null)" for NULL). This
4616// tests whether the workaround works.
4617TEST(StreamableTest, NullCharPtr) {
4618 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4619 "(null)");
4620}
4621
4622// Tests that basic IO manipulators (endl, ends, and flush) can be
4623// streamed to testing::Message.
4624TEST(StreamableTest, BasicIoManip) {
4625 EXPECT_FATAL_FAILURE({ // NOLINT
4626 FAIL() << "Line 1." << std::endl
4627 << "A NUL char " << std::ends << std::flush << " in line 2.";
4628 }, "Line 1.\nA NUL char \\0 in line 2.");
4629}
4630
4631// Tests the macros that haven't been covered so far.
4632
4633void AddFailureHelper(bool* aborted) {
4634 *aborted = true;
4635 ADD_FAILURE() << "Intentional failure.";
4636 *aborted = false;
4637}
4638
4639// Tests ADD_FAILURE.
4640TEST(MacroTest, ADD_FAILURE) {
4641 bool aborted = true;
4642 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4643 "Intentional failure.");
4644 EXPECT_FALSE(aborted);
4645}
4646
4647// Tests ADD_FAILURE_AT.
4648TEST(MacroTest, ADD_FAILURE_AT) {
4649 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4650 // the failure message contains the user-streamed part.
4651 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4652
4653 // Verifies that the user-streamed part is optional.
4654 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4655
4656 // Unfortunately, we cannot verify that the failure message contains
4657 // the right file path and line number the same way, as
4658 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4659 // line number. Instead, we do that in gtest_output_test_.cc.
4660}
4661
4662// Tests FAIL.
4663TEST(MacroTest, FAIL) {
4664 EXPECT_FATAL_FAILURE(FAIL(),
4665 "Failed");
4666 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4667 "Intentional failure.");
4668}
4669
4670// Tests SUCCEED
4671TEST(MacroTest, SUCCEED) {
4672 SUCCEED();
4673 SUCCEED() << "Explicit success.";
4674}
4675
4676// Tests for EXPECT_EQ() and ASSERT_EQ().
4677//
4678// These tests fail *intentionally*, s.t. the failure messages can be
4679// generated and tested.
4680//
4681// We have different tests for different argument types.
4682
4683// Tests using bool values in {EXPECT|ASSERT}_EQ.
4684TEST(EqAssertionTest, Bool) {
4685 EXPECT_EQ(true, true);
4686 EXPECT_FATAL_FAILURE({
4687 bool false_value = false;
4688 ASSERT_EQ(false_value, true);
4689 }, "To be equal to: true");
4690}
4691
4692// Tests using int values in {EXPECT|ASSERT}_EQ.
4693TEST(EqAssertionTest, Int) {
4694 ASSERT_EQ(32, 32);
4695 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4696 "33");
4697}
4698
4699// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4700TEST(EqAssertionTest, Time_T) {
4701 EXPECT_EQ(static_cast<time_t>(0),
4702 static_cast<time_t>(0));
4703 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4704 static_cast<time_t>(1234)),
4705 "1234");
4706}
4707
4708// Tests using char values in {EXPECT|ASSERT}_EQ.
4709TEST(EqAssertionTest, Char) {
4710 ASSERT_EQ('z', 'z');
4711 const char ch = 'b';
4712 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4713 "ch");
4714 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4715 "ch");
4716}
4717
4718// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4719TEST(EqAssertionTest, WideChar) {
4720 EXPECT_EQ(L'b', L'b');
4721
4722 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4723 " Expected: L'\0'\n"
4724 " Which is: L'\0' (0, 0x0)\n"
4725 "To be equal to: L'x'\n"
4726 " Which is: L'x' (120, 0x78)");
4727
4728 static wchar_t wchar;
4729 wchar = L'b';
4730 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4731 "wchar");
4732 wchar = 0x8119;
4733 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4734 "To be equal to: wchar");
4735}
4736
4737// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4738TEST(EqAssertionTest, StdString) {
4739 // Compares a const char* to an std::string that has identical
4740 // content.
4741 ASSERT_EQ("Test", ::std::string("Test"));
4742
4743 // Compares two identical std::strings.
4744 static const ::std::string str1("A * in the middle");
4745 static const ::std::string str2(str1);
4746 EXPECT_EQ(str1, str2);
4747
4748 // Compares a const char* to an std::string that has different
4749 // content
4750 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4751 "\"test\"");
4752
4753 // Compares an std::string to a char* that has different content.
4754 char* const p1 = const_cast<char*>("foo");
4755 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4756 "p1");
4757
4758 // Compares two std::strings that have different contents, one of
4759 // which having a NUL character in the middle. This should fail.
4760 static ::std::string str3(str1);
4761 str3.at(2) = '\0';
4762 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4763 "To be equal to: str3\n"
4764 " Which is: \"A \\0 in the middle\"");
4765}
4766
4767#if GTEST_HAS_STD_WSTRING
4768
4769// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4770TEST(EqAssertionTest, StdWideString) {
4771 // Compares two identical std::wstrings.
4772 const ::std::wstring wstr1(L"A * in the middle");
4773 const ::std::wstring wstr2(wstr1);
4774 ASSERT_EQ(wstr1, wstr2);
4775
4776 // Compares an std::wstring to a const wchar_t* that has identical
4777 // content.
4778 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4779 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4780
4781 // Compares an std::wstring to a const wchar_t* that has different
4782 // content.
4783 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4784 EXPECT_NONFATAL_FAILURE({ // NOLINT
4785 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4786 }, "kTestX8120");
4787
4788 // Compares two std::wstrings that have different contents, one of
4789 // which having a NUL character in the middle.
4790 ::std::wstring wstr3(wstr1);
4791 wstr3.at(2) = L'\0';
4792 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4793 "wstr3");
4794
4795 // Compares a wchar_t* to an std::wstring that has different
4796 // content.
4797 EXPECT_FATAL_FAILURE({ // NOLINT
4798 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4799 }, "");
4800}
4801
4802#endif // GTEST_HAS_STD_WSTRING
4803
4804#if GTEST_HAS_GLOBAL_STRING
4805// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4806TEST(EqAssertionTest, GlobalString) {
4807 // Compares a const char* to a ::string that has identical content.
4808 EXPECT_EQ("Test", ::string("Test"));
4809
4810 // Compares two identical ::strings.
4811 const ::string str1("A * in the middle");
4812 const ::string str2(str1);
4813 ASSERT_EQ(str1, str2);
4814
4815 // Compares a ::string to a const char* that has different content.
4816 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4817 "test");
4818
4819 // Compares two ::strings that have different contents, one of which
4820 // having a NUL character in the middle.
4821 ::string str3(str1);
4822 str3.at(2) = '\0';
4823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4824 "str3");
4825
4826 // Compares a ::string to a char* that has different content.
4827 EXPECT_FATAL_FAILURE({ // NOLINT
4828 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4829 }, "");
4830}
4831
4832#endif // GTEST_HAS_GLOBAL_STRING
4833
4834#if GTEST_HAS_GLOBAL_WSTRING
4835
4836// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4837TEST(EqAssertionTest, GlobalWideString) {
4838 // Compares two identical ::wstrings.
4839 static const ::wstring wstr1(L"A * in the middle");
4840 static const ::wstring wstr2(wstr1);
4841 EXPECT_EQ(wstr1, wstr2);
4842
4843 // Compares a const wchar_t* to a ::wstring that has identical content.
4844 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4845 ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4846
4847 // Compares a const wchar_t* to a ::wstring that has different
4848 // content.
4849 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4850 EXPECT_NONFATAL_FAILURE({ // NOLINT
4851 EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
4852 }, "Test\\x8119");
4853
4854 // Compares a wchar_t* to a ::wstring that has different content.
4855 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4856 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4857 "bar");
4858
4859 // Compares two ::wstrings that have different contents, one of which
4860 // having a NUL character in the middle.
4861 static ::wstring wstr3;
4862 wstr3 = wstr1;
4863 wstr3.at(2) = L'\0';
4864 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4865 "wstr3");
4866}
4867
4868#endif // GTEST_HAS_GLOBAL_WSTRING
4869
4870// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4871TEST(EqAssertionTest, CharPointer) {
4872 char* const p0 = NULL;
4873 // Only way to get the Nokia compiler to compile the cast
4874 // is to have a separate void* variable first. Putting
4875 // the two casts on the same line doesn't work, neither does
4876 // a direct C-style to char*.
4877 void* pv1 = (void*)0x1234; // NOLINT
4878 void* pv2 = (void*)0xABC0; // NOLINT
4879 char* const p1 = reinterpret_cast<char*>(pv1);
4880 char* const p2 = reinterpret_cast<char*>(pv2);
4881 ASSERT_EQ(p1, p1);
4882
4883 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4884 "To be equal to: p2");
4885 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4886 "p2");
4887 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4888 reinterpret_cast<char*>(0xABC0)),
4889 "ABC0");
4890}
4891
4892// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4893TEST(EqAssertionTest, WideCharPointer) {
4894 wchar_t* const p0 = NULL;
4895 // Only way to get the Nokia compiler to compile the cast
4896 // is to have a separate void* variable first. Putting
4897 // the two casts on the same line doesn't work, neither does
4898 // a direct C-style to char*.
4899 void* pv1 = (void*)0x1234; // NOLINT
4900 void* pv2 = (void*)0xABC0; // NOLINT
4901 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4902 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4903 EXPECT_EQ(p0, p0);
4904
4905 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4906 "To be equal to: p2");
4907 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4908 "p2");
4909 void* pv3 = (void*)0x1234; // NOLINT
4910 void* pv4 = (void*)0xABC0; // NOLINT
4911 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4912 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4913 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4914 "p4");
4915}
4916
4917// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4918TEST(EqAssertionTest, OtherPointer) {
4919 ASSERT_EQ(static_cast<const int*>(NULL),
4920 static_cast<const int*>(NULL));
4921 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4922 reinterpret_cast<const int*>(0x1234)),
4923 "0x1234");
4924}
4925
4926// A class that supports binary comparison operators but not streaming.
4927class UnprintableChar {
4928 public:
4929 explicit UnprintableChar(char ch) : char_(ch) {}
4930
4931 bool operator==(const UnprintableChar& rhs) const {
4932 return char_ == rhs.char_;
4933 }
4934 bool operator!=(const UnprintableChar& rhs) const {
4935 return char_ != rhs.char_;
4936 }
4937 bool operator<(const UnprintableChar& rhs) const {
4938 return char_ < rhs.char_;
4939 }
4940 bool operator<=(const UnprintableChar& rhs) const {
4941 return char_ <= rhs.char_;
4942 }
4943 bool operator>(const UnprintableChar& rhs) const {
4944 return char_ > rhs.char_;
4945 }
4946 bool operator>=(const UnprintableChar& rhs) const {
4947 return char_ >= rhs.char_;
4948 }
4949
4950 private:
4951 char char_;
4952};
4953
4954// Tests that ASSERT_EQ() and friends don't require the arguments to
4955// be printable.
4956TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4957 const UnprintableChar x('x'), y('y');
4958 ASSERT_EQ(x, x);
4959 EXPECT_NE(x, y);
4960 ASSERT_LT(x, y);
4961 EXPECT_LE(x, y);
4962 ASSERT_GT(y, x);
4963 EXPECT_GE(x, x);
4964
4965 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4966 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4967 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4968 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4969 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4970
4971 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4972 // variables, so we have to write UnprintableChar('x') instead of x.
4973#ifndef __BORLANDC__
4974 // ICE's in C++Builder.
4975 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4976 "1-byte object <78>");
4977 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4978 "1-byte object <78>");
4979#endif
4980 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4981 "1-byte object <79>");
4982 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4983 "1-byte object <78>");
4984 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4985 "1-byte object <79>");
4986}
4987
4988// Tests the FRIEND_TEST macro.
4989
4990// This class has a private member we want to test. We will test it
4991// both in a TEST and in a TEST_F.
4992class Foo {
4993 public:
4994 Foo() {}
4995
4996 private:
4997 int Bar() const { return 1; }
4998
4999 // Declares the friend tests that can access the private member
5000 // Bar().
5001 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5002 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5003};
5004
5005// Tests that the FRIEND_TEST declaration allows a TEST to access a
5006// class's private members. This should compile.
5007TEST(FRIEND_TEST_Test, TEST) {
5008 ASSERT_EQ(1, Foo().Bar());
5009}
5010
5011// The fixture needed to test using FRIEND_TEST with TEST_F.
5012class FRIEND_TEST_Test2 : public Test {
5013 protected:
5014 Foo foo;
5015};
5016
5017// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5018// class's private members. This should compile.
5019TEST_F(FRIEND_TEST_Test2, TEST_F) {
5020 ASSERT_EQ(1, foo.Bar());
5021}
5022
5023// Tests the life cycle of Test objects.
5024
5025// The test fixture for testing the life cycle of Test objects.
5026//
5027// This class counts the number of live test objects that uses this
5028// fixture.
5029class TestLifeCycleTest : public Test {
5030 protected:
5031 // Constructor. Increments the number of test objects that uses
5032 // this fixture.
5033 TestLifeCycleTest() { count_++; }
5034
5035 // Destructor. Decrements the number of test objects that uses this
5036 // fixture.
5037 ~TestLifeCycleTest() { count_--; }
5038
5039 // Returns the number of live test objects that uses this fixture.
5040 int count() const { return count_; }
5041
5042 private:
5043 static int count_;
5044};
5045
5046int TestLifeCycleTest::count_ = 0;
5047
5048// Tests the life cycle of test objects.
5049TEST_F(TestLifeCycleTest, Test1) {
5050 // There should be only one test object in this test case that's
5051 // currently alive.
5052 ASSERT_EQ(1, count());
5053}
5054
5055// Tests the life cycle of test objects.
5056TEST_F(TestLifeCycleTest, Test2) {
5057 // After Test1 is done and Test2 is started, there should still be
5058 // only one live test object, as the object for Test1 should've been
5059 // deleted.
5060 ASSERT_EQ(1, count());
5061}
5062
5063} // namespace
5064
5065// Tests that the copy constructor works when it is NOT optimized away by
5066// the compiler.
5067TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5068 // Checks that the copy constructor doesn't try to dereference NULL pointers
5069 // in the source object.
5070 AssertionResult r1 = AssertionSuccess();
5071 AssertionResult r2 = r1;
5072 // The following line is added to prevent the compiler from optimizing
5073 // away the constructor call.
5074 r1 << "abc";
5075
5076 AssertionResult r3 = r1;
5077 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5078 EXPECT_STREQ("abc", r1.message());
5079}
5080
5081// Tests that AssertionSuccess and AssertionFailure construct
5082// AssertionResult objects as expected.
5083TEST(AssertionResultTest, ConstructionWorks) {
5084 AssertionResult r1 = AssertionSuccess();
5085 EXPECT_TRUE(r1);
5086 EXPECT_STREQ("", r1.message());
5087
5088 AssertionResult r2 = AssertionSuccess() << "abc";
5089 EXPECT_TRUE(r2);
5090 EXPECT_STREQ("abc", r2.message());
5091
5092 AssertionResult r3 = AssertionFailure();
5093 EXPECT_FALSE(r3);
5094 EXPECT_STREQ("", r3.message());
5095
5096 AssertionResult r4 = AssertionFailure() << "def";
5097 EXPECT_FALSE(r4);
5098 EXPECT_STREQ("def", r4.message());
5099
5100 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5101 EXPECT_FALSE(r5);
5102 EXPECT_STREQ("ghi", r5.message());
5103}
5104
5105// Tests that the negation flips the predicate result but keeps the message.
5106TEST(AssertionResultTest, NegationWorks) {
5107 AssertionResult r1 = AssertionSuccess() << "abc";
5108 EXPECT_FALSE(!r1);
5109 EXPECT_STREQ("abc", (!r1).message());
5110
5111 AssertionResult r2 = AssertionFailure() << "def";
5112 EXPECT_TRUE(!r2);
5113 EXPECT_STREQ("def", (!r2).message());
5114}
5115
5116TEST(AssertionResultTest, StreamingWorks) {
5117 AssertionResult r = AssertionSuccess();
5118 r << "abc" << 'd' << 0 << true;
5119 EXPECT_STREQ("abcd0true", r.message());
5120}
5121
5122TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5123 AssertionResult r = AssertionSuccess();
5124 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5125 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5126}
5127
5128// The next test uses explicit conversion operators -- a C++11 feature.
5129#if GTEST_LANG_CXX11
5130
5131TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5132 struct ExplicitlyConvertibleToBool {
5133 explicit operator bool() const { return value; }
5134 bool value;
5135 };
5136 ExplicitlyConvertibleToBool v1 = {false};
5137 ExplicitlyConvertibleToBool v2 = {true};
5138 EXPECT_FALSE(v1);
5139 EXPECT_TRUE(v2);
5140}
5141
5142#endif // GTEST_LANG_CXX11
5143
5144struct ConvertibleToAssertionResult {
5145 operator AssertionResult() const { return AssertionResult(true); }
5146};
5147
5148TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5149 ConvertibleToAssertionResult obj;
5150 EXPECT_TRUE(obj);
5151}
5152
5153// Tests streaming a user type whose definition and operator << are
5154// both in the global namespace.
5155class Base {
5156 public:
5157 explicit Base(int an_x) : x_(an_x) {}
5158 int x() const { return x_; }
5159 private:
5160 int x_;
5161};
5162std::ostream& operator<<(std::ostream& os,
5163 const Base& val) {
5164 return os << val.x();
5165}
5166std::ostream& operator<<(std::ostream& os,
5167 const Base* pointer) {
5168 return os << "(" << pointer->x() << ")";
5169}
5170
5171TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5172 Message msg;
5173 Base a(1);
5174
5175 msg << a << &a; // Uses ::operator<<.
5176 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5177}
5178
5179// Tests streaming a user type whose definition and operator<< are
5180// both in an unnamed namespace.
5181namespace {
5182class MyTypeInUnnamedNameSpace : public Base {
5183 public:
5184 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5185};
5186std::ostream& operator<<(std::ostream& os,
5187 const MyTypeInUnnamedNameSpace& val) {
5188 return os << val.x();
5189}
5190std::ostream& operator<<(std::ostream& os,
5191 const MyTypeInUnnamedNameSpace* pointer) {
5192 return os << "(" << pointer->x() << ")";
5193}
5194} // namespace
5195
5196TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5197 Message msg;
5198 MyTypeInUnnamedNameSpace a(1);
5199
5200 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5201 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5202}
5203
5204// Tests streaming a user type whose definition and operator<< are
5205// both in a user namespace.
5206namespace namespace1 {
5207class MyTypeInNameSpace1 : public Base {
5208 public:
5209 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5210};
5211std::ostream& operator<<(std::ostream& os,
5212 const MyTypeInNameSpace1& val) {
5213 return os << val.x();
5214}
5215std::ostream& operator<<(std::ostream& os,
5216 const MyTypeInNameSpace1* pointer) {
5217 return os << "(" << pointer->x() << ")";
5218}
5219} // namespace namespace1
5220
5221TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5222 Message msg;
5223 namespace1::MyTypeInNameSpace1 a(1);
5224
5225 msg << a << &a; // Uses namespace1::operator<<.
5226 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5227}
5228
5229// Tests streaming a user type whose definition is in a user namespace
5230// but whose operator<< is in the global namespace.
5231namespace namespace2 {
5232class MyTypeInNameSpace2 : public ::Base {
5233 public:
5234 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5235};
5236} // namespace namespace2
5237std::ostream& operator<<(std::ostream& os,
5238 const namespace2::MyTypeInNameSpace2& val) {
5239 return os << val.x();
5240}
5241std::ostream& operator<<(std::ostream& os,
5242 const namespace2::MyTypeInNameSpace2* pointer) {
5243 return os << "(" << pointer->x() << ")";
5244}
5245
5246TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5247 Message msg;
5248 namespace2::MyTypeInNameSpace2 a(1);
5249
5250 msg << a << &a; // Uses ::operator<<.
5251 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5252}
5253
5254// Tests streaming NULL pointers to testing::Message.
5255TEST(MessageTest, NullPointers) {
5256 Message msg;
5257 char* const p1 = NULL;
5258 unsigned char* const p2 = NULL;
5259 int* p3 = NULL;
5260 double* p4 = NULL;
5261 bool* p5 = NULL;
5262 Message* p6 = NULL;
5263
5264 msg << p1 << p2 << p3 << p4 << p5 << p6;
5265 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5266 msg.GetString().c_str());
5267}
5268
5269// Tests streaming wide strings to testing::Message.
5270TEST(MessageTest, WideStrings) {
5271 // Streams a NULL of type const wchar_t*.
5272 const wchar_t* const_wstr = NULL;
5273 EXPECT_STREQ("(null)",
5274 (Message() << const_wstr).GetString().c_str());
5275
5276 // Streams a NULL of type wchar_t*.
5277 wchar_t* wstr = NULL;
5278 EXPECT_STREQ("(null)",
5279 (Message() << wstr).GetString().c_str());
5280
5281 // Streams a non-NULL of type const wchar_t*.
5282 const_wstr = L"abc\x8119";
5283 EXPECT_STREQ("abc\xe8\x84\x99",
5284 (Message() << const_wstr).GetString().c_str());
5285
5286 // Streams a non-NULL of type wchar_t*.
5287 wstr = const_cast<wchar_t*>(const_wstr);
5288 EXPECT_STREQ("abc\xe8\x84\x99",
5289 (Message() << wstr).GetString().c_str());
5290}
5291
5292
5293// This line tests that we can define tests in the testing namespace.
5294namespace testing {
5295
5296// Tests the TestInfo class.
5297
5298class TestInfoTest : public Test {
5299 protected:
5300 static const TestInfo* GetTestInfo(const char* test_name) {
5301 const TestCase* const test_case = GetUnitTestImpl()->
5302 GetTestCase("TestInfoTest", "", NULL, NULL);
5303
5304 for (int i = 0; i < test_case->total_test_count(); ++i) {
5305 const TestInfo* const test_info = test_case->GetTestInfo(i);
5306 if (strcmp(test_name, test_info->name()) == 0)
5307 return test_info;
5308 }
5309 return NULL;
5310 }
5311
5312 static const TestResult* GetTestResult(
5313 const TestInfo* test_info) {
5314 return test_info->result();
5315 }
5316};
5317
5318// Tests TestInfo::test_case_name() and TestInfo::name().
5319TEST_F(TestInfoTest, Names) {
5320 const TestInfo* const test_info = GetTestInfo("Names");
5321
5322 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5323 ASSERT_STREQ("Names", test_info->name());
5324}
5325
5326// Tests TestInfo::result().
5327TEST_F(TestInfoTest, result) {
5328 const TestInfo* const test_info = GetTestInfo("result");
5329
5330 // Initially, there is no TestPartResult for this test.
5331 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5332
5333 // After the previous assertion, there is still none.
5334 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5335}
5336
5337#define VERIFY_CODE_LOCATION \
5338 const int expected_line = __LINE__ - 1; \
5339 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5340 ASSERT_TRUE(test_info); \
5341 EXPECT_STREQ(__FILE__, test_info->file()); \
5342 EXPECT_EQ(expected_line, test_info->line())
5343
5344TEST(CodeLocationForTEST, Verify) {
5345 VERIFY_CODE_LOCATION;
5346}
5347
5348class CodeLocationForTESTF : public Test {
5349};
5350
5351TEST_F(CodeLocationForTESTF, Verify) {
5352 VERIFY_CODE_LOCATION;
5353}
5354
5355class CodeLocationForTESTP : public TestWithParam<int> {
5356};
5357
5358TEST_P(CodeLocationForTESTP, Verify) {
5359 VERIFY_CODE_LOCATION;
5360}
5361
5362INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0));
5363
5364template <typename T>
5365class CodeLocationForTYPEDTEST : public Test {
5366};
5367
5368TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int);
5369
5370TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5371 VERIFY_CODE_LOCATION;
5372}
5373
5374template <typename T>
5375class CodeLocationForTYPEDTESTP : public Test {
5376};
5377
5378TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP);
5379
5380TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5381 VERIFY_CODE_LOCATION;
5382}
5383
5384REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify);
5385
5386INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int);
5387
5388#undef VERIFY_CODE_LOCATION
5389
5390// Tests setting up and tearing down a test case.
5391
5392class SetUpTestCaseTest : public Test {
5393 protected:
5394 // This will be called once before the first test in this test case
5395 // is run.
5396 static void SetUpTestCase() {
5397 printf("Setting up the test case . . .\n");
5398
5399 // Initializes some shared resource. In this simple example, we
5400 // just create a C string. More complex stuff can be done if
5401 // desired.
5402 shared_resource_ = "123";
5403
5404 // Increments the number of test cases that have been set up.
5405 counter_++;
5406
5407 // SetUpTestCase() should be called only once.
5408 EXPECT_EQ(1, counter_);
5409 }
5410
5411 // This will be called once after the last test in this test case is
5412 // run.
5413 static void TearDownTestCase() {
5414 printf("Tearing down the test case . . .\n");
5415
5416 // Decrements the number of test cases that have been set up.
5417 counter_--;
5418
5419 // TearDownTestCase() should be called only once.
5420 EXPECT_EQ(0, counter_);
5421
5422 // Cleans up the shared resource.
5423 shared_resource_ = NULL;
5424 }
5425
5426 // This will be called before each test in this test case.
5427 virtual void SetUp() {
5428 // SetUpTestCase() should be called only once, so counter_ should
5429 // always be 1.
5430 EXPECT_EQ(1, counter_);
5431 }
5432
5433 // Number of test cases that have been set up.
5434 static int counter_;
5435
5436 // Some resource to be shared by all tests in this test case.
5437 static const char* shared_resource_;
5438};
5439
5440int SetUpTestCaseTest::counter_ = 0;
5441const char* SetUpTestCaseTest::shared_resource_ = NULL;
5442
5443// A test that uses the shared resource.
5444TEST_F(SetUpTestCaseTest, Test1) {
5445 EXPECT_STRNE(NULL, shared_resource_);
5446}
5447
5448// Another test that uses the shared resource.
5449TEST_F(SetUpTestCaseTest, Test2) {
5450 EXPECT_STREQ("123", shared_resource_);
5451}
5452
5453// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5454
5455// The Flags struct stores a copy of all Google Test flags.
5456struct Flags {
5457 // Constructs a Flags struct where each flag has its default value.
5458 Flags() : also_run_disabled_tests(false),
5459 break_on_failure(false),
5460 catch_exceptions(false),
5461 death_test_use_fork(false),
5462 filter(""),
5463 list_tests(false),
5464 output(""),
5465 print_time(true),
5466 random_seed(0),
5467 repeat(1),
5468 shuffle(false),
5469 stack_trace_depth(kMaxStackTraceDepth),
5470 stream_result_to(""),
5471 throw_on_failure(false) {}
5472
5473 // Factory methods.
5474
5475 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5476 // the given value.
5477 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5478 Flags flags;
5479 flags.also_run_disabled_tests = also_run_disabled_tests;
5480 return flags;
5481 }
5482
5483 // Creates a Flags struct where the gtest_break_on_failure flag has
5484 // the given value.
5485 static Flags BreakOnFailure(bool break_on_failure) {
5486 Flags flags;
5487 flags.break_on_failure = break_on_failure;
5488 return flags;
5489 }
5490
5491 // Creates a Flags struct where the gtest_catch_exceptions flag has
5492 // the given value.
5493 static Flags CatchExceptions(bool catch_exceptions) {
5494 Flags flags;
5495 flags.catch_exceptions = catch_exceptions;
5496 return flags;
5497 }
5498
5499 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5500 // the given value.
5501 static Flags DeathTestUseFork(bool death_test_use_fork) {
5502 Flags flags;
5503 flags.death_test_use_fork = death_test_use_fork;
5504 return flags;
5505 }
5506
5507 // Creates a Flags struct where the gtest_filter flag has the given
5508 // value.
5509 static Flags Filter(const char* filter) {
5510 Flags flags;
5511 flags.filter = filter;
5512 return flags;
5513 }
5514
5515 // Creates a Flags struct where the gtest_list_tests flag has the
5516 // given value.
5517 static Flags ListTests(bool list_tests) {
5518 Flags flags;
5519 flags.list_tests = list_tests;
5520 return flags;
5521 }
5522
5523 // Creates a Flags struct where the gtest_output flag has the given
5524 // value.
5525 static Flags Output(const char* output) {
5526 Flags flags;
5527 flags.output = output;
5528 return flags;
5529 }
5530
5531 // Creates a Flags struct where the gtest_print_time flag has the given
5532 // value.
5533 static Flags PrintTime(bool print_time) {
5534 Flags flags;
5535 flags.print_time = print_time;
5536 return flags;
5537 }
5538
5539 // Creates a Flags struct where the gtest_random_seed flag has
5540 // the given value.
5541 static Flags RandomSeed(Int32 random_seed) {
5542 Flags flags;
5543 flags.random_seed = random_seed;
5544 return flags;
5545 }
5546
5547 // Creates a Flags struct where the gtest_repeat flag has the given
5548 // value.
5549 static Flags Repeat(Int32 repeat) {
5550 Flags flags;
5551 flags.repeat = repeat;
5552 return flags;
5553 }
5554
5555 // Creates a Flags struct where the gtest_shuffle flag has
5556 // the given value.
5557 static Flags Shuffle(bool shuffle) {
5558 Flags flags;
5559 flags.shuffle = shuffle;
5560 return flags;
5561 }
5562
5563 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5564 // the given value.
5565 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5566 Flags flags;
5567 flags.stack_trace_depth = stack_trace_depth;
5568 return flags;
5569 }
5570
5571 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5572 // the given value.
5573 static Flags StreamResultTo(const char* stream_result_to) {
5574 Flags flags;
5575 flags.stream_result_to = stream_result_to;
5576 return flags;
5577 }
5578
5579 // Creates a Flags struct where the gtest_throw_on_failure flag has
5580 // the given value.
5581 static Flags ThrowOnFailure(bool throw_on_failure) {
5582 Flags flags;
5583 flags.throw_on_failure = throw_on_failure;
5584 return flags;
5585 }
5586
5587 // These fields store the flag values.
5588 bool also_run_disabled_tests;
5589 bool break_on_failure;
5590 bool catch_exceptions;
5591 bool death_test_use_fork;
5592 const char* filter;
5593 bool list_tests;
5594 const char* output;
5595 bool print_time;
5596 Int32 random_seed;
5597 Int32 repeat;
5598 bool shuffle;
5599 Int32 stack_trace_depth;
5600 const char* stream_result_to;
5601 bool throw_on_failure;
5602};
5603
5604// Fixture for testing InitGoogleTest().
5605class InitGoogleTestTest : public Test {
5606 protected:
5607 // Clears the flags before each test.
5608 virtual void SetUp() {
5609 GTEST_FLAG(also_run_disabled_tests) = false;
5610 GTEST_FLAG(break_on_failure) = false;
5611 GTEST_FLAG(catch_exceptions) = false;
5612 GTEST_FLAG(death_test_use_fork) = false;
5613 GTEST_FLAG(filter) = "";
5614 GTEST_FLAG(list_tests) = false;
5615 GTEST_FLAG(output) = "";
5616 GTEST_FLAG(print_time) = true;
5617 GTEST_FLAG(random_seed) = 0;
5618 GTEST_FLAG(repeat) = 1;
5619 GTEST_FLAG(shuffle) = false;
5620 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5621 GTEST_FLAG(stream_result_to) = "";
5622 GTEST_FLAG(throw_on_failure) = false;
5623 }
5624
5625 // Asserts that two narrow or wide string arrays are equal.
5626 template <typename CharType>
5627 static void AssertStringArrayEq(size_t size1, CharType** array1,
5628 size_t size2, CharType** array2) {
5629 ASSERT_EQ(size1, size2) << " Array sizes different.";
5630
5631 for (size_t i = 0; i != size1; i++) {
5632 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5633 }
5634 }
5635
5636 // Verifies that the flag values match the expected values.
5637 static void CheckFlags(const Flags& expected) {
5638 EXPECT_EQ(expected.also_run_disabled_tests,
5639 GTEST_FLAG(also_run_disabled_tests));
5640 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5641 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5642 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5643 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5644 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5645 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5646 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5647 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5648 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5649 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5650 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5651 EXPECT_STREQ(expected.stream_result_to,
5652 GTEST_FLAG(stream_result_to).c_str());
5653 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5654 }
5655
5656 // Parses a command line (specified by argc1 and argv1), then
5657 // verifies that the flag values are expected and that the
5658 // recognized flags are removed from the command line.
5659 template <typename CharType>
5660 static void TestParsingFlags(int argc1, const CharType** argv1,
5661 int argc2, const CharType** argv2,
5662 const Flags& expected, bool should_print_help) {
5663 const bool saved_help_flag = ::testing::internal::g_help_flag;
5664 ::testing::internal::g_help_flag = false;
5665
5666#if GTEST_HAS_STREAM_REDIRECTION
5667 CaptureStdout();
5668#endif
5669
5670 // Parses the command line.
5671 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5672
5673#if GTEST_HAS_STREAM_REDIRECTION
5674 const std::string captured_stdout = GetCapturedStdout();
5675#endif
5676
5677 // Verifies the flag values.
5678 CheckFlags(expected);
5679
5680 // Verifies that the recognized flags are removed from the command
5681 // line.
5682 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5683
5684 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5685 // help message for the flags it recognizes.
5686 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5687
5688#if GTEST_HAS_STREAM_REDIRECTION
5689 const char* const expected_help_fragment =
5690 "This program contains tests written using";
5691 if (should_print_help) {
5692 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5693 } else {
5694 EXPECT_PRED_FORMAT2(IsNotSubstring,
5695 expected_help_fragment, captured_stdout);
5696 }
5697#endif // GTEST_HAS_STREAM_REDIRECTION
5698
5699 ::testing::internal::g_help_flag = saved_help_flag;
5700 }
5701
5702 // This macro wraps TestParsingFlags s.t. the user doesn't need
5703 // to specify the array sizes.
5704
5705#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5706 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5707 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5708 expected, should_print_help)
5709};
5710
5711// Tests parsing an empty command line.
5712TEST_F(InitGoogleTestTest, Empty) {
5713 const char* argv[] = {
5714 NULL
5715 };
5716
5717 const char* argv2[] = {
5718 NULL
5719 };
5720
5721 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5722}
5723
5724// Tests parsing a command line that has no flag.
5725TEST_F(InitGoogleTestTest, NoFlag) {
5726 const char* argv[] = {
5727 "foo.exe",
5728 NULL
5729 };
5730
5731 const char* argv2[] = {
5732 "foo.exe",
5733 NULL
5734 };
5735
5736 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5737}
5738
5739// Tests parsing a bad --gtest_filter flag.
5740TEST_F(InitGoogleTestTest, FilterBad) {
5741 const char* argv[] = {
5742 "foo.exe",
5743 "--gtest_filter",
5744 NULL
5745 };
5746
5747 const char* argv2[] = {
5748 "foo.exe",
5749 "--gtest_filter",
5750 NULL
5751 };
5752
5753 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5754}
5755
5756// Tests parsing an empty --gtest_filter flag.
5757TEST_F(InitGoogleTestTest, FilterEmpty) {
5758 const char* argv[] = {
5759 "foo.exe",
5760 "--gtest_filter=",
5761 NULL
5762 };
5763
5764 const char* argv2[] = {
5765 "foo.exe",
5766 NULL
5767 };
5768
5769 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5770}
5771
5772// Tests parsing a non-empty --gtest_filter flag.
5773TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5774 const char* argv[] = {
5775 "foo.exe",
5776 "--gtest_filter=abc",
5777 NULL
5778 };
5779
5780 const char* argv2[] = {
5781 "foo.exe",
5782 NULL
5783 };
5784
5785 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5786}
5787
5788// Tests parsing --gtest_break_on_failure.
5789TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
5790 const char* argv[] = {
5791 "foo.exe",
5792 "--gtest_break_on_failure",
5793 NULL
5794};
5795
5796 const char* argv2[] = {
5797 "foo.exe",
5798 NULL
5799 };
5800
5801 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5802}
5803
5804// Tests parsing --gtest_break_on_failure=0.
5805TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5806 const char* argv[] = {
5807 "foo.exe",
5808 "--gtest_break_on_failure=0",
5809 NULL
5810 };
5811
5812 const char* argv2[] = {
5813 "foo.exe",
5814 NULL
5815 };
5816
5817 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5818}
5819
5820// Tests parsing --gtest_break_on_failure=f.
5821TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5822 const char* argv[] = {
5823 "foo.exe",
5824 "--gtest_break_on_failure=f",
5825 NULL
5826 };
5827
5828 const char* argv2[] = {
5829 "foo.exe",
5830 NULL
5831 };
5832
5833 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5834}
5835
5836// Tests parsing --gtest_break_on_failure=F.
5837TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5838 const char* argv[] = {
5839 "foo.exe",
5840 "--gtest_break_on_failure=F",
5841 NULL
5842 };
5843
5844 const char* argv2[] = {
5845 "foo.exe",
5846 NULL
5847 };
5848
5849 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5850}
5851
5852// Tests parsing a --gtest_break_on_failure flag that has a "true"
5853// definition.
5854TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5855 const char* argv[] = {
5856 "foo.exe",
5857 "--gtest_break_on_failure=1",
5858 NULL
5859 };
5860
5861 const char* argv2[] = {
5862 "foo.exe",
5863 NULL
5864 };
5865
5866 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5867}
5868
5869// Tests parsing --gtest_catch_exceptions.
5870TEST_F(InitGoogleTestTest, CatchExceptions) {
5871 const char* argv[] = {
5872 "foo.exe",
5873 "--gtest_catch_exceptions",
5874 NULL
5875 };
5876
5877 const char* argv2[] = {
5878 "foo.exe",
5879 NULL
5880 };
5881
5882 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5883}
5884
5885// Tests parsing --gtest_death_test_use_fork.
5886TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5887 const char* argv[] = {
5888 "foo.exe",
5889 "--gtest_death_test_use_fork",
5890 NULL
5891 };
5892
5893 const char* argv2[] = {
5894 "foo.exe",
5895 NULL
5896 };
5897
5898 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5899}
5900
5901// Tests having the same flag twice with different values. The
5902// expected behavior is that the one coming last takes precedence.
5903TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5904 const char* argv[] = {
5905 "foo.exe",
5906 "--gtest_filter=a",
5907 "--gtest_filter=b",
5908 NULL
5909 };
5910
5911 const char* argv2[] = {
5912 "foo.exe",
5913 NULL
5914 };
5915
5916 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5917}
5918
5919// Tests having an unrecognized flag on the command line.
5920TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5921 const char* argv[] = {
5922 "foo.exe",
5923 "--gtest_break_on_failure",
5924 "bar", // Unrecognized by Google Test.
5925 "--gtest_filter=b",
5926 NULL
5927 };
5928
5929 const char* argv2[] = {
5930 "foo.exe",
5931 "bar",
5932 NULL
5933 };
5934
5935 Flags flags;
5936 flags.break_on_failure = true;
5937 flags.filter = "b";
5938 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5939}
5940
5941// Tests having a --gtest_list_tests flag
5942TEST_F(InitGoogleTestTest, ListTestsFlag) {
5943 const char* argv[] = {
5944 "foo.exe",
5945 "--gtest_list_tests",
5946 NULL
5947 };
5948
5949 const char* argv2[] = {
5950 "foo.exe",
5951 NULL
5952 };
5953
5954 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5955}
5956
5957// Tests having a --gtest_list_tests flag with a "true" value
5958TEST_F(InitGoogleTestTest, ListTestsTrue) {
5959 const char* argv[] = {
5960 "foo.exe",
5961 "--gtest_list_tests=1",
5962 NULL
5963 };
5964
5965 const char* argv2[] = {
5966 "foo.exe",
5967 NULL
5968 };
5969
5970 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5971}
5972
5973// Tests having a --gtest_list_tests flag with a "false" value
5974TEST_F(InitGoogleTestTest, ListTestsFalse) {
5975 const char* argv[] = {
5976 "foo.exe",
5977 "--gtest_list_tests=0",
5978 NULL
5979 };
5980
5981 const char* argv2[] = {
5982 "foo.exe",
5983 NULL
5984 };
5985
5986 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5987}
5988
5989// Tests parsing --gtest_list_tests=f.
5990TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5991 const char* argv[] = {
5992 "foo.exe",
5993 "--gtest_list_tests=f",
5994 NULL
5995 };
5996
5997 const char* argv2[] = {
5998 "foo.exe",
5999 NULL
6000 };
6001
6002 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6003}
6004
6005// Tests parsing --gtest_list_tests=F.
6006TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
6007 const char* argv[] = {
6008 "foo.exe",
6009 "--gtest_list_tests=F",
6010 NULL
6011 };
6012
6013 const char* argv2[] = {
6014 "foo.exe",
6015 NULL
6016 };
6017
6018 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6019}
6020
6021// Tests parsing --gtest_output (invalid).
6022TEST_F(InitGoogleTestTest, OutputEmpty) {
6023 const char* argv[] = {
6024 "foo.exe",
6025 "--gtest_output",
6026 NULL
6027 };
6028
6029 const char* argv2[] = {
6030 "foo.exe",
6031 "--gtest_output",
6032 NULL
6033 };
6034
6035 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6036}
6037
6038// Tests parsing --gtest_output=xml
6039TEST_F(InitGoogleTestTest, OutputXml) {
6040 const char* argv[] = {
6041 "foo.exe",
6042 "--gtest_output=xml",
6043 NULL
6044 };
6045
6046 const char* argv2[] = {
6047 "foo.exe",
6048 NULL
6049 };
6050
6051 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6052}
6053
6054// Tests parsing --gtest_output=xml:file
6055TEST_F(InitGoogleTestTest, OutputXmlFile) {
6056 const char* argv[] = {
6057 "foo.exe",
6058 "--gtest_output=xml:file",
6059 NULL
6060 };
6061
6062 const char* argv2[] = {
6063 "foo.exe",
6064 NULL
6065 };
6066
6067 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6068}
6069
6070// Tests parsing --gtest_output=xml:directory/path/
6071TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
6072 const char* argv[] = {
6073 "foo.exe",
6074 "--gtest_output=xml:directory/path/",
6075 NULL
6076 };
6077
6078 const char* argv2[] = {
6079 "foo.exe",
6080 NULL
6081 };
6082
6083 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6084 Flags::Output("xml:directory/path/"), false);
6085}
6086
6087// Tests having a --gtest_print_time flag
6088TEST_F(InitGoogleTestTest, PrintTimeFlag) {
6089 const char* argv[] = {
6090 "foo.exe",
6091 "--gtest_print_time",
6092 NULL
6093 };
6094
6095 const char* argv2[] = {
6096 "foo.exe",
6097 NULL
6098 };
6099
6100 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6101}
6102
6103// Tests having a --gtest_print_time flag with a "true" value
6104TEST_F(InitGoogleTestTest, PrintTimeTrue) {
6105 const char* argv[] = {
6106 "foo.exe",
6107 "--gtest_print_time=1",
6108 NULL
6109 };
6110
6111 const char* argv2[] = {
6112 "foo.exe",
6113 NULL
6114 };
6115
6116 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6117}
6118
6119// Tests having a --gtest_print_time flag with a "false" value
6120TEST_F(InitGoogleTestTest, PrintTimeFalse) {
6121 const char* argv[] = {
6122 "foo.exe",
6123 "--gtest_print_time=0",
6124 NULL
6125 };
6126
6127 const char* argv2[] = {
6128 "foo.exe",
6129 NULL
6130 };
6131
6132 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6133}
6134
6135// Tests parsing --gtest_print_time=f.
6136TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
6137 const char* argv[] = {
6138 "foo.exe",
6139 "--gtest_print_time=f",
6140 NULL
6141 };
6142
6143 const char* argv2[] = {
6144 "foo.exe",
6145 NULL
6146 };
6147
6148 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6149}
6150
6151// Tests parsing --gtest_print_time=F.
6152TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
6153 const char* argv[] = {
6154 "foo.exe",
6155 "--gtest_print_time=F",
6156 NULL
6157 };
6158
6159 const char* argv2[] = {
6160 "foo.exe",
6161 NULL
6162 };
6163
6164 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6165}
6166
6167// Tests parsing --gtest_random_seed=number
6168TEST_F(InitGoogleTestTest, RandomSeed) {
6169 const char* argv[] = {
6170 "foo.exe",
6171 "--gtest_random_seed=1000",
6172 NULL
6173 };
6174
6175 const char* argv2[] = {
6176 "foo.exe",
6177 NULL
6178 };
6179
6180 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6181}
6182
6183// Tests parsing --gtest_repeat=number
6184TEST_F(InitGoogleTestTest, Repeat) {
6185 const char* argv[] = {
6186 "foo.exe",
6187 "--gtest_repeat=1000",
6188 NULL
6189 };
6190
6191 const char* argv2[] = {
6192 "foo.exe",
6193 NULL
6194 };
6195
6196 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6197}
6198
6199// Tests having a --gtest_also_run_disabled_tests flag
6200TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6201 const char* argv[] = {
6202 "foo.exe",
6203 "--gtest_also_run_disabled_tests",
6204 NULL
6205 };
6206
6207 const char* argv2[] = {
6208 "foo.exe",
6209 NULL
6210 };
6211
6212 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6213 Flags::AlsoRunDisabledTests(true), false);
6214}
6215
6216// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6217TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6218 const char* argv[] = {
6219 "foo.exe",
6220 "--gtest_also_run_disabled_tests=1",
6221 NULL
6222 };
6223
6224 const char* argv2[] = {
6225 "foo.exe",
6226 NULL
6227 };
6228
6229 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6230 Flags::AlsoRunDisabledTests(true), false);
6231}
6232
6233// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6234TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6235 const char* argv[] = {
6236 "foo.exe",
6237 "--gtest_also_run_disabled_tests=0",
6238 NULL
6239 };
6240
6241 const char* argv2[] = {
6242 "foo.exe",
6243 NULL
6244 };
6245
6246 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6247 Flags::AlsoRunDisabledTests(false), false);
6248}
6249
6250// Tests parsing --gtest_shuffle.
6251TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6252 const char* argv[] = {
6253 "foo.exe",
6254 "--gtest_shuffle",
6255 NULL
6256};
6257
6258 const char* argv2[] = {
6259 "foo.exe",
6260 NULL
6261 };
6262
6263 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6264}
6265
6266// Tests parsing --gtest_shuffle=0.
6267TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6268 const char* argv[] = {
6269 "foo.exe",
6270 "--gtest_shuffle=0",
6271 NULL
6272 };
6273
6274 const char* argv2[] = {
6275 "foo.exe",
6276 NULL
6277 };
6278
6279 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6280}
6281
6282// Tests parsing a --gtest_shuffle flag that has a "true"
6283// definition.
6284TEST_F(InitGoogleTestTest, ShuffleTrue) {
6285 const char* argv[] = {
6286 "foo.exe",
6287 "--gtest_shuffle=1",
6288 NULL
6289 };
6290
6291 const char* argv2[] = {
6292 "foo.exe",
6293 NULL
6294 };
6295
6296 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6297}
6298
6299// Tests parsing --gtest_stack_trace_depth=number.
6300TEST_F(InitGoogleTestTest, StackTraceDepth) {
6301 const char* argv[] = {
6302 "foo.exe",
6303 "--gtest_stack_trace_depth=5",
6304 NULL
6305 };
6306
6307 const char* argv2[] = {
6308 "foo.exe",
6309 NULL
6310 };
6311
6312 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6313}
6314
6315TEST_F(InitGoogleTestTest, StreamResultTo) {
6316 const char* argv[] = {
6317 "foo.exe",
6318 "--gtest_stream_result_to=localhost:1234",
6319 NULL
6320 };
6321
6322 const char* argv2[] = {
6323 "foo.exe",
6324 NULL
6325 };
6326
6327 GTEST_TEST_PARSING_FLAGS_(
6328 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6329}
6330
6331// Tests parsing --gtest_throw_on_failure.
6332TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
6333 const char* argv[] = {
6334 "foo.exe",
6335 "--gtest_throw_on_failure",
6336 NULL
6337};
6338
6339 const char* argv2[] = {
6340 "foo.exe",
6341 NULL
6342 };
6343
6344 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6345}
6346
6347// Tests parsing --gtest_throw_on_failure=0.
6348TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6349 const char* argv[] = {
6350 "foo.exe",
6351 "--gtest_throw_on_failure=0",
6352 NULL
6353 };
6354
6355 const char* argv2[] = {
6356 "foo.exe",
6357 NULL
6358 };
6359
6360 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6361}
6362
6363// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6364// definition.
6365TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6366 const char* argv[] = {
6367 "foo.exe",
6368 "--gtest_throw_on_failure=1",
6369 NULL
6370 };
6371
6372 const char* argv2[] = {
6373 "foo.exe",
6374 NULL
6375 };
6376
6377 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6378}
6379
6380#if GTEST_OS_WINDOWS
6381// Tests parsing wide strings.
6382TEST_F(InitGoogleTestTest, WideStrings) {
6383 const wchar_t* argv[] = {
6384 L"foo.exe",
6385 L"--gtest_filter=Foo*",
6386 L"--gtest_list_tests=1",
6387 L"--gtest_break_on_failure",
6388 L"--non_gtest_flag",
6389 NULL
6390 };
6391
6392 const wchar_t* argv2[] = {
6393 L"foo.exe",
6394 L"--non_gtest_flag",
6395 NULL
6396 };
6397
6398 Flags expected_flags;
6399 expected_flags.break_on_failure = true;
6400 expected_flags.filter = "Foo*";
6401 expected_flags.list_tests = true;
6402
6403 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6404}
6405# endif // GTEST_OS_WINDOWS
6406
6407#if GTEST_USE_OWN_FLAGFILE_FLAG_
6408class FlagfileTest : public InitGoogleTestTest {
6409 public:
6410 virtual void SetUp() {
6411 InitGoogleTestTest::SetUp();
6412
6413 testdata_path_.Set(internal::FilePath(
6414 internal::TempDir() + internal::GetCurrentExecutableName().string() +
6415 "_flagfile_test"));
6416 testing::internal::posix::RmDir(testdata_path_.c_str());
6417 EXPECT_TRUE(testdata_path_.CreateFolder());
6418 }
6419
6420 virtual void TearDown() {
6421 testing::internal::posix::RmDir(testdata_path_.c_str());
6422 InitGoogleTestTest::TearDown();
6423 }
6424
6425 internal::FilePath CreateFlagfile(const char* contents) {
6426 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6427 testdata_path_, internal::FilePath("unique"), "txt"));
6428 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6429 fprintf(f, "%s", contents);
6430 fclose(f);
6431 return file_path;
6432 }
6433
6434 private:
6435 internal::FilePath testdata_path_;
6436};
6437
6438// Tests an empty flagfile.
6439TEST_F(FlagfileTest, Empty) {
6440 internal::FilePath flagfile_path(CreateFlagfile(""));
6441 std::string flagfile_flag =
6442 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6443
6444 const char* argv[] = {
6445 "foo.exe",
6446 flagfile_flag.c_str(),
6447 NULL
6448 };
6449
6450 const char* argv2[] = {
6451 "foo.exe",
6452 NULL
6453 };
6454
6455 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6456}
6457
6458// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6459TEST_F(FlagfileTest, FilterNonEmpty) {
6460 internal::FilePath flagfile_path(CreateFlagfile(
6461 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6462 std::string flagfile_flag =
6463 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6464
6465 const char* argv[] = {
6466 "foo.exe",
6467 flagfile_flag.c_str(),
6468 NULL
6469 };
6470
6471 const char* argv2[] = {
6472 "foo.exe",
6473 NULL
6474 };
6475
6476 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6477}
6478
6479// Tests passing several flags via --gtest_flagfile.
6480TEST_F(FlagfileTest, SeveralFlags) {
6481 internal::FilePath flagfile_path(CreateFlagfile(
6482 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6483 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6484 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6485 std::string flagfile_flag =
6486 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6487
6488 const char* argv[] = {
6489 "foo.exe",
6490 flagfile_flag.c_str(),
6491 NULL
6492 };
6493
6494 const char* argv2[] = {
6495 "foo.exe",
6496 NULL
6497 };
6498
6499 Flags expected_flags;
6500 expected_flags.break_on_failure = true;
6501 expected_flags.filter = "abc";
6502 expected_flags.list_tests = true;
6503
6504 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6505}
6506#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6507
6508// Tests current_test_info() in UnitTest.
6509class CurrentTestInfoTest : public Test {
6510 protected:
6511 // Tests that current_test_info() returns NULL before the first test in
6512 // the test case is run.
6513 static void SetUpTestCase() {
6514 // There should be no tests running at this point.
6515 const TestInfo* test_info =
6516 UnitTest::GetInstance()->current_test_info();
6517 EXPECT_TRUE(test_info == NULL)
6518 << "There should be no tests running at this point.";
6519 }
6520
6521 // Tests that current_test_info() returns NULL after the last test in
6522 // the test case has run.
6523 static void TearDownTestCase() {
6524 const TestInfo* test_info =
6525 UnitTest::GetInstance()->current_test_info();
6526 EXPECT_TRUE(test_info == NULL)
6527 << "There should be no tests running at this point.";
6528 }
6529};
6530
6531// Tests that current_test_info() returns TestInfo for currently running
6532// test by checking the expected test name against the actual one.
6533TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6534 const TestInfo* test_info =
6535 UnitTest::GetInstance()->current_test_info();
6536 ASSERT_TRUE(NULL != test_info)
6537 << "There is a test running so we should have a valid TestInfo.";
6538 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6539 << "Expected the name of the currently running test case.";
6540 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6541 << "Expected the name of the currently running test.";
6542}
6543
6544// Tests that current_test_info() returns TestInfo for currently running
6545// test by checking the expected test name against the actual one. We
6546// use this test to see that the TestInfo object actually changed from
6547// the previous invocation.
6548TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6549 const TestInfo* test_info =
6550 UnitTest::GetInstance()->current_test_info();
6551 ASSERT_TRUE(NULL != test_info)
6552 << "There is a test running so we should have a valid TestInfo.";
6553 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6554 << "Expected the name of the currently running test case.";
6555 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6556 << "Expected the name of the currently running test.";
6557}
6558
6559} // namespace testing
6560
6561// These two lines test that we can define tests in a namespace that
6562// has the name "testing" and is nested in another namespace.
6563namespace my_namespace {
6564namespace testing {
6565
6566// Makes sure that TEST knows to use ::testing::Test instead of
6567// ::my_namespace::testing::Test.
6568class Test {};
6569
6570// Makes sure that an assertion knows to use ::testing::Message instead of
6571// ::my_namespace::testing::Message.
6572class Message {};
6573
6574// Makes sure that an assertion knows to use
6575// ::testing::AssertionResult instead of
6576// ::my_namespace::testing::AssertionResult.
6577class AssertionResult {};
6578
6579// Tests that an assertion that should succeed works as expected.
6580TEST(NestedTestingNamespaceTest, Success) {
6581 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6582}
6583
6584// Tests that an assertion that should fail works as expected.
6585TEST(NestedTestingNamespaceTest, Failure) {
6586 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6587 "This failure is expected.");
6588}
6589
6590} // namespace testing
6591} // namespace my_namespace
6592
6593// Tests that one can call superclass SetUp and TearDown methods--
6594// that is, that they are not private.
6595// No tests are based on this fixture; the test "passes" if it compiles
6596// successfully.
6597class ProtectedFixtureMethodsTest : public Test {
6598 protected:
6599 virtual void SetUp() {
6600 Test::SetUp();
6601 }
6602 virtual void TearDown() {
6603 Test::TearDown();
6604 }
6605};
6606
6607// StreamingAssertionsTest tests the streaming versions of a representative
6608// sample of assertions.
6609TEST(StreamingAssertionsTest, Unconditional) {
6610 SUCCEED() << "expected success";
6611 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6612 "expected failure");
6613 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6614 "expected failure");
6615}
6616
6617#ifdef __BORLANDC__
6618// Silences warnings: "Condition is always true", "Unreachable code"
6619# pragma option push -w-ccc -w-rch
6620#endif
6621
6622TEST(StreamingAssertionsTest, Truth) {
6623 EXPECT_TRUE(true) << "unexpected failure";
6624 ASSERT_TRUE(true) << "unexpected failure";
6625 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6626 "expected failure");
6627 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6628 "expected failure");
6629}
6630
6631TEST(StreamingAssertionsTest, Truth2) {
6632 EXPECT_FALSE(false) << "unexpected failure";
6633 ASSERT_FALSE(false) << "unexpected failure";
6634 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6635 "expected failure");
6636 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6637 "expected failure");
6638}
6639
6640#ifdef __BORLANDC__
6641// Restores warnings after previous "#pragma option push" supressed them
6642# pragma option pop
6643#endif
6644
6645TEST(StreamingAssertionsTest, IntegerEquals) {
6646 EXPECT_EQ(1, 1) << "unexpected failure";
6647 ASSERT_EQ(1, 1) << "unexpected failure";
6648 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6649 "expected failure");
6650 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6651 "expected failure");
6652}
6653
6654TEST(StreamingAssertionsTest, IntegerLessThan) {
6655 EXPECT_LT(1, 2) << "unexpected failure";
6656 ASSERT_LT(1, 2) << "unexpected failure";
6657 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6658 "expected failure");
6659 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6660 "expected failure");
6661}
6662
6663TEST(StreamingAssertionsTest, StringsEqual) {
6664 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6665 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6666 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6667 "expected failure");
6668 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6669 "expected failure");
6670}
6671
6672TEST(StreamingAssertionsTest, StringsNotEqual) {
6673 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6674 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6675 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6676 "expected failure");
6677 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6678 "expected failure");
6679}
6680
6681TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6682 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6683 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6684 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6685 "expected failure");
6686 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6687 "expected failure");
6688}
6689
6690TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6691 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6692 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6693 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6694 "expected failure");
6695 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6696 "expected failure");
6697}
6698
6699TEST(StreamingAssertionsTest, FloatingPointEquals) {
6700 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6701 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6702 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6703 "expected failure");
6704 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6705 "expected failure");
6706}
6707
6708#if GTEST_HAS_EXCEPTIONS
6709
6710TEST(StreamingAssertionsTest, Throw) {
6711 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6712 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6713 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6714 "expected failure", "expected failure");
6715 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6716 "expected failure", "expected failure");
6717}
6718
6719TEST(StreamingAssertionsTest, NoThrow) {
6720 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6721 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6722 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6723 "expected failure", "expected failure");
6724 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6725 "expected failure", "expected failure");
6726}
6727
6728TEST(StreamingAssertionsTest, AnyThrow) {
6729 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6730 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6731 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6732 "expected failure", "expected failure");
6733 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6734 "expected failure", "expected failure");
6735}
6736
6737#endif // GTEST_HAS_EXCEPTIONS
6738
6739// Tests that Google Test correctly decides whether to use colors in the output.
6740
6741TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6742 GTEST_FLAG(color) = "yes";
6743
6744 SetEnv("TERM", "xterm"); // TERM supports colors.
6745 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6746 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6747
6748 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6749 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6750 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6751}
6752
6753TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6754 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6755
6756 GTEST_FLAG(color) = "True";
6757 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6758
6759 GTEST_FLAG(color) = "t";
6760 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6761
6762 GTEST_FLAG(color) = "1";
6763 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6764}
6765
6766TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6767 GTEST_FLAG(color) = "no";
6768
6769 SetEnv("TERM", "xterm"); // TERM supports colors.
6770 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6771 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6772
6773 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6774 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6775 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6776}
6777
6778TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6779 SetEnv("TERM", "xterm"); // TERM supports colors.
6780
6781 GTEST_FLAG(color) = "F";
6782 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6783
6784 GTEST_FLAG(color) = "0";
6785 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6786
6787 GTEST_FLAG(color) = "unknown";
6788 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6789}
6790
6791TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6792 GTEST_FLAG(color) = "auto";
6793
6794 SetEnv("TERM", "xterm"); // TERM supports colors.
6795 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6796 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6797}
6798
6799TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6800 GTEST_FLAG(color) = "auto";
6801
6802#if GTEST_OS_WINDOWS
6803 // On Windows, we ignore the TERM variable as it's usually not set.
6804
6805 SetEnv("TERM", "dumb");
6806 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6807
6808 SetEnv("TERM", "");
6809 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6810
6811 SetEnv("TERM", "xterm");
6812 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6813#else
6814 // On non-Windows platforms, we rely on TERM to determine if the
6815 // terminal supports colors.
6816
6817 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6818 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6819
6820 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6821 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6822
6823 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6824 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6825
6826 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6827 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6828
6829 SetEnv("TERM", "xterm"); // TERM supports colors.
6830 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6831
6832 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6833 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6834
6835 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6836 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6837
6838 SetEnv("TERM", "screen"); // TERM supports colors.
6839 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6840
6841 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6842 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6843
6844 SetEnv("TERM", "tmux"); // TERM supports colors.
6845 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6846
6847 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6848 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6849
6850 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6851 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6852
6853 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6854 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6855
6856 SetEnv("TERM", "linux"); // TERM supports colors.
6857 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6858
6859 SetEnv("TERM", "cygwin"); // TERM supports colors.
6860 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6861#endif // GTEST_OS_WINDOWS
6862}
6863
6864// Verifies that StaticAssertTypeEq works in a namespace scope.
6865
6866static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6867static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6868 StaticAssertTypeEq<const int, const int>();
6869
6870// Verifies that StaticAssertTypeEq works in a class.
6871
6872template <typename T>
6873class StaticAssertTypeEqTestHelper {
6874 public:
6875 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6876};
6877
6878TEST(StaticAssertTypeEqTest, WorksInClass) {
6879 StaticAssertTypeEqTestHelper<bool>();
6880}
6881
6882// Verifies that StaticAssertTypeEq works inside a function.
6883
6884typedef int IntAlias;
6885
6886TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6887 StaticAssertTypeEq<int, IntAlias>();
6888 StaticAssertTypeEq<int*, IntAlias*>();
6889}
6890
6891TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6892 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6893
6894 // We don't have a stack walker in Google Test yet.
6895 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6896 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6897}
6898
6899TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6900 EXPECT_FALSE(HasNonfatalFailure());
6901}
6902
6903static void FailFatally() { FAIL(); }
6904
6905TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6906 FailFatally();
6907 const bool has_nonfatal_failure = HasNonfatalFailure();
6908 ClearCurrentTestPartResults();
6909 EXPECT_FALSE(has_nonfatal_failure);
6910}
6911
6912TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6913 ADD_FAILURE();
6914 const bool has_nonfatal_failure = HasNonfatalFailure();
6915 ClearCurrentTestPartResults();
6916 EXPECT_TRUE(has_nonfatal_failure);
6917}
6918
6919TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6920 FailFatally();
6921 ADD_FAILURE();
6922 const bool has_nonfatal_failure = HasNonfatalFailure();
6923 ClearCurrentTestPartResults();
6924 EXPECT_TRUE(has_nonfatal_failure);
6925}
6926
6927// A wrapper for calling HasNonfatalFailure outside of a test body.
6928static bool HasNonfatalFailureHelper() {
6929 return testing::Test::HasNonfatalFailure();
6930}
6931
6932TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6933 EXPECT_FALSE(HasNonfatalFailureHelper());
6934}
6935
6936TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6937 ADD_FAILURE();
6938 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6939 ClearCurrentTestPartResults();
6940 EXPECT_TRUE(has_nonfatal_failure);
6941}
6942
6943TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6944 EXPECT_FALSE(HasFailure());
6945}
6946
6947TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6948 FailFatally();
6949 const bool has_failure = HasFailure();
6950 ClearCurrentTestPartResults();
6951 EXPECT_TRUE(has_failure);
6952}
6953
6954TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6955 ADD_FAILURE();
6956 const bool has_failure = HasFailure();
6957 ClearCurrentTestPartResults();
6958 EXPECT_TRUE(has_failure);
6959}
6960
6961TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6962 FailFatally();
6963 ADD_FAILURE();
6964 const bool has_failure = HasFailure();
6965 ClearCurrentTestPartResults();
6966 EXPECT_TRUE(has_failure);
6967}
6968
6969// A wrapper for calling HasFailure outside of a test body.
6970static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6971
6972TEST(HasFailureTest, WorksOutsideOfTestBody) {
6973 EXPECT_FALSE(HasFailureHelper());
6974}
6975
6976TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6977 ADD_FAILURE();
6978 const bool has_failure = HasFailureHelper();
6979 ClearCurrentTestPartResults();
6980 EXPECT_TRUE(has_failure);
6981}
6982
6983class TestListener : public EmptyTestEventListener {
6984 public:
6985 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6986 TestListener(int* on_start_counter, bool* is_destroyed)
6987 : on_start_counter_(on_start_counter),
6988 is_destroyed_(is_destroyed) {}
6989
6990 virtual ~TestListener() {
6991 if (is_destroyed_)
6992 *is_destroyed_ = true;
6993 }
6994
6995 protected:
6996 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6997 if (on_start_counter_ != NULL)
6998 (*on_start_counter_)++;
6999 }
7000
7001 private:
7002 int* on_start_counter_;
7003 bool* is_destroyed_;
7004};
7005
7006// Tests the constructor.
7007TEST(TestEventListenersTest, ConstructionWorks) {
7008 TestEventListeners listeners;
7009
7010 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
7011 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7012 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7013}
7014
7015// Tests that the TestEventListeners destructor deletes all the listeners it
7016// owns.
7017TEST(TestEventListenersTest, DestructionWorks) {
7018 bool default_result_printer_is_destroyed = false;
7019 bool default_xml_printer_is_destroyed = false;
7020 bool extra_listener_is_destroyed = false;
7021 TestListener* default_result_printer = new TestListener(
7022 NULL, &default_result_printer_is_destroyed);
7023 TestListener* default_xml_printer = new TestListener(
7024 NULL, &default_xml_printer_is_destroyed);
7025 TestListener* extra_listener = new TestListener(
7026 NULL, &extra_listener_is_destroyed);
7027
7028 {
7029 TestEventListeners listeners;
7030 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
7031 default_result_printer);
7032 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
7033 default_xml_printer);
7034 listeners.Append(extra_listener);
7035 }
7036 EXPECT_TRUE(default_result_printer_is_destroyed);
7037 EXPECT_TRUE(default_xml_printer_is_destroyed);
7038 EXPECT_TRUE(extra_listener_is_destroyed);
7039}
7040
7041// Tests that a listener Append'ed to a TestEventListeners list starts
7042// receiving events.
7043TEST(TestEventListenersTest, Append) {
7044 int on_start_counter = 0;
7045 bool is_destroyed = false;
7046 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7047 {
7048 TestEventListeners listeners;
7049 listeners.Append(listener);
7050 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7051 *UnitTest::GetInstance());
7052 EXPECT_EQ(1, on_start_counter);
7053 }
7054 EXPECT_TRUE(is_destroyed);
7055}
7056
7057// Tests that listeners receive events in the order they were appended to
7058// the list, except for *End requests, which must be received in the reverse
7059// order.
7060class SequenceTestingListener : public EmptyTestEventListener {
7061 public:
7062 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
7063 : vector_(vector), id_(id) {}
7064
7065 protected:
7066 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
7067 vector_->push_back(GetEventDescription("OnTestProgramStart"));
7068 }
7069
7070 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
7071 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
7072 }
7073
7074 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
7075 int /*iteration*/) {
7076 vector_->push_back(GetEventDescription("OnTestIterationStart"));
7077 }
7078
7079 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
7080 int /*iteration*/) {
7081 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
7082 }
7083
7084 private:
7085 std::string GetEventDescription(const char* method) {
7086 Message message;
7087 message << id_ << "." << method;
7088 return message.GetString();
7089 }
7090
7091 std::vector<std::string>* vector_;
7092 const char* const id_;
7093
7094 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
7095};
7096
7097TEST(EventListenerTest, AppendKeepsOrder) {
7098 std::vector<std::string> vec;
7099 TestEventListeners listeners;
7100 listeners.Append(new SequenceTestingListener(&vec, "1st"));
7101 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
7102 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
7103
7104 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7105 *UnitTest::GetInstance());
7106 ASSERT_EQ(3U, vec.size());
7107 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
7108 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
7109 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
7110
7111 vec.clear();
7112 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
7113 *UnitTest::GetInstance());
7114 ASSERT_EQ(3U, vec.size());
7115 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
7116 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
7117 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
7118
7119 vec.clear();
7120 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
7121 *UnitTest::GetInstance(), 0);
7122 ASSERT_EQ(3U, vec.size());
7123 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
7124 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
7125 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
7126
7127 vec.clear();
7128 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
7129 *UnitTest::GetInstance(), 0);
7130 ASSERT_EQ(3U, vec.size());
7131 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7132 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7133 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7134}
7135
7136// Tests that a listener removed from a TestEventListeners list stops receiving
7137// events and is not deleted when the list is destroyed.
7138TEST(TestEventListenersTest, Release) {
7139 int on_start_counter = 0;
7140 bool is_destroyed = false;
7141 // Although Append passes the ownership of this object to the list,
7142 // the following calls release it, and we need to delete it before the
7143 // test ends.
7144 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7145 {
7146 TestEventListeners listeners;
7147 listeners.Append(listener);
7148 EXPECT_EQ(listener, listeners.Release(listener));
7149 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7150 *UnitTest::GetInstance());
7151 EXPECT_TRUE(listeners.Release(listener) == NULL);
7152 }
7153 EXPECT_EQ(0, on_start_counter);
7154 EXPECT_FALSE(is_destroyed);
7155 delete listener;
7156}
7157
7158// Tests that no events are forwarded when event forwarding is disabled.
7159TEST(EventListenerTest, SuppressEventForwarding) {
7160 int on_start_counter = 0;
7161 TestListener* listener = new TestListener(&on_start_counter, NULL);
7162
7163 TestEventListeners listeners;
7164 listeners.Append(listener);
7165 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7166 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7167 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7168 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7169 *UnitTest::GetInstance());
7170 EXPECT_EQ(0, on_start_counter);
7171}
7172
7173// Tests that events generated by Google Test are not forwarded in
7174// death test subprocesses.
7175TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7176 EXPECT_DEATH_IF_SUPPORTED({
7177 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7178 *GetUnitTestImpl()->listeners())) << "expected failure";},
7179 "expected failure");
7180}
7181
7182// Tests that a listener installed via SetDefaultResultPrinter() starts
7183// receiving events and is returned via default_result_printer() and that
7184// the previous default_result_printer is removed from the list and deleted.
7185TEST(EventListenerTest, default_result_printer) {
7186 int on_start_counter = 0;
7187 bool is_destroyed = false;
7188 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7189
7190 TestEventListeners listeners;
7191 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7192
7193 EXPECT_EQ(listener, listeners.default_result_printer());
7194
7195 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7196 *UnitTest::GetInstance());
7197
7198 EXPECT_EQ(1, on_start_counter);
7199
7200 // Replacing default_result_printer with something else should remove it
7201 // from the list and destroy it.
7202 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
7203
7204 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7205 EXPECT_TRUE(is_destroyed);
7206
7207 // After broadcasting an event the counter is still the same, indicating
7208 // the listener is not in the list anymore.
7209 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7210 *UnitTest::GetInstance());
7211 EXPECT_EQ(1, on_start_counter);
7212}
7213
7214// Tests that the default_result_printer listener stops receiving events
7215// when removed via Release and that is not owned by the list anymore.
7216TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7217 int on_start_counter = 0;
7218 bool is_destroyed = false;
7219 // Although Append passes the ownership of this object to the list,
7220 // the following calls release it, and we need to delete it before the
7221 // test ends.
7222 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7223 {
7224 TestEventListeners listeners;
7225 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7226
7227 EXPECT_EQ(listener, listeners.Release(listener));
7228 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7229 EXPECT_FALSE(is_destroyed);
7230
7231 // Broadcasting events now should not affect default_result_printer.
7232 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7233 *UnitTest::GetInstance());
7234 EXPECT_EQ(0, on_start_counter);
7235 }
7236 // Destroying the list should not affect the listener now, too.
7237 EXPECT_FALSE(is_destroyed);
7238 delete listener;
7239}
7240
7241// Tests that a listener installed via SetDefaultXmlGenerator() starts
7242// receiving events and is returned via default_xml_generator() and that
7243// the previous default_xml_generator is removed from the list and deleted.
7244TEST(EventListenerTest, default_xml_generator) {
7245 int on_start_counter = 0;
7246 bool is_destroyed = false;
7247 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7248
7249 TestEventListeners listeners;
7250 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7251
7252 EXPECT_EQ(listener, listeners.default_xml_generator());
7253
7254 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7255 *UnitTest::GetInstance());
7256
7257 EXPECT_EQ(1, on_start_counter);
7258
7259 // Replacing default_xml_generator with something else should remove it
7260 // from the list and destroy it.
7261 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
7262
7263 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7264 EXPECT_TRUE(is_destroyed);
7265
7266 // After broadcasting an event the counter is still the same, indicating
7267 // the listener is not in the list anymore.
7268 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7269 *UnitTest::GetInstance());
7270 EXPECT_EQ(1, on_start_counter);
7271}
7272
7273// Tests that the default_xml_generator listener stops receiving events
7274// when removed via Release and that is not owned by the list anymore.
7275TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7276 int on_start_counter = 0;
7277 bool is_destroyed = false;
7278 // Although Append passes the ownership of this object to the list,
7279 // the following calls release it, and we need to delete it before the
7280 // test ends.
7281 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7282 {
7283 TestEventListeners listeners;
7284 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7285
7286 EXPECT_EQ(listener, listeners.Release(listener));
7287 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7288 EXPECT_FALSE(is_destroyed);
7289
7290 // Broadcasting events now should not affect default_xml_generator.
7291 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7292 *UnitTest::GetInstance());
7293 EXPECT_EQ(0, on_start_counter);
7294 }
7295 // Destroying the list should not affect the listener now, too.
7296 EXPECT_FALSE(is_destroyed);
7297 delete listener;
7298}
7299
7300// Sanity tests to ensure that the alternative, verbose spellings of
7301// some of the macros work. We don't test them thoroughly as that
7302// would be quite involved. Since their implementations are
7303// straightforward, and they are rarely used, we'll just rely on the
7304// users to tell us when they are broken.
7305GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7306 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7307
7308 // GTEST_FAIL is the same as FAIL.
7309 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7310 "An expected failure");
7311
7312 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7313
7314 GTEST_ASSERT_EQ(0, 0);
7315 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7316 "An expected failure");
7317 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7318 "An expected failure");
7319
7320 GTEST_ASSERT_NE(0, 1);
7321 GTEST_ASSERT_NE(1, 0);
7322 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7323 "An expected failure");
7324
7325 GTEST_ASSERT_LE(0, 0);
7326 GTEST_ASSERT_LE(0, 1);
7327 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7328 "An expected failure");
7329
7330 GTEST_ASSERT_LT(0, 1);
7331 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7332 "An expected failure");
7333 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7334 "An expected failure");
7335
7336 GTEST_ASSERT_GE(0, 0);
7337 GTEST_ASSERT_GE(1, 0);
7338 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7339 "An expected failure");
7340
7341 GTEST_ASSERT_GT(1, 0);
7342 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7343 "An expected failure");
7344 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7345 "An expected failure");
7346}
7347
7348// Tests for internal utilities necessary for implementation of the universal
7349// printing.
7350// TODO(vladl@google.com): Find a better home for them.
7351
7352class ConversionHelperBase {};
7353class ConversionHelperDerived : public ConversionHelperBase {};
7354
7355// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
7356TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
7357 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
7358 const_true);
7359 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
7360}
7361
7362// Tests that IsAProtocolMessage<T>::value is true when T is
7363// proto2::Message or a sub-class of it.
7364TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
7365 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
7366 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
7367}
7368
7369// Tests that IsAProtocolMessage<T>::value is false when T is neither
7370// ProtocolMessage nor a sub-class of it.
7371TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7372 EXPECT_FALSE(IsAProtocolMessage<int>::value);
7373 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7374}
7375
7376// Tests that CompileAssertTypesEqual compiles when the type arguments are
7377// equal.
7378TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7379 CompileAssertTypesEqual<void, void>();
7380 CompileAssertTypesEqual<int*, int*>();
7381}
7382
7383// Tests that RemoveReference does not affect non-reference types.
7384TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7385 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7386 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7387}
7388
7389// Tests that RemoveReference removes reference from reference types.
7390TEST(RemoveReferenceTest, RemovesReference) {
7391 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7392 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7393}
7394
7395// Tests GTEST_REMOVE_REFERENCE_.
7396
7397template <typename T1, typename T2>
7398void TestGTestRemoveReference() {
7399 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7400}
7401
7402TEST(RemoveReferenceTest, MacroVersion) {
7403 TestGTestRemoveReference<int, int>();
7404 TestGTestRemoveReference<const char, const char&>();
7405}
7406
7407
7408// Tests that RemoveConst does not affect non-const types.
7409TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7410 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7411 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7412}
7413
7414// Tests that RemoveConst removes const from const types.
7415TEST(RemoveConstTest, RemovesConst) {
7416 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7417 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7418 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7419}
7420
7421// Tests GTEST_REMOVE_CONST_.
7422
7423template <typename T1, typename T2>
7424void TestGTestRemoveConst() {
7425 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7426}
7427
7428TEST(RemoveConstTest, MacroVersion) {
7429 TestGTestRemoveConst<int, int>();
7430 TestGTestRemoveConst<double&, double&>();
7431 TestGTestRemoveConst<char, const char>();
7432}
7433
7434// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7435
7436template <typename T1, typename T2>
7437void TestGTestRemoveReferenceAndConst() {
7438 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7439}
7440
7441TEST(RemoveReferenceToConstTest, Works) {
7442 TestGTestRemoveReferenceAndConst<int, int>();
7443 TestGTestRemoveReferenceAndConst<double, double&>();
7444 TestGTestRemoveReferenceAndConst<char, const char>();
7445 TestGTestRemoveReferenceAndConst<char, const char&>();
7446 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7447}
7448
7449// Tests that AddReference does not affect reference types.
7450TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7451 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7452 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7453}
7454
7455// Tests that AddReference adds reference to non-reference types.
7456TEST(AddReferenceTest, AddsReference) {
7457 CompileAssertTypesEqual<int&, AddReference<int>::type>();
7458 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7459}
7460
7461// Tests GTEST_ADD_REFERENCE_.
7462
7463template <typename T1, typename T2>
7464void TestGTestAddReference() {
7465 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7466}
7467
7468TEST(AddReferenceTest, MacroVersion) {
7469 TestGTestAddReference<int&, int>();
7470 TestGTestAddReference<const char&, const char&>();
7471}
7472
7473// Tests GTEST_REFERENCE_TO_CONST_.
7474
7475template <typename T1, typename T2>
7476void TestGTestReferenceToConst() {
7477 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7478}
7479
7480TEST(GTestReferenceToConstTest, Works) {
7481 TestGTestReferenceToConst<const char&, char>();
7482 TestGTestReferenceToConst<const int&, const int>();
7483 TestGTestReferenceToConst<const double&, double>();
7484 TestGTestReferenceToConst<const std::string&, const std::string&>();
7485}
7486
7487// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7488TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7489 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7490 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7491 const_false);
7492}
7493
7494// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7495// be implicitly converted to T2.
7496TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7497 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7498 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7499 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7500 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7501 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7502 const ConversionHelperBase&>::value));
7503 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7504 ConversionHelperBase>::value));
7505}
7506
7507// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7508// cannot be implicitly converted to T2.
7509TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7510 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7511 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7512 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7513 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7514 ConversionHelperDerived&>::value));
7515}
7516
7517// Tests IsContainerTest.
7518
7519class NonContainer {};
7520
7521TEST(IsContainerTestTest, WorksForNonContainer) {
7522 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7523 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7524 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7525}
7526
7527TEST(IsContainerTestTest, WorksForContainer) {
7528 EXPECT_EQ(sizeof(IsContainer),
7529 sizeof(IsContainerTest<std::vector<bool> >(0)));
7530 EXPECT_EQ(sizeof(IsContainer),
7531 sizeof(IsContainerTest<std::map<int, double> >(0)));
7532}
7533
7534// Tests ArrayEq().
7535
7536TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7537 EXPECT_TRUE(ArrayEq(5, 5L));
7538 EXPECT_FALSE(ArrayEq('a', 0));
7539}
7540
7541TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7542 // Note that a and b are distinct but compatible types.
7543 const int a[] = { 0, 1 };
7544 long b[] = { 0, 1 };
7545 EXPECT_TRUE(ArrayEq(a, b));
7546 EXPECT_TRUE(ArrayEq(a, 2, b));
7547
7548 b[0] = 2;
7549 EXPECT_FALSE(ArrayEq(a, b));
7550 EXPECT_FALSE(ArrayEq(a, 1, b));
7551}
7552
7553TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7554 const char a[][3] = { "hi", "lo" };
7555 const char b[][3] = { "hi", "lo" };
7556 const char c[][3] = { "hi", "li" };
7557
7558 EXPECT_TRUE(ArrayEq(a, b));
7559 EXPECT_TRUE(ArrayEq(a, 2, b));
7560
7561 EXPECT_FALSE(ArrayEq(a, c));
7562 EXPECT_FALSE(ArrayEq(a, 2, c));
7563}
7564
7565// Tests ArrayAwareFind().
7566
7567TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7568 const char a[] = "hello";
7569 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7570 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7571}
7572
7573TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7574 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7575 const int b[2] = { 2, 3 };
7576 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7577
7578 const int c[2] = { 6, 7 };
7579 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7580}
7581
7582// Tests CopyArray().
7583
7584TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7585 int n = 0;
7586 CopyArray('a', &n);
7587 EXPECT_EQ('a', n);
7588}
7589
7590TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7591 const char a[3] = "hi";
7592 int b[3];
7593#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7594 CopyArray(a, &b);
7595 EXPECT_TRUE(ArrayEq(a, b));
7596#endif
7597
7598 int c[3];
7599 CopyArray(a, 3, c);
7600 EXPECT_TRUE(ArrayEq(a, c));
7601}
7602
7603TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7604 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7605 int b[2][3];
7606#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7607 CopyArray(a, &b);
7608 EXPECT_TRUE(ArrayEq(a, b));
7609#endif
7610
7611 int c[2][3];
7612 CopyArray(a, 2, c);
7613 EXPECT_TRUE(ArrayEq(a, c));
7614}
7615
7616// Tests NativeArray.
7617
7618TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7619 const int a[3] = { 0, 1, 2 };
7620 NativeArray<int> na(a, 3, RelationToSourceReference());
7621 EXPECT_EQ(3U, na.size());
7622 EXPECT_EQ(a, na.begin());
7623}
7624
7625TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7626 typedef int Array[2];
7627 Array* a = new Array[1];
7628 (*a)[0] = 0;
7629 (*a)[1] = 1;
7630 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7631 EXPECT_NE(*a, na.begin());
7632 delete[] a;
7633 EXPECT_EQ(0, na.begin()[0]);
7634 EXPECT_EQ(1, na.begin()[1]);
7635
7636 // We rely on the heap checker to verify that na deletes the copy of
7637 // array.
7638}
7639
7640TEST(NativeArrayTest, TypeMembersAreCorrect) {
7641 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7642 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7643
7644 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7645 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7646}
7647
7648TEST(NativeArrayTest, MethodsWork) {
7649 const int a[3] = { 0, 1, 2 };
7650 NativeArray<int> na(a, 3, RelationToSourceCopy());
7651 ASSERT_EQ(3U, na.size());
7652 EXPECT_EQ(3, na.end() - na.begin());
7653
7654 NativeArray<int>::const_iterator it = na.begin();
7655 EXPECT_EQ(0, *it);
7656 ++it;
7657 EXPECT_EQ(1, *it);
7658 it++;
7659 EXPECT_EQ(2, *it);
7660 ++it;
7661 EXPECT_EQ(na.end(), it);
7662
7663 EXPECT_TRUE(na == na);
7664
7665 NativeArray<int> na2(a, 3, RelationToSourceReference());
7666 EXPECT_TRUE(na == na2);
7667
7668 const int b1[3] = { 0, 1, 1 };
7669 const int b2[4] = { 0, 1, 2, 3 };
7670 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7671 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7672}
7673
7674TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7675 const char a[2][3] = { "hi", "lo" };
7676 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7677 ASSERT_EQ(2U, na.size());
7678 EXPECT_EQ(a, na.begin());
7679}
7680
7681// Tests SkipPrefix().
7682
7683TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7684 const char* const str = "hello";
7685
7686 const char* p = str;
7687 EXPECT_TRUE(SkipPrefix("", &p));
7688 EXPECT_EQ(str, p);
7689
7690 p = str;
7691 EXPECT_TRUE(SkipPrefix("hell", &p));
7692 EXPECT_EQ(str + 4, p);
7693}
7694
7695TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7696 const char* const str = "world";
7697
7698 const char* p = str;
7699 EXPECT_FALSE(SkipPrefix("W", &p));
7700 EXPECT_EQ(str, p);
7701
7702 p = str;
7703 EXPECT_FALSE(SkipPrefix("world!", &p));
7704 EXPECT_EQ(str, p);
7705}
7706