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