source: gtest-1.7.0/test/gtest_unittest.cc@ 12756

Last change on this file since 12756 was 12746, checked in by hock@…, 11 years ago

integrated the Google Testing Framework (gtest)

and wrote an Hello World test, to ensure the framework is working..

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