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