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