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