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