Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7240 lines
228 KiB

  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: [email protected] (Zhanyong Wan)
  31. //
  32. // Tests for Google Test itself. This verifies that the basic constructs of
  33. // Google Test work.
  34. #include "gtest/gtest.h"
  35. // Verifies that the command line flag variables can be accessed
  36. // in code once <gtest/gtest.h> has been #included.
  37. // Do not move it after other #includes.
  38. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
  39. bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
  40. || testing::GTEST_FLAG(break_on_failure)
  41. || testing::GTEST_FLAG(catch_exceptions)
  42. || testing::GTEST_FLAG(color) != "unknown"
  43. || testing::GTEST_FLAG(filter) != "unknown"
  44. || testing::GTEST_FLAG(list_tests)
  45. || testing::GTEST_FLAG(output) != "unknown"
  46. || testing::GTEST_FLAG(print_time)
  47. || testing::GTEST_FLAG(random_seed)
  48. || testing::GTEST_FLAG(repeat) > 0
  49. || testing::GTEST_FLAG(show_internal_stack_frames)
  50. || testing::GTEST_FLAG(shuffle)
  51. || testing::GTEST_FLAG(stack_trace_depth) > 0
  52. || testing::GTEST_FLAG(stream_result_to) != "unknown"
  53. || testing::GTEST_FLAG(throw_on_failure);
  54. EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
  55. }
  56. #include <limits.h> // For INT_MAX.
  57. #include <stdlib.h>
  58. #include <string.h>
  59. #include <time.h>
  60. #include <map>
  61. #include <vector>
  62. #include <ostream>
  63. #include "gtest/gtest-spi.h"
  64. // Indicates that this translation unit is part of Google Test's
  65. // implementation. It must come before gtest-internal-inl.h is
  66. // included, or there will be a compiler error. This trick is to
  67. // prevent a user from accidentally including gtest-internal-inl.h in
  68. // his code.
  69. #define GTEST_IMPLEMENTATION_ 1
  70. #include "src/gtest-internal-inl.h"
  71. #undef GTEST_IMPLEMENTATION_
  72. namespace testing {
  73. namespace internal {
  74. // Provides access to otherwise private parts of the TestEventListeners class
  75. // that are needed to test it.
  76. class TestEventListenersAccessor {
  77. public:
  78. static TestEventListener* GetRepeater(TestEventListeners* listeners) {
  79. return listeners->repeater();
  80. }
  81. static void SetDefaultResultPrinter(TestEventListeners* listeners,
  82. TestEventListener* listener) {
  83. listeners->SetDefaultResultPrinter(listener);
  84. }
  85. static void SetDefaultXmlGenerator(TestEventListeners* listeners,
  86. TestEventListener* listener) {
  87. listeners->SetDefaultXmlGenerator(listener);
  88. }
  89. static bool EventForwardingEnabled(const TestEventListeners& listeners) {
  90. return listeners.EventForwardingEnabled();
  91. }
  92. static void SuppressEventForwarding(TestEventListeners* listeners) {
  93. listeners->SuppressEventForwarding();
  94. }
  95. };
  96. } // namespace internal
  97. } // namespace testing
  98. using testing::AssertionFailure;
  99. using testing::AssertionResult;
  100. using testing::AssertionSuccess;
  101. using testing::DoubleLE;
  102. using testing::EmptyTestEventListener;
  103. using testing::FloatLE;
  104. using testing::GTEST_FLAG(also_run_disabled_tests);
  105. using testing::GTEST_FLAG(break_on_failure);
  106. using testing::GTEST_FLAG(catch_exceptions);
  107. using testing::GTEST_FLAG(color);
  108. using testing::GTEST_FLAG(death_test_use_fork);
  109. using testing::GTEST_FLAG(filter);
  110. using testing::GTEST_FLAG(list_tests);
  111. using testing::GTEST_FLAG(output);
  112. using testing::GTEST_FLAG(print_time);
  113. using testing::GTEST_FLAG(random_seed);
  114. using testing::GTEST_FLAG(repeat);
  115. using testing::GTEST_FLAG(show_internal_stack_frames);
  116. using testing::GTEST_FLAG(shuffle);
  117. using testing::GTEST_FLAG(stack_trace_depth);
  118. using testing::GTEST_FLAG(stream_result_to);
  119. using testing::GTEST_FLAG(throw_on_failure);
  120. using testing::IsNotSubstring;
  121. using testing::IsSubstring;
  122. using testing::Message;
  123. using testing::ScopedFakeTestPartResultReporter;
  124. using testing::StaticAssertTypeEq;
  125. using testing::Test;
  126. using testing::TestCase;
  127. using testing::TestEventListeners;
  128. using testing::TestPartResult;
  129. using testing::TestPartResultArray;
  130. using testing::TestProperty;
  131. using testing::TestResult;
  132. using testing::TimeInMillis;
  133. using testing::UnitTest;
  134. using testing::kMaxStackTraceDepth;
  135. using testing::internal::AddReference;
  136. using testing::internal::AlwaysFalse;
  137. using testing::internal::AlwaysTrue;
  138. using testing::internal::AppendUserMessage;
  139. using testing::internal::ArrayAwareFind;
  140. using testing::internal::ArrayEq;
  141. using testing::internal::CodePointToUtf8;
  142. using testing::internal::CompileAssertTypesEqual;
  143. using testing::internal::CopyArray;
  144. using testing::internal::CountIf;
  145. using testing::internal::EqFailure;
  146. using testing::internal::FloatingPoint;
  147. using testing::internal::ForEach;
  148. using testing::internal::FormatEpochTimeInMillisAsIso8601;
  149. using testing::internal::FormatTimeInMillisAsSeconds;
  150. using testing::internal::GTestFlagSaver;
  151. using testing::internal::GetCurrentOsStackTraceExceptTop;
  152. using testing::internal::GetElementOr;
  153. using testing::internal::GetNextRandomSeed;
  154. using testing::internal::GetRandomSeedFromFlag;
  155. using testing::internal::GetTestTypeId;
  156. using testing::internal::GetTimeInMillis;
  157. using testing::internal::GetTypeId;
  158. using testing::internal::GetUnitTestImpl;
  159. using testing::internal::ImplicitlyConvertible;
  160. using testing::internal::Int32;
  161. using testing::internal::Int32FromEnvOrDie;
  162. using testing::internal::IsAProtocolMessage;
  163. using testing::internal::IsContainer;
  164. using testing::internal::IsContainerTest;
  165. using testing::internal::IsNotContainer;
  166. using testing::internal::NativeArray;
  167. using testing::internal::ParseInt32Flag;
  168. using testing::internal::RemoveConst;
  169. using testing::internal::RemoveReference;
  170. using testing::internal::ShouldRunTestOnShard;
  171. using testing::internal::ShouldShard;
  172. using testing::internal::ShouldUseColor;
  173. using testing::internal::Shuffle;
  174. using testing::internal::ShuffleRange;
  175. using testing::internal::SkipPrefix;
  176. using testing::internal::StreamableToString;
  177. using testing::internal::String;
  178. using testing::internal::TestEventListenersAccessor;
  179. using testing::internal::TestResultAccessor;
  180. using testing::internal::UInt32;
  181. using testing::internal::WideStringToUtf8;
  182. using testing::internal::kCopy;
  183. using testing::internal::kMaxRandomSeed;
  184. using testing::internal::kReference;
  185. using testing::internal::kTestTypeIdInGoogleTest;
  186. using testing::internal::scoped_ptr;
  187. #if GTEST_HAS_STREAM_REDIRECTION
  188. using testing::internal::CaptureStdout;
  189. using testing::internal::GetCapturedStdout;
  190. #endif
  191. #if GTEST_IS_THREADSAFE
  192. using testing::internal::ThreadWithParam;
  193. #endif
  194. class TestingVector : public std::vector<int> {
  195. };
  196. ::std::ostream& operator<<(::std::ostream& os,
  197. const TestingVector& vector) {
  198. os << "{ ";
  199. for (size_t i = 0; i < vector.size(); i++) {
  200. os << vector[i] << " ";
  201. }
  202. os << "}";
  203. return os;
  204. }
  205. // This line tests that we can define tests in an unnamed namespace.
  206. namespace {
  207. TEST(GetRandomSeedFromFlagTest, HandlesZero) {
  208. const int seed = GetRandomSeedFromFlag(0);
  209. EXPECT_LE(1, seed);
  210. EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
  211. }
  212. TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
  213. EXPECT_EQ(1, GetRandomSeedFromFlag(1));
  214. EXPECT_EQ(2, GetRandomSeedFromFlag(2));
  215. EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
  216. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  217. GetRandomSeedFromFlag(kMaxRandomSeed));
  218. }
  219. TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
  220. const int seed1 = GetRandomSeedFromFlag(-1);
  221. EXPECT_LE(1, seed1);
  222. EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
  223. const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
  224. EXPECT_LE(1, seed2);
  225. EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
  226. }
  227. TEST(GetNextRandomSeedTest, WorksForValidInput) {
  228. EXPECT_EQ(2, GetNextRandomSeed(1));
  229. EXPECT_EQ(3, GetNextRandomSeed(2));
  230. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  231. GetNextRandomSeed(kMaxRandomSeed - 1));
  232. EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
  233. // We deliberately don't test GetNextRandomSeed() with invalid
  234. // inputs, as that requires death tests, which are expensive. This
  235. // is fine as GetNextRandomSeed() is internal and has a
  236. // straightforward definition.
  237. }
  238. static void ClearCurrentTestPartResults() {
  239. TestResultAccessor::ClearTestPartResults(
  240. GetUnitTestImpl()->current_test_result());
  241. }
  242. // Tests GetTypeId.
  243. TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
  244. EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
  245. EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
  246. }
  247. class SubClassOfTest : public Test {};
  248. class AnotherSubClassOfTest : public Test {};
  249. TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
  250. EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
  251. EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
  252. EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
  253. EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
  254. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
  255. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
  256. }
  257. // Verifies that GetTestTypeId() returns the same value, no matter it
  258. // is called from inside Google Test or outside of it.
  259. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
  260. EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
  261. }
  262. // Tests FormatTimeInMillisAsSeconds().
  263. TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
  264. EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
  265. }
  266. TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
  267. EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
  268. EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
  269. EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
  270. EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
  271. EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
  272. }
  273. TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
  274. EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
  275. EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
  276. EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
  277. EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
  278. EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
  279. }
  280. // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
  281. // for particular dates below was verified in Python using
  282. // datetime.datetime.fromutctimestamp(<timetamp>/1000).
  283. // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
  284. // have to set up a particular timezone to obtain predictable results.
  285. class FormatEpochTimeInMillisAsIso8601Test : public Test {
  286. public:
  287. // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
  288. // 32 bits, even when 64-bit integer types are available. We have to
  289. // force the constants to have a 64-bit type here.
  290. static const TimeInMillis kMillisPerSec = 1000;
  291. private:
  292. virtual void SetUp() {
  293. saved_tz_ = NULL;
  294. #if _MSC_VER
  295. # pragma warning(push) // Saves the current warning state.
  296. # pragma warning(disable:4996) // Temporarily disables warning 4996
  297. // (function or variable may be unsafe
  298. // for getenv, function is deprecated for
  299. // strdup).
  300. if (getenv("TZ"))
  301. saved_tz_ = strdup(getenv("TZ"));
  302. # pragma warning(pop) // Restores the warning state again.
  303. #else
  304. if (getenv("TZ"))
  305. saved_tz_ = strdup(getenv("TZ"));
  306. #endif
  307. // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
  308. // cannot use the local time zone because the function's output depends
  309. // on the time zone.
  310. SetTimeZone("UTC+00");
  311. }
  312. virtual void TearDown() {
  313. SetTimeZone(saved_tz_);
  314. free(const_cast<char*>(saved_tz_));
  315. saved_tz_ = NULL;
  316. }
  317. static void SetTimeZone(const char* time_zone) {
  318. // tzset() distinguishes between the TZ variable being present and empty
  319. // and not being present, so we have to consider the case of time_zone
  320. // being NULL.
  321. #if _MSC_VER
  322. // ...Unless it's MSVC, whose standard library's _putenv doesn't
  323. // distinguish between an empty and a missing variable.
  324. const std::string env_var =
  325. std::string("TZ=") + (time_zone ? time_zone : "");
  326. _putenv(env_var.c_str());
  327. # pragma warning(push) // Saves the current warning state.
  328. # pragma warning(disable:4996) // Temporarily disables warning 4996
  329. // (function is deprecated).
  330. tzset();
  331. # pragma warning(pop) // Restores the warning state again.
  332. #else
  333. if (time_zone) {
  334. setenv(("TZ"), time_zone, 1);
  335. } else {
  336. unsetenv("TZ");
  337. }
  338. tzset();
  339. #endif
  340. }
  341. const char* saved_tz_;
  342. };
  343. const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
  344. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
  345. EXPECT_EQ("2011-10-31T18:52:42",
  346. FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
  347. }
  348. TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
  349. EXPECT_EQ(
  350. "2011-10-31T18:52:42",
  351. FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
  352. }
  353. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
  354. EXPECT_EQ("2011-09-03T05:07:02",
  355. FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
  356. }
  357. TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
  358. EXPECT_EQ("2011-09-28T17:08:22",
  359. FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
  360. }
  361. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
  362. EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
  363. }
  364. #if GTEST_CAN_COMPARE_NULL
  365. # ifdef __BORLANDC__
  366. // Silences warnings: "Condition is always true", "Unreachable code"
  367. # pragma option push -w-ccc -w-rch
  368. # endif
  369. // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
  370. // pointer literal.
  371. TEST(NullLiteralTest, IsTrueForNullLiterals) {
  372. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
  373. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
  374. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
  375. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
  376. # ifndef __BORLANDC__
  377. // Some compilers may fail to detect some null pointer literals;
  378. // as long as users of the framework don't use such literals, this
  379. // is harmless.
  380. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
  381. # endif
  382. }
  383. // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
  384. // pointer literal.
  385. TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
  386. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
  387. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
  388. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
  389. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
  390. }
  391. # ifdef __BORLANDC__
  392. // Restores warnings after previous "#pragma option push" suppressed them.
  393. # pragma option pop
  394. # endif
  395. #endif // GTEST_CAN_COMPARE_NULL
  396. //
  397. // Tests CodePointToUtf8().
  398. // Tests that the NUL character L'\0' is encoded correctly.
  399. TEST(CodePointToUtf8Test, CanEncodeNul) {
  400. char buffer[32];
  401. EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
  402. }
  403. // Tests that ASCII characters are encoded correctly.
  404. TEST(CodePointToUtf8Test, CanEncodeAscii) {
  405. char buffer[32];
  406. EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
  407. EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
  408. EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
  409. EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
  410. }
  411. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  412. // as 110xxxxx 10xxxxxx.
  413. TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
  414. char buffer[32];
  415. // 000 1101 0011 => 110-00011 10-010011
  416. EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
  417. // 101 0111 0110 => 110-10101 10-110110
  418. // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
  419. // in wide strings and wide chars. In order to accomodate them, we have to
  420. // introduce such character constants as integers.
  421. EXPECT_STREQ("\xD5\xB6",
  422. CodePointToUtf8(static_cast<wchar_t>(0x576), buffer));
  423. }
  424. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  425. // as 1110xxxx 10xxxxxx 10xxxxxx.
  426. TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
  427. char buffer[32];
  428. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  429. EXPECT_STREQ("\xE0\xA3\x93",
  430. CodePointToUtf8(static_cast<wchar_t>(0x8D3), buffer));
  431. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  432. EXPECT_STREQ("\xEC\x9D\x8D",
  433. CodePointToUtf8(static_cast<wchar_t>(0xC74D), buffer));
  434. }
  435. #if !GTEST_WIDE_STRING_USES_UTF16_
  436. // Tests in this group require a wchar_t to hold > 16 bits, and thus
  437. // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
  438. // 16-bit wide. This code may not compile on those systems.
  439. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  440. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
  441. TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
  442. char buffer[32];
  443. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  444. EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
  445. // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
  446. EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
  447. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  448. EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
  449. }
  450. // Tests that encoding an invalid code-point generates the expected result.
  451. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
  452. char buffer[32];
  453. EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
  454. CodePointToUtf8(L'\x1234ABCD', buffer));
  455. }
  456. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  457. // Tests WideStringToUtf8().
  458. // Tests that the NUL character L'\0' is encoded correctly.
  459. TEST(WideStringToUtf8Test, CanEncodeNul) {
  460. EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
  461. EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
  462. }
  463. // Tests that ASCII strings are encoded correctly.
  464. TEST(WideStringToUtf8Test, CanEncodeAscii) {
  465. EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
  466. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
  467. EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
  468. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
  469. }
  470. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  471. // as 110xxxxx 10xxxxxx.
  472. TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
  473. // 000 1101 0011 => 110-00011 10-010011
  474. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
  475. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
  476. // 101 0111 0110 => 110-10101 10-110110
  477. const wchar_t s[] = { 0x576, '\0' };
  478. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
  479. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
  480. }
  481. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  482. // as 1110xxxx 10xxxxxx 10xxxxxx.
  483. TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
  484. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  485. const wchar_t s1[] = { 0x8D3, '\0' };
  486. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
  487. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
  488. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  489. const wchar_t s2[] = { 0xC74D, '\0' };
  490. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
  491. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
  492. }
  493. // Tests that the conversion stops when the function encounters \0 character.
  494. TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
  495. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
  496. }
  497. // Tests that the conversion stops when the function reaches the limit
  498. // specified by the 'length' parameter.
  499. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
  500. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
  501. }
  502. #if !GTEST_WIDE_STRING_USES_UTF16_
  503. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  504. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
  505. // on the systems using UTF-16 encoding.
  506. TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
  507. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  508. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
  509. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
  510. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  511. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
  512. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
  513. }
  514. // Tests that encoding an invalid code-point generates the expected result.
  515. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
  516. EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
  517. WideStringToUtf8(L"\xABCDFF", -1).c_str());
  518. }
  519. #else // !GTEST_WIDE_STRING_USES_UTF16_
  520. // Tests that surrogate pairs are encoded correctly on the systems using
  521. // UTF-16 encoding in the wide strings.
  522. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
  523. const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
  524. EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
  525. }
  526. // Tests that encoding an invalid UTF-16 surrogate pair
  527. // generates the expected result.
  528. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
  529. // Leading surrogate is at the end of the string.
  530. const wchar_t s1[] = { 0xD800, '\0' };
  531. EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
  532. // Leading surrogate is not followed by the trailing surrogate.
  533. const wchar_t s2[] = { 0xD800, 'M', '\0' };
  534. EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
  535. // Trailing surrogate appearas without a leading surrogate.
  536. const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
  537. EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
  538. }
  539. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  540. // Tests that codepoint concatenation works correctly.
  541. #if !GTEST_WIDE_STRING_USES_UTF16_
  542. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  543. const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
  544. EXPECT_STREQ(
  545. "\xF4\x88\x98\xB4"
  546. "\xEC\x9D\x8D"
  547. "\n"
  548. "\xD5\xB6"
  549. "\xE0\xA3\x93"
  550. "\xF4\x88\x98\xB4",
  551. WideStringToUtf8(s, -1).c_str());
  552. }
  553. #else
  554. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  555. const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
  556. EXPECT_STREQ(
  557. "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
  558. WideStringToUtf8(s, -1).c_str());
  559. }
  560. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  561. // Tests the Random class.
  562. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
  563. testing::internal::Random random(42);
  564. EXPECT_DEATH_IF_SUPPORTED(
  565. random.Generate(0),
  566. "Cannot generate a number in the range \\[0, 0\\)");
  567. EXPECT_DEATH_IF_SUPPORTED(
  568. random.Generate(testing::internal::Random::kMaxRange + 1),
  569. "Generation of a number in \\[0, 2147483649\\) was requested, "
  570. "but this can only generate numbers in \\[0, 2147483648\\)");
  571. }
  572. TEST(RandomTest, GeneratesNumbersWithinRange) {
  573. const UInt32 kRange = 10000;
  574. testing::internal::Random random(12345);
  575. for (int i = 0; i < 10; i++) {
  576. EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
  577. }
  578. testing::internal::Random random2(testing::internal::Random::kMaxRange);
  579. for (int i = 0; i < 10; i++) {
  580. EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
  581. }
  582. }
  583. TEST(RandomTest, RepeatsWhenReseeded) {
  584. const int kSeed = 123;
  585. const int kArraySize = 10;
  586. const UInt32 kRange = 10000;
  587. UInt32 values[kArraySize];
  588. testing::internal::Random random(kSeed);
  589. for (int i = 0; i < kArraySize; i++) {
  590. values[i] = random.Generate(kRange);
  591. }
  592. random.Reseed(kSeed);
  593. for (int i = 0; i < kArraySize; i++) {
  594. EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
  595. }
  596. }
  597. // Tests STL container utilities.
  598. // Tests CountIf().
  599. static bool IsPositive(int n) { return n > 0; }
  600. TEST(ContainerUtilityTest, CountIf) {
  601. std::vector<int> v;
  602. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
  603. v.push_back(-1);
  604. v.push_back(0);
  605. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
  606. v.push_back(2);
  607. v.push_back(-10);
  608. v.push_back(10);
  609. EXPECT_EQ(2, CountIf(v, IsPositive));
  610. }
  611. // Tests ForEach().
  612. static int g_sum = 0;
  613. static void Accumulate(int n) { g_sum += n; }
  614. TEST(ContainerUtilityTest, ForEach) {
  615. std::vector<int> v;
  616. g_sum = 0;
  617. ForEach(v, Accumulate);
  618. EXPECT_EQ(0, g_sum); // Works for an empty container;
  619. g_sum = 0;
  620. v.push_back(1);
  621. ForEach(v, Accumulate);
  622. EXPECT_EQ(1, g_sum); // Works for a container with one element.
  623. g_sum = 0;
  624. v.push_back(20);
  625. v.push_back(300);
  626. ForEach(v, Accumulate);
  627. EXPECT_EQ(321, g_sum);
  628. }
  629. // Tests GetElementOr().
  630. TEST(ContainerUtilityTest, GetElementOr) {
  631. std::vector<char> a;
  632. EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
  633. a.push_back('a');
  634. a.push_back('b');
  635. EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
  636. EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
  637. EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
  638. EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
  639. }
  640. TEST(ContainerUtilityDeathTest, ShuffleRange) {
  641. std::vector<int> a;
  642. a.push_back(0);
  643. a.push_back(1);
  644. a.push_back(2);
  645. testing::internal::Random random(1);
  646. EXPECT_DEATH_IF_SUPPORTED(
  647. ShuffleRange(&random, -1, 1, &a),
  648. "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
  649. EXPECT_DEATH_IF_SUPPORTED(
  650. ShuffleRange(&random, 4, 4, &a),
  651. "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
  652. EXPECT_DEATH_IF_SUPPORTED(
  653. ShuffleRange(&random, 3, 2, &a),
  654. "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
  655. EXPECT_DEATH_IF_SUPPORTED(
  656. ShuffleRange(&random, 3, 4, &a),
  657. "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
  658. }
  659. class VectorShuffleTest : public Test {
  660. protected:
  661. static const int kVectorSize = 20;
  662. VectorShuffleTest() : random_(1) {
  663. for (int i = 0; i < kVectorSize; i++) {
  664. vector_.push_back(i);
  665. }
  666. }
  667. static bool VectorIsCorrupt(const TestingVector& vector) {
  668. if (kVectorSize != static_cast<int>(vector.size())) {
  669. return true;
  670. }
  671. bool found_in_vector[kVectorSize] = { false };
  672. for (size_t i = 0; i < vector.size(); i++) {
  673. const int e = vector[i];
  674. if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
  675. return true;
  676. }
  677. found_in_vector[e] = true;
  678. }
  679. // Vector size is correct, elements' range is correct, no
  680. // duplicate elements. Therefore no corruption has occurred.
  681. return false;
  682. }
  683. static bool VectorIsNotCorrupt(const TestingVector& vector) {
  684. return !VectorIsCorrupt(vector);
  685. }
  686. static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
  687. for (int i = begin; i < end; i++) {
  688. if (i != vector[i]) {
  689. return true;
  690. }
  691. }
  692. return false;
  693. }
  694. static bool RangeIsUnshuffled(
  695. const TestingVector& vector, int begin, int end) {
  696. return !RangeIsShuffled(vector, begin, end);
  697. }
  698. static bool VectorIsShuffled(const TestingVector& vector) {
  699. return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
  700. }
  701. static bool VectorIsUnshuffled(const TestingVector& vector) {
  702. return !VectorIsShuffled(vector);
  703. }
  704. testing::internal::Random random_;
  705. TestingVector vector_;
  706. }; // class VectorShuffleTest
  707. const int VectorShuffleTest::kVectorSize;
  708. TEST_F(VectorShuffleTest, HandlesEmptyRange) {
  709. // Tests an empty range at the beginning...
  710. ShuffleRange(&random_, 0, 0, &vector_);
  711. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  712. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  713. // ...in the middle...
  714. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
  715. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  716. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  717. // ...at the end...
  718. ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
  719. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  720. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  721. // ...and past the end.
  722. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
  723. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  724. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  725. }
  726. TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
  727. // Tests a size one range at the beginning...
  728. ShuffleRange(&random_, 0, 1, &vector_);
  729. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  730. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  731. // ...in the middle...
  732. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
  733. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  734. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  735. // ...and at the end.
  736. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
  737. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  738. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  739. }
  740. // Because we use our own random number generator and a fixed seed,
  741. // we can guarantee that the following "random" tests will succeed.
  742. TEST_F(VectorShuffleTest, ShufflesEntireVector) {
  743. Shuffle(&random_, &vector_);
  744. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  745. EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
  746. // Tests the first and last elements in particular to ensure that
  747. // there are no off-by-one problems in our shuffle algorithm.
  748. EXPECT_NE(0, vector_[0]);
  749. EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
  750. }
  751. TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
  752. const int kRangeSize = kVectorSize/2;
  753. ShuffleRange(&random_, 0, kRangeSize, &vector_);
  754. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  755. EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
  756. EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
  757. }
  758. TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
  759. const int kRangeSize = kVectorSize / 2;
  760. ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
  761. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  762. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  763. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
  764. }
  765. TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
  766. int kRangeSize = kVectorSize/3;
  767. ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
  768. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  769. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  770. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
  771. EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
  772. }
  773. TEST_F(VectorShuffleTest, ShufflesRepeatably) {
  774. TestingVector vector2;
  775. for (int i = 0; i < kVectorSize; i++) {
  776. vector2.push_back(i);
  777. }
  778. random_.Reseed(1234);
  779. Shuffle(&random_, &vector_);
  780. random_.Reseed(1234);
  781. Shuffle(&random_, &vector2);
  782. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  783. ASSERT_PRED1(VectorIsNotCorrupt, vector2);
  784. for (int i = 0; i < kVectorSize; i++) {
  785. EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
  786. }
  787. }
  788. // Tests the size of the AssertHelper class.
  789. TEST(AssertHelperTest, AssertHelperIsSmall) {
  790. // To avoid breaking clients that use lots of assertions in one
  791. // function, we cannot grow the size of AssertHelper.
  792. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
  793. }
  794. // Tests String::EndsWithCaseInsensitive().
  795. TEST(StringTest, EndsWithCaseInsensitive) {
  796. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
  797. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
  798. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
  799. EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
  800. EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
  801. EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
  802. EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
  803. }
  804. // C++Builder's preprocessor is buggy; it fails to expand macros that
  805. // appear in macro parameters after wide char literals. Provide an alias
  806. // for NULL as a workaround.
  807. static const wchar_t* const kNull = NULL;
  808. // Tests String::CaseInsensitiveWideCStringEquals
  809. TEST(StringTest, CaseInsensitiveWideCStringEquals) {
  810. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
  811. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
  812. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
  813. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
  814. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
  815. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
  816. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
  817. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
  818. }
  819. // Tests that String::Format() works.
  820. TEST(StringTest, FormatWorks) {
  821. // Normal case: the format spec is valid, the arguments match the
  822. // spec, and the result is < 4095 characters.
  823. EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
  824. // Edge case: the result is 4095 characters.
  825. char buffer[4096];
  826. const size_t kSize = sizeof(buffer);
  827. memset(buffer, 'a', kSize - 1);
  828. buffer[kSize - 1] = '\0';
  829. EXPECT_EQ(buffer, String::Format("%s", buffer));
  830. // The result needs to be 4096 characters, exceeding Format()'s limit.
  831. EXPECT_EQ("<formatting error or buffer exceeded>",
  832. String::Format("x%s", buffer));
  833. #if GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  834. // On Linux, invalid format spec should lead to an error message.
  835. // In other environment (e.g. MSVC on Windows), String::Format() may
  836. // simply ignore a bad format spec, so this assertion is run on
  837. // Linux only.
  838. EXPECT_EQ("<formatting error or buffer exceeded>",
  839. String::Format("%"));
  840. #endif
  841. }
  842. #if GTEST_OS_WINDOWS
  843. // Tests String::ShowWideCString().
  844. TEST(StringTest, ShowWideCString) {
  845. EXPECT_STREQ("(null)",
  846. String::ShowWideCString(NULL).c_str());
  847. EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
  848. EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
  849. }
  850. # if GTEST_OS_WINDOWS_MOBILE
  851. TEST(StringTest, AnsiAndUtf16Null) {
  852. EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
  853. EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
  854. }
  855. TEST(StringTest, AnsiAndUtf16ConvertBasic) {
  856. const char* ansi = String::Utf16ToAnsi(L"str");
  857. EXPECT_STREQ("str", ansi);
  858. delete [] ansi;
  859. const WCHAR* utf16 = String::AnsiToUtf16("str");
  860. EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
  861. delete [] utf16;
  862. }
  863. TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
  864. const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
  865. EXPECT_STREQ(".:\\ \"*?", ansi);
  866. delete [] ansi;
  867. const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
  868. EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
  869. delete [] utf16;
  870. }
  871. # endif // GTEST_OS_WINDOWS_MOBILE
  872. #endif // GTEST_OS_WINDOWS
  873. // Tests TestProperty construction.
  874. TEST(TestPropertyTest, StringValue) {
  875. TestProperty property("key", "1");
  876. EXPECT_STREQ("key", property.key());
  877. EXPECT_STREQ("1", property.value());
  878. }
  879. // Tests TestProperty replacing a value.
  880. TEST(TestPropertyTest, ReplaceStringValue) {
  881. TestProperty property("key", "1");
  882. EXPECT_STREQ("1", property.value());
  883. property.SetValue("2");
  884. EXPECT_STREQ("2", property.value());
  885. }
  886. // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
  887. // functions (i.e. their definitions cannot be inlined at the call
  888. // sites), or C++Builder won't compile the code.
  889. static void AddFatalFailure() {
  890. FAIL() << "Expected fatal failure.";
  891. }
  892. static void AddNonfatalFailure() {
  893. ADD_FAILURE() << "Expected non-fatal failure.";
  894. }
  895. class ScopedFakeTestPartResultReporterTest : public Test {
  896. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  897. enum FailureMode {
  898. FATAL_FAILURE,
  899. NONFATAL_FAILURE
  900. };
  901. static void AddFailure(FailureMode failure) {
  902. if (failure == FATAL_FAILURE) {
  903. AddFatalFailure();
  904. } else {
  905. AddNonfatalFailure();
  906. }
  907. }
  908. };
  909. // Tests that ScopedFakeTestPartResultReporter intercepts test
  910. // failures.
  911. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
  912. TestPartResultArray results;
  913. {
  914. ScopedFakeTestPartResultReporter reporter(
  915. ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
  916. &results);
  917. AddFailure(NONFATAL_FAILURE);
  918. AddFailure(FATAL_FAILURE);
  919. }
  920. EXPECT_EQ(2, results.size());
  921. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  922. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  923. }
  924. TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
  925. TestPartResultArray results;
  926. {
  927. // Tests, that the deprecated constructor still works.
  928. ScopedFakeTestPartResultReporter reporter(&results);
  929. AddFailure(NONFATAL_FAILURE);
  930. }
  931. EXPECT_EQ(1, results.size());
  932. }
  933. #if GTEST_IS_THREADSAFE
  934. class ScopedFakeTestPartResultReporterWithThreadsTest
  935. : public ScopedFakeTestPartResultReporterTest {
  936. protected:
  937. static void AddFailureInOtherThread(FailureMode failure) {
  938. ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
  939. thread.Join();
  940. }
  941. };
  942. TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
  943. InterceptsTestFailuresInAllThreads) {
  944. TestPartResultArray results;
  945. {
  946. ScopedFakeTestPartResultReporter reporter(
  947. ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
  948. AddFailure(NONFATAL_FAILURE);
  949. AddFailure(FATAL_FAILURE);
  950. AddFailureInOtherThread(NONFATAL_FAILURE);
  951. AddFailureInOtherThread(FATAL_FAILURE);
  952. }
  953. EXPECT_EQ(4, results.size());
  954. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  955. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  956. EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
  957. EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
  958. }
  959. #endif // GTEST_IS_THREADSAFE
  960. // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
  961. // work even if the failure is generated in a called function rather than
  962. // the current context.
  963. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
  964. TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
  965. EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
  966. }
  967. #if GTEST_HAS_GLOBAL_STRING
  968. TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
  969. EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
  970. }
  971. #endif
  972. TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
  973. EXPECT_FATAL_FAILURE(AddFatalFailure(),
  974. ::std::string("Expected fatal failure."));
  975. }
  976. TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
  977. // We have another test below to verify that the macro catches fatal
  978. // failures generated on another thread.
  979. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
  980. "Expected fatal failure.");
  981. }
  982. #ifdef __BORLANDC__
  983. // Silences warnings: "Condition is always true"
  984. # pragma option push -w-ccc
  985. #endif
  986. // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
  987. // function even when the statement in it contains ASSERT_*.
  988. int NonVoidFunction() {
  989. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  990. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  991. return 0;
  992. }
  993. TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
  994. NonVoidFunction();
  995. }
  996. // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
  997. // current function even though 'statement' generates a fatal failure.
  998. void DoesNotAbortHelper(bool* aborted) {
  999. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1000. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1001. *aborted = false;
  1002. }
  1003. #ifdef __BORLANDC__
  1004. // Restores warnings after previous "#pragma option push" suppressed them.
  1005. # pragma option pop
  1006. #endif
  1007. TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
  1008. bool aborted = true;
  1009. DoesNotAbortHelper(&aborted);
  1010. EXPECT_FALSE(aborted);
  1011. }
  1012. // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1013. // statement that contains a macro which expands to code containing an
  1014. // unprotected comma.
  1015. static int global_var = 0;
  1016. #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
  1017. TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1018. #ifndef __BORLANDC__
  1019. // ICE's in C++Builder.
  1020. EXPECT_FATAL_FAILURE({
  1021. GTEST_USE_UNPROTECTED_COMMA_;
  1022. AddFatalFailure();
  1023. }, "");
  1024. #endif
  1025. EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
  1026. GTEST_USE_UNPROTECTED_COMMA_;
  1027. AddFatalFailure();
  1028. }, "");
  1029. }
  1030. // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
  1031. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
  1032. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
  1033. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1034. "Expected non-fatal failure.");
  1035. }
  1036. #if GTEST_HAS_GLOBAL_STRING
  1037. TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
  1038. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1039. ::string("Expected non-fatal failure."));
  1040. }
  1041. #endif
  1042. TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
  1043. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1044. ::std::string("Expected non-fatal failure."));
  1045. }
  1046. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
  1047. // We have another test below to verify that the macro catches
  1048. // non-fatal failures generated on another thread.
  1049. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
  1050. "Expected non-fatal failure.");
  1051. }
  1052. // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1053. // statement that contains a macro which expands to code containing an
  1054. // unprotected comma.
  1055. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1056. EXPECT_NONFATAL_FAILURE({
  1057. GTEST_USE_UNPROTECTED_COMMA_;
  1058. AddNonfatalFailure();
  1059. }, "");
  1060. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
  1061. GTEST_USE_UNPROTECTED_COMMA_;
  1062. AddNonfatalFailure();
  1063. }, "");
  1064. }
  1065. #if GTEST_IS_THREADSAFE
  1066. typedef ScopedFakeTestPartResultReporterWithThreadsTest
  1067. ExpectFailureWithThreadsTest;
  1068. TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
  1069. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
  1070. "Expected fatal failure.");
  1071. }
  1072. TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  1073. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  1074. AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
  1075. }
  1076. #endif // GTEST_IS_THREADSAFE
  1077. // Tests the TestProperty class.
  1078. TEST(TestPropertyTest, ConstructorWorks) {
  1079. const TestProperty property("key", "value");
  1080. EXPECT_STREQ("key", property.key());
  1081. EXPECT_STREQ("value", property.value());
  1082. }
  1083. TEST(TestPropertyTest, SetValue) {
  1084. TestProperty property("key", "value_1");
  1085. EXPECT_STREQ("key", property.key());
  1086. property.SetValue("value_2");
  1087. EXPECT_STREQ("key", property.key());
  1088. EXPECT_STREQ("value_2", property.value());
  1089. }
  1090. // Tests the TestResult class
  1091. // The test fixture for testing TestResult.
  1092. class TestResultTest : public Test {
  1093. protected:
  1094. typedef std::vector<TestPartResult> TPRVector;
  1095. // We make use of 2 TestPartResult objects,
  1096. TestPartResult * pr1, * pr2;
  1097. // ... and 3 TestResult objects.
  1098. TestResult * r0, * r1, * r2;
  1099. virtual void SetUp() {
  1100. // pr1 is for success.
  1101. pr1 = new TestPartResult(TestPartResult::kSuccess,
  1102. "foo/bar.cc",
  1103. 10,
  1104. "Success!");
  1105. // pr2 is for fatal failure.
  1106. pr2 = new TestPartResult(TestPartResult::kFatalFailure,
  1107. "foo/bar.cc",
  1108. -1, // This line number means "unknown"
  1109. "Failure!");
  1110. // Creates the TestResult objects.
  1111. r0 = new TestResult();
  1112. r1 = new TestResult();
  1113. r2 = new TestResult();
  1114. // In order to test TestResult, we need to modify its internal
  1115. // state, in particular the TestPartResult vector it holds.
  1116. // test_part_results() returns a const reference to this vector.
  1117. // We cast it to a non-const object s.t. it can be modified (yes,
  1118. // this is a hack).
  1119. TPRVector* results1 = const_cast<TPRVector*>(
  1120. &TestResultAccessor::test_part_results(*r1));
  1121. TPRVector* results2 = const_cast<TPRVector*>(
  1122. &TestResultAccessor::test_part_results(*r2));
  1123. // r0 is an empty TestResult.
  1124. // r1 contains a single SUCCESS TestPartResult.
  1125. results1->push_back(*pr1);
  1126. // r2 contains a SUCCESS, and a FAILURE.
  1127. results2->push_back(*pr1);
  1128. results2->push_back(*pr2);
  1129. }
  1130. virtual void TearDown() {
  1131. delete pr1;
  1132. delete pr2;
  1133. delete r0;
  1134. delete r1;
  1135. delete r2;
  1136. }
  1137. // Helper that compares two two TestPartResults.
  1138. static void CompareTestPartResult(const TestPartResult& expected,
  1139. const TestPartResult& actual) {
  1140. EXPECT_EQ(expected.type(), actual.type());
  1141. EXPECT_STREQ(expected.file_name(), actual.file_name());
  1142. EXPECT_EQ(expected.line_number(), actual.line_number());
  1143. EXPECT_STREQ(expected.summary(), actual.summary());
  1144. EXPECT_STREQ(expected.message(), actual.message());
  1145. EXPECT_EQ(expected.passed(), actual.passed());
  1146. EXPECT_EQ(expected.failed(), actual.failed());
  1147. EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
  1148. EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
  1149. }
  1150. };
  1151. // Tests TestResult::total_part_count().
  1152. TEST_F(TestResultTest, total_part_count) {
  1153. ASSERT_EQ(0, r0->total_part_count());
  1154. ASSERT_EQ(1, r1->total_part_count());
  1155. ASSERT_EQ(2, r2->total_part_count());
  1156. }
  1157. // Tests TestResult::Passed().
  1158. TEST_F(TestResultTest, Passed) {
  1159. ASSERT_TRUE(r0->Passed());
  1160. ASSERT_TRUE(r1->Passed());
  1161. ASSERT_FALSE(r2->Passed());
  1162. }
  1163. // Tests TestResult::Failed().
  1164. TEST_F(TestResultTest, Failed) {
  1165. ASSERT_FALSE(r0->Failed());
  1166. ASSERT_FALSE(r1->Failed());
  1167. ASSERT_TRUE(r2->Failed());
  1168. }
  1169. // Tests TestResult::GetTestPartResult().
  1170. typedef TestResultTest TestResultDeathTest;
  1171. TEST_F(TestResultDeathTest, GetTestPartResult) {
  1172. CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
  1173. CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
  1174. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
  1175. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
  1176. }
  1177. // Tests TestResult has no properties when none are added.
  1178. TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
  1179. TestResult test_result;
  1180. ASSERT_EQ(0, test_result.test_property_count());
  1181. }
  1182. // Tests TestResult has the expected property when added.
  1183. TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
  1184. TestResult test_result;
  1185. TestProperty property("key_1", "1");
  1186. TestResultAccessor::RecordProperty(&test_result, property);
  1187. ASSERT_EQ(1, test_result.test_property_count());
  1188. const TestProperty& actual_property = test_result.GetTestProperty(0);
  1189. EXPECT_STREQ("key_1", actual_property.key());
  1190. EXPECT_STREQ("1", actual_property.value());
  1191. }
  1192. // Tests TestResult has multiple properties when added.
  1193. TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
  1194. TestResult test_result;
  1195. TestProperty property_1("key_1", "1");
  1196. TestProperty property_2("key_2", "2");
  1197. TestResultAccessor::RecordProperty(&test_result, property_1);
  1198. TestResultAccessor::RecordProperty(&test_result, property_2);
  1199. ASSERT_EQ(2, test_result.test_property_count());
  1200. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1201. EXPECT_STREQ("key_1", actual_property_1.key());
  1202. EXPECT_STREQ("1", actual_property_1.value());
  1203. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1204. EXPECT_STREQ("key_2", actual_property_2.key());
  1205. EXPECT_STREQ("2", actual_property_2.value());
  1206. }
  1207. // Tests TestResult::RecordProperty() overrides values for duplicate keys.
  1208. TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
  1209. TestResult test_result;
  1210. TestProperty property_1_1("key_1", "1");
  1211. TestProperty property_2_1("key_2", "2");
  1212. TestProperty property_1_2("key_1", "12");
  1213. TestProperty property_2_2("key_2", "22");
  1214. TestResultAccessor::RecordProperty(&test_result, property_1_1);
  1215. TestResultAccessor::RecordProperty(&test_result, property_2_1);
  1216. TestResultAccessor::RecordProperty(&test_result, property_1_2);
  1217. TestResultAccessor::RecordProperty(&test_result, property_2_2);
  1218. ASSERT_EQ(2, test_result.test_property_count());
  1219. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1220. EXPECT_STREQ("key_1", actual_property_1.key());
  1221. EXPECT_STREQ("12", actual_property_1.value());
  1222. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1223. EXPECT_STREQ("key_2", actual_property_2.key());
  1224. EXPECT_STREQ("22", actual_property_2.value());
  1225. }
  1226. // Tests TestResult::GetTestProperty().
  1227. TEST(TestResultPropertyDeathTest, GetTestProperty) {
  1228. TestResult test_result;
  1229. TestProperty property_1("key_1", "1");
  1230. TestProperty property_2("key_2", "2");
  1231. TestProperty property_3("key_3", "3");
  1232. TestResultAccessor::RecordProperty(&test_result, property_1);
  1233. TestResultAccessor::RecordProperty(&test_result, property_2);
  1234. TestResultAccessor::RecordProperty(&test_result, property_3);
  1235. const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
  1236. const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
  1237. const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
  1238. EXPECT_STREQ("key_1", fetched_property_1.key());
  1239. EXPECT_STREQ("1", fetched_property_1.value());
  1240. EXPECT_STREQ("key_2", fetched_property_2.key());
  1241. EXPECT_STREQ("2", fetched_property_2.value());
  1242. EXPECT_STREQ("key_3", fetched_property_3.key());
  1243. EXPECT_STREQ("3", fetched_property_3.value());
  1244. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
  1245. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
  1246. }
  1247. // When a property using a reserved key is supplied to this function, it tests
  1248. // that a non-fatal failure is added, a fatal failure is not added, and that the
  1249. // property is not recorded.
  1250. void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
  1251. TestResult test_result;
  1252. TestProperty property(key, "1");
  1253. EXPECT_NONFATAL_FAILURE(
  1254. TestResultAccessor::RecordProperty(&test_result, property),
  1255. "Reserved key");
  1256. ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
  1257. }
  1258. // Attempting to recording a property with the Reserved literal "name"
  1259. // should add a non-fatal failure and the property should not be recorded.
  1260. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
  1261. ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
  1262. }
  1263. // Attempting to recording a property with the Reserved literal "status"
  1264. // should add a non-fatal failure and the property should not be recorded.
  1265. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
  1266. ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
  1267. }
  1268. // Attempting to recording a property with the Reserved literal "time"
  1269. // should add a non-fatal failure and the property should not be recorded.
  1270. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
  1271. ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
  1272. }
  1273. // Attempting to recording a property with the Reserved literal "classname"
  1274. // should add a non-fatal failure and the property should not be recorded.
  1275. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
  1276. ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
  1277. }
  1278. // Tests that GTestFlagSaver works on Windows and Mac.
  1279. class GTestFlagSaverTest : public Test {
  1280. protected:
  1281. // Saves the Google Test flags such that we can restore them later, and
  1282. // then sets them to their default values. This will be called
  1283. // before the first test in this test case is run.
  1284. static void SetUpTestCase() {
  1285. saver_ = new GTestFlagSaver;
  1286. GTEST_FLAG(also_run_disabled_tests) = false;
  1287. GTEST_FLAG(break_on_failure) = false;
  1288. GTEST_FLAG(catch_exceptions) = false;
  1289. GTEST_FLAG(death_test_use_fork) = false;
  1290. GTEST_FLAG(color) = "auto";
  1291. GTEST_FLAG(filter) = "";
  1292. GTEST_FLAG(list_tests) = false;
  1293. GTEST_FLAG(output) = "";
  1294. GTEST_FLAG(print_time) = true;
  1295. GTEST_FLAG(random_seed) = 0;
  1296. GTEST_FLAG(repeat) = 1;
  1297. GTEST_FLAG(shuffle) = false;
  1298. GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
  1299. GTEST_FLAG(stream_result_to) = "";
  1300. GTEST_FLAG(throw_on_failure) = false;
  1301. }
  1302. // Restores the Google Test flags that the tests have modified. This will
  1303. // be called after the last test in this test case is run.
  1304. static void TearDownTestCase() {
  1305. delete saver_;
  1306. saver_ = NULL;
  1307. }
  1308. // Verifies that the Google Test flags have their default values, and then
  1309. // modifies each of them.
  1310. void VerifyAndModifyFlags() {
  1311. EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
  1312. EXPECT_FALSE(GTEST_FLAG(break_on_failure));
  1313. EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
  1314. EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
  1315. EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
  1316. EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
  1317. EXPECT_FALSE(GTEST_FLAG(list_tests));
  1318. EXPECT_STREQ("", GTEST_FLAG(output).c_str());
  1319. EXPECT_TRUE(GTEST_FLAG(print_time));
  1320. EXPECT_EQ(0, GTEST_FLAG(random_seed));
  1321. EXPECT_EQ(1, GTEST_FLAG(repeat));
  1322. EXPECT_FALSE(GTEST_FLAG(shuffle));
  1323. EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
  1324. EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
  1325. EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
  1326. GTEST_FLAG(also_run_disabled_tests) = true;
  1327. GTEST_FLAG(break_on_failure) = true;
  1328. GTEST_FLAG(catch_exceptions) = true;
  1329. GTEST_FLAG(color) = "no";
  1330. GTEST_FLAG(death_test_use_fork) = true;
  1331. GTEST_FLAG(filter) = "abc";
  1332. GTEST_FLAG(list_tests) = true;
  1333. GTEST_FLAG(output) = "xml:foo.xml";
  1334. GTEST_FLAG(print_time) = false;
  1335. GTEST_FLAG(random_seed) = 1;
  1336. GTEST_FLAG(repeat) = 100;
  1337. GTEST_FLAG(shuffle) = true;
  1338. GTEST_FLAG(stack_trace_depth) = 1;
  1339. GTEST_FLAG(stream_result_to) = "localhost:1234";
  1340. GTEST_FLAG(throw_on_failure) = true;
  1341. }
  1342. private:
  1343. // For saving Google Test flags during this test case.
  1344. static GTestFlagSaver* saver_;
  1345. };
  1346. GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
  1347. // Google Test doesn't guarantee the order of tests. The following two
  1348. // tests are designed to work regardless of their order.
  1349. // Modifies the Google Test flags in the test body.
  1350. TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
  1351. VerifyAndModifyFlags();
  1352. }
  1353. // Verifies that the Google Test flags in the body of the previous test were
  1354. // restored to their original values.
  1355. TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
  1356. VerifyAndModifyFlags();
  1357. }
  1358. // Sets an environment variable with the given name to the given
  1359. // value. If the value argument is "", unsets the environment
  1360. // variable. The caller must ensure that both arguments are not NULL.
  1361. static void SetEnv(const char* name, const char* value) {
  1362. #if GTEST_OS_WINDOWS_MOBILE
  1363. // Environment variables are not supported on Windows CE.
  1364. return;
  1365. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  1366. // C++Builder's putenv only stores a pointer to its parameter; we have to
  1367. // ensure that the string remains valid as long as it might be needed.
  1368. // We use an std::map to do so.
  1369. static std::map<std::string, std::string*> added_env;
  1370. // Because putenv stores a pointer to the string buffer, we can't delete the
  1371. // previous string (if present) until after it's replaced.
  1372. std::string *prev_env = NULL;
  1373. if (added_env.find(name) != added_env.end()) {
  1374. prev_env = added_env[name];
  1375. }
  1376. added_env[name] = new std::string(
  1377. (Message() << name << "=" << value).GetString());
  1378. // The standard signature of putenv accepts a 'char*' argument. Other
  1379. // implementations, like C++Builder's, accept a 'const char*'.
  1380. // We cast away the 'const' since that would work for both variants.
  1381. putenv(const_cast<char*>(added_env[name]->c_str()));
  1382. delete prev_env;
  1383. #elif GTEST_OS_WINDOWS // If we are on Windows proper.
  1384. _putenv((Message() << name << "=" << value).GetString().c_str());
  1385. #else
  1386. if (*value == '\0') {
  1387. unsetenv(name);
  1388. } else {
  1389. setenv(name, value, 1);
  1390. }
  1391. #endif // GTEST_OS_WINDOWS_MOBILE
  1392. }
  1393. #if !GTEST_OS_WINDOWS_MOBILE
  1394. // Environment variables are not supported on Windows CE.
  1395. using testing::internal::Int32FromGTestEnv;
  1396. // Tests Int32FromGTestEnv().
  1397. // Tests that Int32FromGTestEnv() returns the default value when the
  1398. // environment variable is not set.
  1399. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
  1400. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
  1401. EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
  1402. }
  1403. // Tests that Int32FromGTestEnv() returns the default value when the
  1404. // environment variable overflows as an Int32.
  1405. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
  1406. printf("(expecting 2 warnings)\n");
  1407. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
  1408. EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
  1409. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
  1410. EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
  1411. }
  1412. // Tests that Int32FromGTestEnv() returns the default value when the
  1413. // environment variable does not represent a valid decimal integer.
  1414. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
  1415. printf("(expecting 2 warnings)\n");
  1416. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
  1417. EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
  1418. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
  1419. EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
  1420. }
  1421. // Tests that Int32FromGTestEnv() parses and returns the value of the
  1422. // environment variable when it represents a valid decimal integer in
  1423. // the range of an Int32.
  1424. TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
  1425. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
  1426. EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
  1427. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
  1428. EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
  1429. }
  1430. #endif // !GTEST_OS_WINDOWS_MOBILE
  1431. // Tests ParseInt32Flag().
  1432. // Tests that ParseInt32Flag() returns false and doesn't change the
  1433. // output value when the flag has wrong format
  1434. TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
  1435. Int32 value = 123;
  1436. EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
  1437. EXPECT_EQ(123, value);
  1438. EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
  1439. EXPECT_EQ(123, value);
  1440. }
  1441. // Tests that ParseInt32Flag() returns false and doesn't change the
  1442. // output value when the flag overflows as an Int32.
  1443. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
  1444. printf("(expecting 2 warnings)\n");
  1445. Int32 value = 123;
  1446. EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
  1447. EXPECT_EQ(123, value);
  1448. EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
  1449. EXPECT_EQ(123, value);
  1450. }
  1451. // Tests that ParseInt32Flag() returns false and doesn't change the
  1452. // output value when the flag does not represent a valid decimal
  1453. // integer.
  1454. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
  1455. printf("(expecting 2 warnings)\n");
  1456. Int32 value = 123;
  1457. EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
  1458. EXPECT_EQ(123, value);
  1459. EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
  1460. EXPECT_EQ(123, value);
  1461. }
  1462. // Tests that ParseInt32Flag() parses the value of the flag and
  1463. // returns true when the flag represents a valid decimal integer in
  1464. // the range of an Int32.
  1465. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
  1466. Int32 value = 123;
  1467. EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
  1468. EXPECT_EQ(456, value);
  1469. EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
  1470. "abc", &value));
  1471. EXPECT_EQ(-789, value);
  1472. }
  1473. // Tests that Int32FromEnvOrDie() parses the value of the var or
  1474. // returns the correct default.
  1475. // Environment variables are not supported on Windows CE.
  1476. #if !GTEST_OS_WINDOWS_MOBILE
  1477. TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
  1478. EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1479. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
  1480. EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1481. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
  1482. EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1483. }
  1484. #endif // !GTEST_OS_WINDOWS_MOBILE
  1485. // Tests that Int32FromEnvOrDie() aborts with an error message
  1486. // if the variable is not an Int32.
  1487. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
  1488. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
  1489. EXPECT_DEATH_IF_SUPPORTED(
  1490. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
  1491. ".*");
  1492. }
  1493. // Tests that Int32FromEnvOrDie() aborts with an error message
  1494. // if the variable cannot be represnted by an Int32.
  1495. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
  1496. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
  1497. EXPECT_DEATH_IF_SUPPORTED(
  1498. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
  1499. ".*");
  1500. }
  1501. // Tests that ShouldRunTestOnShard() selects all tests
  1502. // where there is 1 shard.
  1503. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
  1504. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
  1505. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
  1506. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
  1507. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
  1508. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
  1509. }
  1510. class ShouldShardTest : public testing::Test {
  1511. protected:
  1512. virtual void SetUp() {
  1513. index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
  1514. total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
  1515. }
  1516. virtual void TearDown() {
  1517. SetEnv(index_var_, "");
  1518. SetEnv(total_var_, "");
  1519. }
  1520. const char* index_var_;
  1521. const char* total_var_;
  1522. };
  1523. // Tests that sharding is disabled if neither of the environment variables
  1524. // are set.
  1525. TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
  1526. SetEnv(index_var_, "");
  1527. SetEnv(total_var_, "");
  1528. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1529. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1530. }
  1531. // Tests that sharding is not enabled if total_shards == 1.
  1532. TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
  1533. SetEnv(index_var_, "0");
  1534. SetEnv(total_var_, "1");
  1535. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1536. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1537. }
  1538. // Tests that sharding is enabled if total_shards > 1 and
  1539. // we are not in a death test subprocess.
  1540. // Environment variables are not supported on Windows CE.
  1541. #if !GTEST_OS_WINDOWS_MOBILE
  1542. TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
  1543. SetEnv(index_var_, "4");
  1544. SetEnv(total_var_, "22");
  1545. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1546. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1547. SetEnv(index_var_, "8");
  1548. SetEnv(total_var_, "9");
  1549. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1550. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1551. SetEnv(index_var_, "0");
  1552. SetEnv(total_var_, "9");
  1553. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1554. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1555. }
  1556. #endif // !GTEST_OS_WINDOWS_MOBILE
  1557. // Tests that we exit in error if the sharding values are not valid.
  1558. typedef ShouldShardTest ShouldShardDeathTest;
  1559. TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
  1560. SetEnv(index_var_, "4");
  1561. SetEnv(total_var_, "4");
  1562. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1563. SetEnv(index_var_, "4");
  1564. SetEnv(total_var_, "-2");
  1565. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1566. SetEnv(index_var_, "5");
  1567. SetEnv(total_var_, "");
  1568. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1569. SetEnv(index_var_, "");
  1570. SetEnv(total_var_, "5");
  1571. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1572. }
  1573. // Tests that ShouldRunTestOnShard is a partition when 5
  1574. // shards are used.
  1575. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
  1576. // Choose an arbitrary number of tests and shards.
  1577. const int num_tests = 17;
  1578. const int num_shards = 5;
  1579. // Check partitioning: each test should be on exactly 1 shard.
  1580. for (int test_id = 0; test_id < num_tests; test_id++) {
  1581. int prev_selected_shard_index = -1;
  1582. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1583. if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
  1584. if (prev_selected_shard_index < 0) {
  1585. prev_selected_shard_index = shard_index;
  1586. } else {
  1587. ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
  1588. << shard_index << " are both selected to run test " << test_id;
  1589. }
  1590. }
  1591. }
  1592. }
  1593. // Check balance: This is not required by the sharding protocol, but is a
  1594. // desirable property for performance.
  1595. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1596. int num_tests_on_shard = 0;
  1597. for (int test_id = 0; test_id < num_tests; test_id++) {
  1598. num_tests_on_shard +=
  1599. ShouldRunTestOnShard(num_shards, shard_index, test_id);
  1600. }
  1601. EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
  1602. }
  1603. }
  1604. // For the same reason we are not explicitly testing everything in the
  1605. // Test class, there are no separate tests for the following classes
  1606. // (except for some trivial cases):
  1607. //
  1608. // TestCase, UnitTest, UnitTestResultPrinter.
  1609. //
  1610. // Similarly, there are no separate tests for the following macros:
  1611. //
  1612. // TEST, TEST_F, RUN_ALL_TESTS
  1613. TEST(UnitTestTest, CanGetOriginalWorkingDir) {
  1614. ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
  1615. EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
  1616. }
  1617. TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
  1618. EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
  1619. EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
  1620. }
  1621. // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
  1622. // of various arities. They do not attempt to be exhaustive. Rather,
  1623. // view them as smoke tests that can be easily reviewed and verified.
  1624. // A more complete set of tests for predicate assertions can be found
  1625. // in gtest_pred_impl_unittest.cc.
  1626. // First, some predicates and predicate-formatters needed by the tests.
  1627. // Returns true iff the argument is an even number.
  1628. bool IsEven(int n) {
  1629. return (n % 2) == 0;
  1630. }
  1631. // A functor that returns true iff the argument is an even number.
  1632. struct IsEvenFunctor {
  1633. bool operator()(int n) { return IsEven(n); }
  1634. };
  1635. // A predicate-formatter function that asserts the argument is an even
  1636. // number.
  1637. AssertionResult AssertIsEven(const char* expr, int n) {
  1638. if (IsEven(n)) {
  1639. return AssertionSuccess();
  1640. }
  1641. Message msg;
  1642. msg << expr << " evaluates to " << n << ", which is not even.";
  1643. return AssertionFailure(msg);
  1644. }
  1645. // A predicate function that returns AssertionResult for use in
  1646. // EXPECT/ASSERT_TRUE/FALSE.
  1647. AssertionResult ResultIsEven(int n) {
  1648. if (IsEven(n))
  1649. return AssertionSuccess() << n << " is even";
  1650. else
  1651. return AssertionFailure() << n << " is odd";
  1652. }
  1653. // A predicate function that returns AssertionResult but gives no
  1654. // explanation why it succeeds. Needed for testing that
  1655. // EXPECT/ASSERT_FALSE handles such functions correctly.
  1656. AssertionResult ResultIsEvenNoExplanation(int n) {
  1657. if (IsEven(n))
  1658. return AssertionSuccess();
  1659. else
  1660. return AssertionFailure() << n << " is odd";
  1661. }
  1662. // A predicate-formatter functor that asserts the argument is an even
  1663. // number.
  1664. struct AssertIsEvenFunctor {
  1665. AssertionResult operator()(const char* expr, int n) {
  1666. return AssertIsEven(expr, n);
  1667. }
  1668. };
  1669. // Returns true iff the sum of the arguments is an even number.
  1670. bool SumIsEven2(int n1, int n2) {
  1671. return IsEven(n1 + n2);
  1672. }
  1673. // A functor that returns true iff the sum of the arguments is an even
  1674. // number.
  1675. struct SumIsEven3Functor {
  1676. bool operator()(int n1, int n2, int n3) {
  1677. return IsEven(n1 + n2 + n3);
  1678. }
  1679. };
  1680. // A predicate-formatter function that asserts the sum of the
  1681. // arguments is an even number.
  1682. AssertionResult AssertSumIsEven4(
  1683. const char* e1, const char* e2, const char* e3, const char* e4,
  1684. int n1, int n2, int n3, int n4) {
  1685. const int sum = n1 + n2 + n3 + n4;
  1686. if (IsEven(sum)) {
  1687. return AssertionSuccess();
  1688. }
  1689. Message msg;
  1690. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
  1691. << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
  1692. << ") evaluates to " << sum << ", which is not even.";
  1693. return AssertionFailure(msg);
  1694. }
  1695. // A predicate-formatter functor that asserts the sum of the arguments
  1696. // is an even number.
  1697. struct AssertSumIsEven5Functor {
  1698. AssertionResult operator()(
  1699. const char* e1, const char* e2, const char* e3, const char* e4,
  1700. const char* e5, int n1, int n2, int n3, int n4, int n5) {
  1701. const int sum = n1 + n2 + n3 + n4 + n5;
  1702. if (IsEven(sum)) {
  1703. return AssertionSuccess();
  1704. }
  1705. Message msg;
  1706. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
  1707. << " ("
  1708. << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
  1709. << ") evaluates to " << sum << ", which is not even.";
  1710. return AssertionFailure(msg);
  1711. }
  1712. };
  1713. // Tests unary predicate assertions.
  1714. // Tests unary predicate assertions that don't use a custom formatter.
  1715. TEST(Pred1Test, WithoutFormat) {
  1716. // Success cases.
  1717. EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
  1718. ASSERT_PRED1(IsEven, 4);
  1719. // Failure cases.
  1720. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1721. EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
  1722. }, "This failure is expected.");
  1723. EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
  1724. "evaluates to false");
  1725. }
  1726. // Tests unary predicate assertions that use a custom formatter.
  1727. TEST(Pred1Test, WithFormat) {
  1728. // Success cases.
  1729. EXPECT_PRED_FORMAT1(AssertIsEven, 2);
  1730. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
  1731. << "This failure is UNEXPECTED!";
  1732. // Failure cases.
  1733. const int n = 5;
  1734. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
  1735. "n evaluates to 5, which is not even.");
  1736. EXPECT_FATAL_FAILURE({ // NOLINT
  1737. ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
  1738. }, "This failure is expected.");
  1739. }
  1740. // Tests that unary predicate assertions evaluates their arguments
  1741. // exactly once.
  1742. TEST(Pred1Test, SingleEvaluationOnFailure) {
  1743. // A success case.
  1744. static int n = 0;
  1745. EXPECT_PRED1(IsEven, n++);
  1746. EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
  1747. // A failure case.
  1748. EXPECT_FATAL_FAILURE({ // NOLINT
  1749. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
  1750. << "This failure is expected.";
  1751. }, "This failure is expected.");
  1752. EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
  1753. }
  1754. // Tests predicate assertions whose arity is >= 2.
  1755. // Tests predicate assertions that don't use a custom formatter.
  1756. TEST(PredTest, WithoutFormat) {
  1757. // Success cases.
  1758. ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
  1759. EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
  1760. // Failure cases.
  1761. const int n1 = 1;
  1762. const int n2 = 2;
  1763. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1764. EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
  1765. }, "This failure is expected.");
  1766. EXPECT_FATAL_FAILURE({ // NOLINT
  1767. ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
  1768. }, "evaluates to false");
  1769. }
  1770. // Tests predicate assertions that use a custom formatter.
  1771. TEST(PredTest, WithFormat) {
  1772. // Success cases.
  1773. ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
  1774. "This failure is UNEXPECTED!";
  1775. EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
  1776. // Failure cases.
  1777. const int n1 = 1;
  1778. const int n2 = 2;
  1779. const int n3 = 4;
  1780. const int n4 = 6;
  1781. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1782. EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
  1783. }, "evaluates to 13, which is not even.");
  1784. EXPECT_FATAL_FAILURE({ // NOLINT
  1785. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
  1786. << "This failure is expected.";
  1787. }, "This failure is expected.");
  1788. }
  1789. // Tests that predicate assertions evaluates their arguments
  1790. // exactly once.
  1791. TEST(PredTest, SingleEvaluationOnFailure) {
  1792. // A success case.
  1793. int n1 = 0;
  1794. int n2 = 0;
  1795. EXPECT_PRED2(SumIsEven2, n1++, n2++);
  1796. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1797. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1798. // Another success case.
  1799. n1 = n2 = 0;
  1800. int n3 = 0;
  1801. int n4 = 0;
  1802. int n5 = 0;
  1803. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
  1804. n1++, n2++, n3++, n4++, n5++)
  1805. << "This failure is UNEXPECTED!";
  1806. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1807. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1808. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1809. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  1810. EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
  1811. // A failure case.
  1812. n1 = n2 = n3 = 0;
  1813. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1814. EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
  1815. << "This failure is expected.";
  1816. }, "This failure is expected.");
  1817. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1818. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1819. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1820. // Another failure case.
  1821. n1 = n2 = n3 = n4 = 0;
  1822. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1823. EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
  1824. }, "evaluates to 1, which is not even.");
  1825. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1826. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1827. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1828. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  1829. }
  1830. // Some helper functions for testing using overloaded/template
  1831. // functions with ASSERT_PREDn and EXPECT_PREDn.
  1832. bool IsPositive(double x) {
  1833. return x > 0;
  1834. }
  1835. template <typename T>
  1836. bool IsNegative(T x) {
  1837. return x < 0;
  1838. }
  1839. template <typename T1, typename T2>
  1840. bool GreaterThan(T1 x1, T2 x2) {
  1841. return x1 > x2;
  1842. }
  1843. // Tests that overloaded functions can be used in *_PRED* as long as
  1844. // their types are explicitly specified.
  1845. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
  1846. // C++Builder requires C-style casts rather than static_cast.
  1847. EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
  1848. ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
  1849. }
  1850. // Tests that template functions can be used in *_PRED* as long as
  1851. // their types are explicitly specified.
  1852. TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
  1853. EXPECT_PRED1(IsNegative<int>, -5);
  1854. // Makes sure that we can handle templates with more than one
  1855. // parameter.
  1856. ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
  1857. }
  1858. // Some helper functions for testing using overloaded/template
  1859. // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
  1860. AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
  1861. return n > 0 ? AssertionSuccess() :
  1862. AssertionFailure(Message() << "Failure");
  1863. }
  1864. AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
  1865. return x > 0 ? AssertionSuccess() :
  1866. AssertionFailure(Message() << "Failure");
  1867. }
  1868. template <typename T>
  1869. AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
  1870. return x < 0 ? AssertionSuccess() :
  1871. AssertionFailure(Message() << "Failure");
  1872. }
  1873. template <typename T1, typename T2>
  1874. AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
  1875. const T1& x1, const T2& x2) {
  1876. return x1 == x2 ? AssertionSuccess() :
  1877. AssertionFailure(Message() << "Failure");
  1878. }
  1879. // Tests that overloaded functions can be used in *_PRED_FORMAT*
  1880. // without explicitly specifying their types.
  1881. TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
  1882. EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
  1883. ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
  1884. }
  1885. // Tests that template functions can be used in *_PRED_FORMAT* without
  1886. // explicitly specifying their types.
  1887. TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
  1888. EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
  1889. ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
  1890. }
  1891. // Tests string assertions.
  1892. // Tests ASSERT_STREQ with non-NULL arguments.
  1893. TEST(StringAssertionTest, ASSERT_STREQ) {
  1894. const char * const p1 = "good";
  1895. ASSERT_STREQ(p1, p1);
  1896. // Let p2 have the same content as p1, but be at a different address.
  1897. const char p2[] = "good";
  1898. ASSERT_STREQ(p1, p2);
  1899. EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
  1900. "Expected: \"bad\"");
  1901. }
  1902. // Tests ASSERT_STREQ with NULL arguments.
  1903. TEST(StringAssertionTest, ASSERT_STREQ_Null) {
  1904. ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
  1905. EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
  1906. "non-null");
  1907. }
  1908. // Tests ASSERT_STREQ with NULL arguments.
  1909. TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
  1910. EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
  1911. "non-null");
  1912. }
  1913. // Tests ASSERT_STRNE.
  1914. TEST(StringAssertionTest, ASSERT_STRNE) {
  1915. ASSERT_STRNE("hi", "Hi");
  1916. ASSERT_STRNE("Hi", NULL);
  1917. ASSERT_STRNE(NULL, "Hi");
  1918. ASSERT_STRNE("", NULL);
  1919. ASSERT_STRNE(NULL, "");
  1920. ASSERT_STRNE("", "Hi");
  1921. ASSERT_STRNE("Hi", "");
  1922. EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
  1923. "\"Hi\" vs \"Hi\"");
  1924. }
  1925. // Tests ASSERT_STRCASEEQ.
  1926. TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
  1927. ASSERT_STRCASEEQ("hi", "Hi");
  1928. ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
  1929. ASSERT_STRCASEEQ("", "");
  1930. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
  1931. "(ignoring case)");
  1932. }
  1933. // Tests ASSERT_STRCASENE.
  1934. TEST(StringAssertionTest, ASSERT_STRCASENE) {
  1935. ASSERT_STRCASENE("hi1", "Hi2");
  1936. ASSERT_STRCASENE("Hi", NULL);
  1937. ASSERT_STRCASENE(NULL, "Hi");
  1938. ASSERT_STRCASENE("", NULL);
  1939. ASSERT_STRCASENE(NULL, "");
  1940. ASSERT_STRCASENE("", "Hi");
  1941. ASSERT_STRCASENE("Hi", "");
  1942. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
  1943. "(ignoring case)");
  1944. }
  1945. // Tests *_STREQ on wide strings.
  1946. TEST(StringAssertionTest, STREQ_Wide) {
  1947. // NULL strings.
  1948. ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
  1949. // Empty strings.
  1950. ASSERT_STREQ(L"", L"");
  1951. // Non-null vs NULL.
  1952. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
  1953. "non-null");
  1954. // Equal strings.
  1955. EXPECT_STREQ(L"Hi", L"Hi");
  1956. // Unequal strings.
  1957. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
  1958. "Abc");
  1959. // Strings containing wide characters.
  1960. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
  1961. "abc");
  1962. // The streaming variation.
  1963. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1964. EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
  1965. }, "Expected failure");
  1966. }
  1967. // Tests *_STRNE on wide strings.
  1968. TEST(StringAssertionTest, STRNE_Wide) {
  1969. // NULL strings.
  1970. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1971. EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
  1972. }, "");
  1973. // Empty strings.
  1974. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
  1975. "L\"\"");
  1976. // Non-null vs NULL.
  1977. ASSERT_STRNE(L"non-null", NULL);
  1978. // Equal strings.
  1979. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
  1980. "L\"Hi\"");
  1981. // Unequal strings.
  1982. EXPECT_STRNE(L"abc", L"Abc");
  1983. // Strings containing wide characters.
  1984. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
  1985. "abc");
  1986. // The streaming variation.
  1987. ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
  1988. }
  1989. // Tests for ::testing::IsSubstring().
  1990. // Tests that IsSubstring() returns the correct result when the input
  1991. // argument type is const char*.
  1992. TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
  1993. EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
  1994. EXPECT_FALSE(IsSubstring("", "", "b", NULL));
  1995. EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
  1996. EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
  1997. EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
  1998. }
  1999. // Tests that IsSubstring() returns the correct result when the input
  2000. // argument type is const wchar_t*.
  2001. TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
  2002. EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
  2003. EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
  2004. EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
  2005. EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
  2006. EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
  2007. }
  2008. // Tests that IsSubstring() generates the correct message when the input
  2009. // argument type is const char*.
  2010. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
  2011. EXPECT_STREQ("Value of: needle_expr\n"
  2012. " Actual: \"needle\"\n"
  2013. "Expected: a substring of haystack_expr\n"
  2014. "Which is: \"haystack\"",
  2015. IsSubstring("needle_expr", "haystack_expr",
  2016. "needle", "haystack").failure_message());
  2017. }
  2018. // Tests that IsSubstring returns the correct result when the input
  2019. // argument type is ::std::string.
  2020. TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
  2021. EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
  2022. EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
  2023. }
  2024. #if GTEST_HAS_STD_WSTRING
  2025. // Tests that IsSubstring returns the correct result when the input
  2026. // argument type is ::std::wstring.
  2027. TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
  2028. EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2029. EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2030. }
  2031. // Tests that IsSubstring() generates the correct message when the input
  2032. // argument type is ::std::wstring.
  2033. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
  2034. EXPECT_STREQ("Value of: needle_expr\n"
  2035. " Actual: L\"needle\"\n"
  2036. "Expected: a substring of haystack_expr\n"
  2037. "Which is: L\"haystack\"",
  2038. IsSubstring(
  2039. "needle_expr", "haystack_expr",
  2040. ::std::wstring(L"needle"), L"haystack").failure_message());
  2041. }
  2042. #endif // GTEST_HAS_STD_WSTRING
  2043. // Tests for ::testing::IsNotSubstring().
  2044. // Tests that IsNotSubstring() returns the correct result when the input
  2045. // argument type is const char*.
  2046. TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
  2047. EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
  2048. EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
  2049. }
  2050. // Tests that IsNotSubstring() returns the correct result when the input
  2051. // argument type is const wchar_t*.
  2052. TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
  2053. EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
  2054. EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
  2055. }
  2056. // Tests that IsNotSubstring() generates the correct message when the input
  2057. // argument type is const wchar_t*.
  2058. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
  2059. EXPECT_STREQ("Value of: needle_expr\n"
  2060. " Actual: L\"needle\"\n"
  2061. "Expected: not a substring of haystack_expr\n"
  2062. "Which is: L\"two needles\"",
  2063. IsNotSubstring(
  2064. "needle_expr", "haystack_expr",
  2065. L"needle", L"two needles").failure_message());
  2066. }
  2067. // Tests that IsNotSubstring returns the correct result when the input
  2068. // argument type is ::std::string.
  2069. TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
  2070. EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
  2071. EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
  2072. }
  2073. // Tests that IsNotSubstring() generates the correct message when the input
  2074. // argument type is ::std::string.
  2075. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
  2076. EXPECT_STREQ("Value of: needle_expr\n"
  2077. " Actual: \"needle\"\n"
  2078. "Expected: not a substring of haystack_expr\n"
  2079. "Which is: \"two needles\"",
  2080. IsNotSubstring(
  2081. "needle_expr", "haystack_expr",
  2082. ::std::string("needle"), "two needles").failure_message());
  2083. }
  2084. #if GTEST_HAS_STD_WSTRING
  2085. // Tests that IsNotSubstring returns the correct result when the input
  2086. // argument type is ::std::wstring.
  2087. TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
  2088. EXPECT_FALSE(
  2089. IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2090. EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2091. }
  2092. #endif // GTEST_HAS_STD_WSTRING
  2093. // Tests floating-point assertions.
  2094. template <typename RawType>
  2095. class FloatingPointTest : public Test {
  2096. protected:
  2097. // Pre-calculated numbers to be used by the tests.
  2098. struct TestValues {
  2099. RawType close_to_positive_zero;
  2100. RawType close_to_negative_zero;
  2101. RawType further_from_negative_zero;
  2102. RawType close_to_one;
  2103. RawType further_from_one;
  2104. RawType infinity;
  2105. RawType close_to_infinity;
  2106. RawType further_from_infinity;
  2107. RawType nan1;
  2108. RawType nan2;
  2109. };
  2110. typedef typename testing::internal::FloatingPoint<RawType> Floating;
  2111. typedef typename Floating::Bits Bits;
  2112. virtual void SetUp() {
  2113. const size_t max_ulps = Floating::kMaxUlps;
  2114. // The bits that represent 0.0.
  2115. const Bits zero_bits = Floating(0).bits();
  2116. // Makes some numbers close to 0.0.
  2117. values_.close_to_positive_zero = Floating::ReinterpretBits(
  2118. zero_bits + max_ulps/2);
  2119. values_.close_to_negative_zero = -Floating::ReinterpretBits(
  2120. zero_bits + max_ulps - max_ulps/2);
  2121. values_.further_from_negative_zero = -Floating::ReinterpretBits(
  2122. zero_bits + max_ulps + 1 - max_ulps/2);
  2123. // The bits that represent 1.0.
  2124. const Bits one_bits = Floating(1).bits();
  2125. // Makes some numbers close to 1.0.
  2126. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
  2127. values_.further_from_one = Floating::ReinterpretBits(
  2128. one_bits + max_ulps + 1);
  2129. // +infinity.
  2130. values_.infinity = Floating::Infinity();
  2131. // The bits that represent +infinity.
  2132. const Bits infinity_bits = Floating(values_.infinity).bits();
  2133. // Makes some numbers close to infinity.
  2134. values_.close_to_infinity = Floating::ReinterpretBits(
  2135. infinity_bits - max_ulps);
  2136. values_.further_from_infinity = Floating::ReinterpretBits(
  2137. infinity_bits - max_ulps - 1);
  2138. // Makes some NAN's. Sets the most significant bit of the fraction so that
  2139. // our NaN's are quiet; trying to process a signaling NaN would raise an
  2140. // exception if our environment enables floating point exceptions.
  2141. values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
  2142. | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
  2143. values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
  2144. | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
  2145. }
  2146. void TestSize() {
  2147. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2148. }
  2149. static TestValues values_;
  2150. };
  2151. template <typename RawType>
  2152. typename FloatingPointTest<RawType>::TestValues
  2153. FloatingPointTest<RawType>::values_;
  2154. // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
  2155. typedef FloatingPointTest<float> FloatTest;
  2156. // Tests that the size of Float::Bits matches the size of float.
  2157. TEST_F(FloatTest, Size) {
  2158. TestSize();
  2159. }
  2160. // Tests comparing with +0 and -0.
  2161. TEST_F(FloatTest, Zeros) {
  2162. EXPECT_FLOAT_EQ(0.0, -0.0);
  2163. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
  2164. "1.0");
  2165. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
  2166. "1.5");
  2167. }
  2168. // Tests comparing numbers close to 0.
  2169. //
  2170. // This ensures that *_FLOAT_EQ handles the sign correctly and no
  2171. // overflow occurs when comparing numbers whose absolute value is very
  2172. // small.
  2173. TEST_F(FloatTest, AlmostZeros) {
  2174. // In C++Builder, names within local classes (such as used by
  2175. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2176. // scoping class. Use a static local alias as a workaround.
  2177. // We use the assignment syntax since some compilers, like Sun Studio,
  2178. // don't allow initializing references using construction syntax
  2179. // (parentheses).
  2180. static const FloatTest::TestValues& v = this->values_;
  2181. EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
  2182. EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
  2183. EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2184. EXPECT_FATAL_FAILURE({ // NOLINT
  2185. ASSERT_FLOAT_EQ(v.close_to_positive_zero,
  2186. v.further_from_negative_zero);
  2187. }, "v.further_from_negative_zero");
  2188. }
  2189. // Tests comparing numbers close to each other.
  2190. TEST_F(FloatTest, SmallDiff) {
  2191. EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
  2192. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
  2193. "values_.further_from_one");
  2194. }
  2195. // Tests comparing numbers far apart.
  2196. TEST_F(FloatTest, LargeDiff) {
  2197. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
  2198. "3.0");
  2199. }
  2200. // Tests comparing with infinity.
  2201. //
  2202. // This ensures that no overflow occurs when comparing numbers whose
  2203. // absolute value is very large.
  2204. TEST_F(FloatTest, Infinity) {
  2205. EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
  2206. EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
  2207. #if !GTEST_OS_SYMBIAN
  2208. // Nokia's STLport crashes if we try to output infinity or NaN.
  2209. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
  2210. "-values_.infinity");
  2211. // This is interesting as the representations of infinity and nan1
  2212. // are only 1 DLP apart.
  2213. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
  2214. "values_.nan1");
  2215. #endif // !GTEST_OS_SYMBIAN
  2216. }
  2217. // Tests that comparing with NAN always returns false.
  2218. TEST_F(FloatTest, NaN) {
  2219. #if !GTEST_OS_SYMBIAN
  2220. // Nokia's STLport crashes if we try to output infinity or NaN.
  2221. // In C++Builder, names within local classes (such as used by
  2222. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2223. // scoping class. Use a static local alias as a workaround.
  2224. // We use the assignment syntax since some compilers, like Sun Studio,
  2225. // don't allow initializing references using construction syntax
  2226. // (parentheses).
  2227. static const FloatTest::TestValues& v = this->values_;
  2228. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
  2229. "v.nan1");
  2230. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
  2231. "v.nan2");
  2232. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
  2233. "v.nan1");
  2234. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
  2235. "v.infinity");
  2236. #endif // !GTEST_OS_SYMBIAN
  2237. }
  2238. // Tests that *_FLOAT_EQ are reflexive.
  2239. TEST_F(FloatTest, Reflexive) {
  2240. EXPECT_FLOAT_EQ(0.0, 0.0);
  2241. EXPECT_FLOAT_EQ(1.0, 1.0);
  2242. ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
  2243. }
  2244. // Tests that *_FLOAT_EQ are commutative.
  2245. TEST_F(FloatTest, Commutative) {
  2246. // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
  2247. EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
  2248. // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
  2249. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
  2250. "1.0");
  2251. }
  2252. // Tests EXPECT_NEAR.
  2253. TEST_F(FloatTest, EXPECT_NEAR) {
  2254. EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
  2255. EXPECT_NEAR(2.0f, 3.0f, 1.0f);
  2256. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
  2257. "The difference between 1.0f and 1.5f is 0.5, "
  2258. "which exceeds 0.25f");
  2259. // To work around a bug in gcc 2.95.0, there is intentionally no
  2260. // space after the first comma in the previous line.
  2261. }
  2262. // Tests ASSERT_NEAR.
  2263. TEST_F(FloatTest, ASSERT_NEAR) {
  2264. ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
  2265. ASSERT_NEAR(2.0f, 3.0f, 1.0f);
  2266. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
  2267. "The difference between 1.0f and 1.5f is 0.5, "
  2268. "which exceeds 0.25f");
  2269. // To work around a bug in gcc 2.95.0, there is intentionally no
  2270. // space after the first comma in the previous line.
  2271. }
  2272. // Tests the cases where FloatLE() should succeed.
  2273. TEST_F(FloatTest, FloatLESucceeds) {
  2274. EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
  2275. ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
  2276. // or when val1 is greater than, but almost equals to, val2.
  2277. EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
  2278. }
  2279. // Tests the cases where FloatLE() should fail.
  2280. TEST_F(FloatTest, FloatLEFails) {
  2281. // When val1 is greater than val2 by a large margin,
  2282. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
  2283. "(2.0f) <= (1.0f)");
  2284. // or by a small yet non-negligible margin,
  2285. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2286. EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
  2287. }, "(values_.further_from_one) <= (1.0f)");
  2288. #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2289. // Nokia's STLport crashes if we try to output infinity or NaN.
  2290. // C++Builder gives bad results for ordered comparisons involving NaNs
  2291. // due to compiler bugs.
  2292. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2293. EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
  2294. }, "(values_.nan1) <= (values_.infinity)");
  2295. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2296. EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
  2297. }, "(-values_.infinity) <= (values_.nan1)");
  2298. EXPECT_FATAL_FAILURE({ // NOLINT
  2299. ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
  2300. }, "(values_.nan1) <= (values_.nan1)");
  2301. #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2302. }
  2303. // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
  2304. typedef FloatingPointTest<double> DoubleTest;
  2305. // Tests that the size of Double::Bits matches the size of double.
  2306. TEST_F(DoubleTest, Size) {
  2307. TestSize();
  2308. }
  2309. // Tests comparing with +0 and -0.
  2310. TEST_F(DoubleTest, Zeros) {
  2311. EXPECT_DOUBLE_EQ(0.0, -0.0);
  2312. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
  2313. "1.0");
  2314. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
  2315. "1.0");
  2316. }
  2317. // Tests comparing numbers close to 0.
  2318. //
  2319. // This ensures that *_DOUBLE_EQ handles the sign correctly and no
  2320. // overflow occurs when comparing numbers whose absolute value is very
  2321. // small.
  2322. TEST_F(DoubleTest, AlmostZeros) {
  2323. // In C++Builder, names within local classes (such as used by
  2324. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2325. // scoping class. Use a static local alias as a workaround.
  2326. // We use the assignment syntax since some compilers, like Sun Studio,
  2327. // don't allow initializing references using construction syntax
  2328. // (parentheses).
  2329. static const DoubleTest::TestValues& v = this->values_;
  2330. EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
  2331. EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
  2332. EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2333. EXPECT_FATAL_FAILURE({ // NOLINT
  2334. ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
  2335. v.further_from_negative_zero);
  2336. }, "v.further_from_negative_zero");
  2337. }
  2338. // Tests comparing numbers close to each other.
  2339. TEST_F(DoubleTest, SmallDiff) {
  2340. EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
  2341. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
  2342. "values_.further_from_one");
  2343. }
  2344. // Tests comparing numbers far apart.
  2345. TEST_F(DoubleTest, LargeDiff) {
  2346. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
  2347. "3.0");
  2348. }
  2349. // Tests comparing with infinity.
  2350. //
  2351. // This ensures that no overflow occurs when comparing numbers whose
  2352. // absolute value is very large.
  2353. TEST_F(DoubleTest, Infinity) {
  2354. EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
  2355. EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
  2356. #if !GTEST_OS_SYMBIAN
  2357. // Nokia's STLport crashes if we try to output infinity or NaN.
  2358. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
  2359. "-values_.infinity");
  2360. // This is interesting as the representations of infinity_ and nan1_
  2361. // are only 1 DLP apart.
  2362. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
  2363. "values_.nan1");
  2364. #endif // !GTEST_OS_SYMBIAN
  2365. }
  2366. // Tests that comparing with NAN always returns false.
  2367. TEST_F(DoubleTest, NaN) {
  2368. #if !GTEST_OS_SYMBIAN
  2369. // In C++Builder, names within local classes (such as used by
  2370. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2371. // scoping class. Use a static local alias as a workaround.
  2372. // We use the assignment syntax since some compilers, like Sun Studio,
  2373. // don't allow initializing references using construction syntax
  2374. // (parentheses).
  2375. static const DoubleTest::TestValues& v = this->values_;
  2376. // Nokia's STLport crashes if we try to output infinity or NaN.
  2377. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
  2378. "v.nan1");
  2379. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
  2380. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
  2381. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
  2382. "v.infinity");
  2383. #endif // !GTEST_OS_SYMBIAN
  2384. }
  2385. // Tests that *_DOUBLE_EQ are reflexive.
  2386. TEST_F(DoubleTest, Reflexive) {
  2387. EXPECT_DOUBLE_EQ(0.0, 0.0);
  2388. EXPECT_DOUBLE_EQ(1.0, 1.0);
  2389. #if !GTEST_OS_SYMBIAN
  2390. // Nokia's STLport crashes if we try to output infinity or NaN.
  2391. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
  2392. #endif // !GTEST_OS_SYMBIAN
  2393. }
  2394. // Tests that *_DOUBLE_EQ are commutative.
  2395. TEST_F(DoubleTest, Commutative) {
  2396. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
  2397. EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
  2398. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
  2399. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
  2400. "1.0");
  2401. }
  2402. // Tests EXPECT_NEAR.
  2403. TEST_F(DoubleTest, EXPECT_NEAR) {
  2404. EXPECT_NEAR(-1.0, -1.1, 0.2);
  2405. EXPECT_NEAR(2.0, 3.0, 1.0);
  2406. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2407. "The difference between 1.0 and 1.5 is 0.5, "
  2408. "which exceeds 0.25");
  2409. // To work around a bug in gcc 2.95.0, there is intentionally no
  2410. // space after the first comma in the previous statement.
  2411. }
  2412. // Tests ASSERT_NEAR.
  2413. TEST_F(DoubleTest, ASSERT_NEAR) {
  2414. ASSERT_NEAR(-1.0, -1.1, 0.2);
  2415. ASSERT_NEAR(2.0, 3.0, 1.0);
  2416. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2417. "The difference between 1.0 and 1.5 is 0.5, "
  2418. "which exceeds 0.25");
  2419. // To work around a bug in gcc 2.95.0, there is intentionally no
  2420. // space after the first comma in the previous statement.
  2421. }
  2422. // Tests the cases where DoubleLE() should succeed.
  2423. TEST_F(DoubleTest, DoubleLESucceeds) {
  2424. EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
  2425. ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
  2426. // or when val1 is greater than, but almost equals to, val2.
  2427. EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
  2428. }
  2429. // Tests the cases where DoubleLE() should fail.
  2430. TEST_F(DoubleTest, DoubleLEFails) {
  2431. // When val1 is greater than val2 by a large margin,
  2432. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
  2433. "(2.0) <= (1.0)");
  2434. // or by a small yet non-negligible margin,
  2435. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2436. EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
  2437. }, "(values_.further_from_one) <= (1.0)");
  2438. #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2439. // Nokia's STLport crashes if we try to output infinity or NaN.
  2440. // C++Builder gives bad results for ordered comparisons involving NaNs
  2441. // due to compiler bugs.
  2442. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2443. EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
  2444. }, "(values_.nan1) <= (values_.infinity)");
  2445. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2446. EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
  2447. }, " (-values_.infinity) <= (values_.nan1)");
  2448. EXPECT_FATAL_FAILURE({ // NOLINT
  2449. ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
  2450. }, "(values_.nan1) <= (values_.nan1)");
  2451. #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2452. }
  2453. // Verifies that a test or test case whose name starts with DISABLED_ is
  2454. // not run.
  2455. // A test whose name starts with DISABLED_.
  2456. // Should not run.
  2457. TEST(DisabledTest, DISABLED_TestShouldNotRun) {
  2458. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2459. }
  2460. // A test whose name does not start with DISABLED_.
  2461. // Should run.
  2462. TEST(DisabledTest, NotDISABLED_TestShouldRun) {
  2463. EXPECT_EQ(1, 1);
  2464. }
  2465. // A test case whose name starts with DISABLED_.
  2466. // Should not run.
  2467. TEST(DISABLED_TestCase, TestShouldNotRun) {
  2468. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2469. }
  2470. // A test case and test whose names start with DISABLED_.
  2471. // Should not run.
  2472. TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
  2473. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2474. }
  2475. // Check that when all tests in a test case are disabled, SetupTestCase() and
  2476. // TearDownTestCase() are not called.
  2477. class DisabledTestsTest : public Test {
  2478. protected:
  2479. static void SetUpTestCase() {
  2480. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2481. "SetupTestCase() should not be called.";
  2482. }
  2483. static void TearDownTestCase() {
  2484. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2485. "TearDownTestCase() should not be called.";
  2486. }
  2487. };
  2488. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
  2489. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2490. }
  2491. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
  2492. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2493. }
  2494. // Tests that disabled typed tests aren't run.
  2495. #if GTEST_HAS_TYPED_TEST
  2496. template <typename T>
  2497. class TypedTest : public Test {
  2498. };
  2499. typedef testing::Types<int, double> NumericTypes;
  2500. TYPED_TEST_CASE(TypedTest, NumericTypes);
  2501. TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
  2502. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2503. }
  2504. template <typename T>
  2505. class DISABLED_TypedTest : public Test {
  2506. };
  2507. TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
  2508. TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
  2509. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2510. }
  2511. #endif // GTEST_HAS_TYPED_TEST
  2512. // Tests that disabled type-parameterized tests aren't run.
  2513. #if GTEST_HAS_TYPED_TEST_P
  2514. template <typename T>
  2515. class TypedTestP : public Test {
  2516. };
  2517. TYPED_TEST_CASE_P(TypedTestP);
  2518. TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
  2519. FAIL() << "Unexpected failure: "
  2520. << "Disabled type-parameterized test should not run.";
  2521. }
  2522. REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
  2523. INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
  2524. template <typename T>
  2525. class DISABLED_TypedTestP : public Test {
  2526. };
  2527. TYPED_TEST_CASE_P(DISABLED_TypedTestP);
  2528. TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
  2529. FAIL() << "Unexpected failure: "
  2530. << "Disabled type-parameterized test should not run.";
  2531. }
  2532. REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
  2533. INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
  2534. #endif // GTEST_HAS_TYPED_TEST_P
  2535. // Tests that assertion macros evaluate their arguments exactly once.
  2536. class SingleEvaluationTest : public Test {
  2537. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  2538. // This helper function is needed by the FailedASSERT_STREQ test
  2539. // below. It's public to work around C++Builder's bug with scoping local
  2540. // classes.
  2541. static void CompareAndIncrementCharPtrs() {
  2542. ASSERT_STREQ(p1_++, p2_++);
  2543. }
  2544. // This helper function is needed by the FailedASSERT_NE test below. It's
  2545. // public to work around C++Builder's bug with scoping local classes.
  2546. static void CompareAndIncrementInts() {
  2547. ASSERT_NE(a_++, b_++);
  2548. }
  2549. protected:
  2550. SingleEvaluationTest() {
  2551. p1_ = s1_;
  2552. p2_ = s2_;
  2553. a_ = 0;
  2554. b_ = 0;
  2555. }
  2556. static const char* const s1_;
  2557. static const char* const s2_;
  2558. static const char* p1_;
  2559. static const char* p2_;
  2560. static int a_;
  2561. static int b_;
  2562. };
  2563. const char* const SingleEvaluationTest::s1_ = "01234";
  2564. const char* const SingleEvaluationTest::s2_ = "abcde";
  2565. const char* SingleEvaluationTest::p1_;
  2566. const char* SingleEvaluationTest::p2_;
  2567. int SingleEvaluationTest::a_;
  2568. int SingleEvaluationTest::b_;
  2569. // Tests that when ASSERT_STREQ fails, it evaluates its arguments
  2570. // exactly once.
  2571. TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
  2572. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
  2573. "p2_++");
  2574. EXPECT_EQ(s1_ + 1, p1_);
  2575. EXPECT_EQ(s2_ + 1, p2_);
  2576. }
  2577. // Tests that string assertion arguments are evaluated exactly once.
  2578. TEST_F(SingleEvaluationTest, ASSERT_STR) {
  2579. // successful EXPECT_STRNE
  2580. EXPECT_STRNE(p1_++, p2_++);
  2581. EXPECT_EQ(s1_ + 1, p1_);
  2582. EXPECT_EQ(s2_ + 1, p2_);
  2583. // failed EXPECT_STRCASEEQ
  2584. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
  2585. "ignoring case");
  2586. EXPECT_EQ(s1_ + 2, p1_);
  2587. EXPECT_EQ(s2_ + 2, p2_);
  2588. }
  2589. // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
  2590. // once.
  2591. TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
  2592. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
  2593. "(a_++) != (b_++)");
  2594. EXPECT_EQ(1, a_);
  2595. EXPECT_EQ(1, b_);
  2596. }
  2597. // Tests that assertion arguments are evaluated exactly once.
  2598. TEST_F(SingleEvaluationTest, OtherCases) {
  2599. // successful EXPECT_TRUE
  2600. EXPECT_TRUE(0 == a_++); // NOLINT
  2601. EXPECT_EQ(1, a_);
  2602. // failed EXPECT_TRUE
  2603. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
  2604. EXPECT_EQ(2, a_);
  2605. // successful EXPECT_GT
  2606. EXPECT_GT(a_++, b_++);
  2607. EXPECT_EQ(3, a_);
  2608. EXPECT_EQ(1, b_);
  2609. // failed EXPECT_LT
  2610. EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
  2611. EXPECT_EQ(4, a_);
  2612. EXPECT_EQ(2, b_);
  2613. // successful ASSERT_TRUE
  2614. ASSERT_TRUE(0 < a_++); // NOLINT
  2615. EXPECT_EQ(5, a_);
  2616. // successful ASSERT_GT
  2617. ASSERT_GT(a_++, b_++);
  2618. EXPECT_EQ(6, a_);
  2619. EXPECT_EQ(3, b_);
  2620. }
  2621. #if GTEST_HAS_EXCEPTIONS
  2622. void ThrowAnInteger() {
  2623. throw 1;
  2624. }
  2625. // Tests that assertion arguments are evaluated exactly once.
  2626. TEST_F(SingleEvaluationTest, ExceptionTests) {
  2627. // successful EXPECT_THROW
  2628. EXPECT_THROW({ // NOLINT
  2629. a_++;
  2630. ThrowAnInteger();
  2631. }, int);
  2632. EXPECT_EQ(1, a_);
  2633. // failed EXPECT_THROW, throws different
  2634. EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
  2635. a_++;
  2636. ThrowAnInteger();
  2637. }, bool), "throws a different type");
  2638. EXPECT_EQ(2, a_);
  2639. // failed EXPECT_THROW, throws nothing
  2640. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
  2641. EXPECT_EQ(3, a_);
  2642. // successful EXPECT_NO_THROW
  2643. EXPECT_NO_THROW(a_++);
  2644. EXPECT_EQ(4, a_);
  2645. // failed EXPECT_NO_THROW
  2646. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
  2647. a_++;
  2648. ThrowAnInteger();
  2649. }), "it throws");
  2650. EXPECT_EQ(5, a_);
  2651. // successful EXPECT_ANY_THROW
  2652. EXPECT_ANY_THROW({ // NOLINT
  2653. a_++;
  2654. ThrowAnInteger();
  2655. });
  2656. EXPECT_EQ(6, a_);
  2657. // failed EXPECT_ANY_THROW
  2658. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
  2659. EXPECT_EQ(7, a_);
  2660. }
  2661. #endif // GTEST_HAS_EXCEPTIONS
  2662. // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
  2663. class NoFatalFailureTest : public Test {
  2664. protected:
  2665. void Succeeds() {}
  2666. void FailsNonFatal() {
  2667. ADD_FAILURE() << "some non-fatal failure";
  2668. }
  2669. void Fails() {
  2670. FAIL() << "some fatal failure";
  2671. }
  2672. void DoAssertNoFatalFailureOnFails() {
  2673. ASSERT_NO_FATAL_FAILURE(Fails());
  2674. ADD_FAILURE() << "shold not reach here.";
  2675. }
  2676. void DoExpectNoFatalFailureOnFails() {
  2677. EXPECT_NO_FATAL_FAILURE(Fails());
  2678. ADD_FAILURE() << "other failure";
  2679. }
  2680. };
  2681. TEST_F(NoFatalFailureTest, NoFailure) {
  2682. EXPECT_NO_FATAL_FAILURE(Succeeds());
  2683. ASSERT_NO_FATAL_FAILURE(Succeeds());
  2684. }
  2685. TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
  2686. EXPECT_NONFATAL_FAILURE(
  2687. EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
  2688. "some non-fatal failure");
  2689. EXPECT_NONFATAL_FAILURE(
  2690. ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
  2691. "some non-fatal failure");
  2692. }
  2693. TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
  2694. TestPartResultArray gtest_failures;
  2695. {
  2696. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2697. DoAssertNoFatalFailureOnFails();
  2698. }
  2699. ASSERT_EQ(2, gtest_failures.size());
  2700. EXPECT_EQ(TestPartResult::kFatalFailure,
  2701. gtest_failures.GetTestPartResult(0).type());
  2702. EXPECT_EQ(TestPartResult::kFatalFailure,
  2703. gtest_failures.GetTestPartResult(1).type());
  2704. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2705. gtest_failures.GetTestPartResult(0).message());
  2706. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2707. gtest_failures.GetTestPartResult(1).message());
  2708. }
  2709. TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
  2710. TestPartResultArray gtest_failures;
  2711. {
  2712. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2713. DoExpectNoFatalFailureOnFails();
  2714. }
  2715. ASSERT_EQ(3, gtest_failures.size());
  2716. EXPECT_EQ(TestPartResult::kFatalFailure,
  2717. gtest_failures.GetTestPartResult(0).type());
  2718. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2719. gtest_failures.GetTestPartResult(1).type());
  2720. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2721. gtest_failures.GetTestPartResult(2).type());
  2722. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2723. gtest_failures.GetTestPartResult(0).message());
  2724. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2725. gtest_failures.GetTestPartResult(1).message());
  2726. EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
  2727. gtest_failures.GetTestPartResult(2).message());
  2728. }
  2729. TEST_F(NoFatalFailureTest, MessageIsStreamable) {
  2730. TestPartResultArray gtest_failures;
  2731. {
  2732. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2733. EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
  2734. }
  2735. ASSERT_EQ(2, gtest_failures.size());
  2736. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2737. gtest_failures.GetTestPartResult(0).type());
  2738. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2739. gtest_failures.GetTestPartResult(1).type());
  2740. EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
  2741. gtest_failures.GetTestPartResult(0).message());
  2742. EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
  2743. gtest_failures.GetTestPartResult(1).message());
  2744. }
  2745. // Tests non-string assertions.
  2746. // Tests EqFailure(), used for implementing *EQ* assertions.
  2747. TEST(AssertionTest, EqFailure) {
  2748. const std::string foo_val("5"), bar_val("6");
  2749. const std::string msg1(
  2750. EqFailure("foo", "bar", foo_val, bar_val, false)
  2751. .failure_message());
  2752. EXPECT_STREQ(
  2753. "Value of: bar\n"
  2754. " Actual: 6\n"
  2755. "Expected: foo\n"
  2756. "Which is: 5",
  2757. msg1.c_str());
  2758. const std::string msg2(
  2759. EqFailure("foo", "6", foo_val, bar_val, false)
  2760. .failure_message());
  2761. EXPECT_STREQ(
  2762. "Value of: 6\n"
  2763. "Expected: foo\n"
  2764. "Which is: 5",
  2765. msg2.c_str());
  2766. const std::string msg3(
  2767. EqFailure("5", "bar", foo_val, bar_val, false)
  2768. .failure_message());
  2769. EXPECT_STREQ(
  2770. "Value of: bar\n"
  2771. " Actual: 6\n"
  2772. "Expected: 5",
  2773. msg3.c_str());
  2774. const std::string msg4(
  2775. EqFailure("5", "6", foo_val, bar_val, false).failure_message());
  2776. EXPECT_STREQ(
  2777. "Value of: 6\n"
  2778. "Expected: 5",
  2779. msg4.c_str());
  2780. const std::string msg5(
  2781. EqFailure("foo", "bar",
  2782. std::string("\"x\""), std::string("\"y\""),
  2783. true).failure_message());
  2784. EXPECT_STREQ(
  2785. "Value of: bar\n"
  2786. " Actual: \"y\"\n"
  2787. "Expected: foo (ignoring case)\n"
  2788. "Which is: \"x\"",
  2789. msg5.c_str());
  2790. }
  2791. // Tests AppendUserMessage(), used for implementing the *EQ* macros.
  2792. TEST(AssertionTest, AppendUserMessage) {
  2793. const std::string foo("foo");
  2794. Message msg;
  2795. EXPECT_STREQ("foo",
  2796. AppendUserMessage(foo, msg).c_str());
  2797. msg << "bar";
  2798. EXPECT_STREQ("foo\nbar",
  2799. AppendUserMessage(foo, msg).c_str());
  2800. }
  2801. #ifdef __BORLANDC__
  2802. // Silences warnings: "Condition is always true", "Unreachable code"
  2803. # pragma option push -w-ccc -w-rch
  2804. #endif
  2805. // Tests ASSERT_TRUE.
  2806. TEST(AssertionTest, ASSERT_TRUE) {
  2807. ASSERT_TRUE(2 > 1); // NOLINT
  2808. EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
  2809. "2 < 1");
  2810. }
  2811. // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
  2812. TEST(AssertionTest, AssertTrueWithAssertionResult) {
  2813. ASSERT_TRUE(ResultIsEven(2));
  2814. #ifndef __BORLANDC__
  2815. // ICE's in C++Builder.
  2816. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
  2817. "Value of: ResultIsEven(3)\n"
  2818. " Actual: false (3 is odd)\n"
  2819. "Expected: true");
  2820. #endif
  2821. ASSERT_TRUE(ResultIsEvenNoExplanation(2));
  2822. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
  2823. "Value of: ResultIsEvenNoExplanation(3)\n"
  2824. " Actual: false (3 is odd)\n"
  2825. "Expected: true");
  2826. }
  2827. // Tests ASSERT_FALSE.
  2828. TEST(AssertionTest, ASSERT_FALSE) {
  2829. ASSERT_FALSE(2 < 1); // NOLINT
  2830. EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
  2831. "Value of: 2 > 1\n"
  2832. " Actual: true\n"
  2833. "Expected: false");
  2834. }
  2835. // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
  2836. TEST(AssertionTest, AssertFalseWithAssertionResult) {
  2837. ASSERT_FALSE(ResultIsEven(3));
  2838. #ifndef __BORLANDC__
  2839. // ICE's in C++Builder.
  2840. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
  2841. "Value of: ResultIsEven(2)\n"
  2842. " Actual: true (2 is even)\n"
  2843. "Expected: false");
  2844. #endif
  2845. ASSERT_FALSE(ResultIsEvenNoExplanation(3));
  2846. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
  2847. "Value of: ResultIsEvenNoExplanation(2)\n"
  2848. " Actual: true\n"
  2849. "Expected: false");
  2850. }
  2851. #ifdef __BORLANDC__
  2852. // Restores warnings after previous "#pragma option push" supressed them
  2853. # pragma option pop
  2854. #endif
  2855. // Tests using ASSERT_EQ on double values. The purpose is to make
  2856. // sure that the specialization we did for integer and anonymous enums
  2857. // isn't used for double arguments.
  2858. TEST(ExpectTest, ASSERT_EQ_Double) {
  2859. // A success.
  2860. ASSERT_EQ(5.6, 5.6);
  2861. // A failure.
  2862. EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
  2863. "5.1");
  2864. }
  2865. // Tests ASSERT_EQ.
  2866. TEST(AssertionTest, ASSERT_EQ) {
  2867. ASSERT_EQ(5, 2 + 3);
  2868. EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
  2869. "Value of: 2*3\n"
  2870. " Actual: 6\n"
  2871. "Expected: 5");
  2872. }
  2873. // Tests ASSERT_EQ(NULL, pointer).
  2874. #if GTEST_CAN_COMPARE_NULL
  2875. TEST(AssertionTest, ASSERT_EQ_NULL) {
  2876. // A success.
  2877. const char* p = NULL;
  2878. // Some older GCC versions may issue a spurious waring in this or the next
  2879. // assertion statement. This warning should not be suppressed with
  2880. // static_cast since the test verifies the ability to use bare NULL as the
  2881. // expected parameter to the macro.
  2882. ASSERT_EQ(NULL, p);
  2883. // A failure.
  2884. static int n = 0;
  2885. EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
  2886. "Value of: &n\n");
  2887. }
  2888. #endif // GTEST_CAN_COMPARE_NULL
  2889. // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
  2890. // treated as a null pointer by the compiler, we need to make sure
  2891. // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
  2892. // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
  2893. TEST(ExpectTest, ASSERT_EQ_0) {
  2894. int n = 0;
  2895. // A success.
  2896. ASSERT_EQ(0, n);
  2897. // A failure.
  2898. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
  2899. "Expected: 0");
  2900. }
  2901. // Tests ASSERT_NE.
  2902. TEST(AssertionTest, ASSERT_NE) {
  2903. ASSERT_NE(6, 7);
  2904. EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
  2905. "Expected: ('a') != ('a'), "
  2906. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  2907. }
  2908. // Tests ASSERT_LE.
  2909. TEST(AssertionTest, ASSERT_LE) {
  2910. ASSERT_LE(2, 3);
  2911. ASSERT_LE(2, 2);
  2912. EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
  2913. "Expected: (2) <= (0), actual: 2 vs 0");
  2914. }
  2915. // Tests ASSERT_LT.
  2916. TEST(AssertionTest, ASSERT_LT) {
  2917. ASSERT_LT(2, 3);
  2918. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
  2919. "Expected: (2) < (2), actual: 2 vs 2");
  2920. }
  2921. // Tests ASSERT_GE.
  2922. TEST(AssertionTest, ASSERT_GE) {
  2923. ASSERT_GE(2, 1);
  2924. ASSERT_GE(2, 2);
  2925. EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
  2926. "Expected: (2) >= (3), actual: 2 vs 3");
  2927. }
  2928. // Tests ASSERT_GT.
  2929. TEST(AssertionTest, ASSERT_GT) {
  2930. ASSERT_GT(2, 1);
  2931. EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
  2932. "Expected: (2) > (2), actual: 2 vs 2");
  2933. }
  2934. #if GTEST_HAS_EXCEPTIONS
  2935. void ThrowNothing() {}
  2936. // Tests ASSERT_THROW.
  2937. TEST(AssertionTest, ASSERT_THROW) {
  2938. ASSERT_THROW(ThrowAnInteger(), int);
  2939. # ifndef __BORLANDC__
  2940. // ICE's in C++Builder 2007 and 2009.
  2941. EXPECT_FATAL_FAILURE(
  2942. ASSERT_THROW(ThrowAnInteger(), bool),
  2943. "Expected: ThrowAnInteger() throws an exception of type bool.\n"
  2944. " Actual: it throws a different type.");
  2945. # endif
  2946. EXPECT_FATAL_FAILURE(
  2947. ASSERT_THROW(ThrowNothing(), bool),
  2948. "Expected: ThrowNothing() throws an exception of type bool.\n"
  2949. " Actual: it throws nothing.");
  2950. }
  2951. // Tests ASSERT_NO_THROW.
  2952. TEST(AssertionTest, ASSERT_NO_THROW) {
  2953. ASSERT_NO_THROW(ThrowNothing());
  2954. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
  2955. "Expected: ThrowAnInteger() doesn't throw an exception."
  2956. "\n Actual: it throws.");
  2957. }
  2958. // Tests ASSERT_ANY_THROW.
  2959. TEST(AssertionTest, ASSERT_ANY_THROW) {
  2960. ASSERT_ANY_THROW(ThrowAnInteger());
  2961. EXPECT_FATAL_FAILURE(
  2962. ASSERT_ANY_THROW(ThrowNothing()),
  2963. "Expected: ThrowNothing() throws an exception.\n"
  2964. " Actual: it doesn't.");
  2965. }
  2966. #endif // GTEST_HAS_EXCEPTIONS
  2967. // Makes sure we deal with the precedence of <<. This test should
  2968. // compile.
  2969. TEST(AssertionTest, AssertPrecedence) {
  2970. ASSERT_EQ(1 < 2, true);
  2971. bool false_value = false;
  2972. ASSERT_EQ(true && false_value, false);
  2973. }
  2974. // A subroutine used by the following test.
  2975. void TestEq1(int x) {
  2976. ASSERT_EQ(1, x);
  2977. }
  2978. // Tests calling a test subroutine that's not part of a fixture.
  2979. TEST(AssertionTest, NonFixtureSubroutine) {
  2980. EXPECT_FATAL_FAILURE(TestEq1(2),
  2981. "Value of: x");
  2982. }
  2983. // An uncopyable class.
  2984. class Uncopyable {
  2985. public:
  2986. explicit Uncopyable(int a_value) : value_(a_value) {}
  2987. int value() const { return value_; }
  2988. bool operator==(const Uncopyable& rhs) const {
  2989. return value() == rhs.value();
  2990. }
  2991. private:
  2992. // This constructor deliberately has no implementation, as we don't
  2993. // want this class to be copyable.
  2994. Uncopyable(const Uncopyable&); // NOLINT
  2995. int value_;
  2996. };
  2997. ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
  2998. return os << value.value();
  2999. }
  3000. bool IsPositiveUncopyable(const Uncopyable& x) {
  3001. return x.value() > 0;
  3002. }
  3003. // A subroutine used by the following test.
  3004. void TestAssertNonPositive() {
  3005. Uncopyable y(-1);
  3006. ASSERT_PRED1(IsPositiveUncopyable, y);
  3007. }
  3008. // A subroutine used by the following test.
  3009. void TestAssertEqualsUncopyable() {
  3010. Uncopyable x(5);
  3011. Uncopyable y(-1);
  3012. ASSERT_EQ(x, y);
  3013. }
  3014. // Tests that uncopyable objects can be used in assertions.
  3015. TEST(AssertionTest, AssertWorksWithUncopyableObject) {
  3016. Uncopyable x(5);
  3017. ASSERT_PRED1(IsPositiveUncopyable, x);
  3018. ASSERT_EQ(x, x);
  3019. EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
  3020. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3021. EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
  3022. "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
  3023. }
  3024. // Tests that uncopyable objects can be used in expects.
  3025. TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
  3026. Uncopyable x(5);
  3027. EXPECT_PRED1(IsPositiveUncopyable, x);
  3028. Uncopyable y(-1);
  3029. EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
  3030. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3031. EXPECT_EQ(x, x);
  3032. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
  3033. "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
  3034. }
  3035. enum NamedEnum {
  3036. kE1 = 0,
  3037. kE2 = 1
  3038. };
  3039. TEST(AssertionTest, NamedEnum) {
  3040. EXPECT_EQ(kE1, kE1);
  3041. EXPECT_LT(kE1, kE2);
  3042. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
  3043. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
  3044. }
  3045. // The version of gcc used in XCode 2.2 has a bug and doesn't allow
  3046. // anonymous enums in assertions. Therefore the following test is not
  3047. // done on Mac.
  3048. // Sun Studio and HP aCC also reject this code.
  3049. #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
  3050. // Tests using assertions with anonymous enums.
  3051. enum {
  3052. kCaseA = -1,
  3053. # if GTEST_OS_LINUX
  3054. // We want to test the case where the size of the anonymous enum is
  3055. // larger than sizeof(int), to make sure our implementation of the
  3056. // assertions doesn't truncate the enums. However, MSVC
  3057. // (incorrectly) doesn't allow an enum value to exceed the range of
  3058. // an int, so this has to be conditionally compiled.
  3059. //
  3060. // On Linux, kCaseB and kCaseA have the same value when truncated to
  3061. // int size. We want to test whether this will confuse the
  3062. // assertions.
  3063. kCaseB = testing::internal::kMaxBiggestInt,
  3064. # else
  3065. kCaseB = INT_MAX,
  3066. # endif // GTEST_OS_LINUX
  3067. kCaseC = 42
  3068. };
  3069. TEST(AssertionTest, AnonymousEnum) {
  3070. # if GTEST_OS_LINUX
  3071. EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
  3072. # endif // GTEST_OS_LINUX
  3073. EXPECT_EQ(kCaseA, kCaseA);
  3074. EXPECT_NE(kCaseA, kCaseB);
  3075. EXPECT_LT(kCaseA, kCaseB);
  3076. EXPECT_LE(kCaseA, kCaseB);
  3077. EXPECT_GT(kCaseB, kCaseA);
  3078. EXPECT_GE(kCaseA, kCaseA);
  3079. EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
  3080. "(kCaseA) >= (kCaseB)");
  3081. EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
  3082. "-1 vs 42");
  3083. ASSERT_EQ(kCaseA, kCaseA);
  3084. ASSERT_NE(kCaseA, kCaseB);
  3085. ASSERT_LT(kCaseA, kCaseB);
  3086. ASSERT_LE(kCaseA, kCaseB);
  3087. ASSERT_GT(kCaseB, kCaseA);
  3088. ASSERT_GE(kCaseA, kCaseA);
  3089. # ifndef __BORLANDC__
  3090. // ICE's in C++Builder.
  3091. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
  3092. "Value of: kCaseB");
  3093. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
  3094. "Actual: 42");
  3095. # endif
  3096. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
  3097. "Which is: -1");
  3098. }
  3099. #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
  3100. #if GTEST_OS_WINDOWS
  3101. static HRESULT UnexpectedHRESULTFailure() {
  3102. return E_UNEXPECTED;
  3103. }
  3104. static HRESULT OkHRESULTSuccess() {
  3105. return S_OK;
  3106. }
  3107. static HRESULT FalseHRESULTSuccess() {
  3108. return S_FALSE;
  3109. }
  3110. // HRESULT assertion tests test both zero and non-zero
  3111. // success codes as well as failure message for each.
  3112. //
  3113. // Windows CE doesn't support message texts.
  3114. TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
  3115. EXPECT_HRESULT_SUCCEEDED(S_OK);
  3116. EXPECT_HRESULT_SUCCEEDED(S_FALSE);
  3117. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3118. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3119. " Actual: 0x8000FFFF");
  3120. }
  3121. TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
  3122. ASSERT_HRESULT_SUCCEEDED(S_OK);
  3123. ASSERT_HRESULT_SUCCEEDED(S_FALSE);
  3124. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3125. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3126. " Actual: 0x8000FFFF");
  3127. }
  3128. TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
  3129. EXPECT_HRESULT_FAILED(E_UNEXPECTED);
  3130. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
  3131. "Expected: (OkHRESULTSuccess()) fails.\n"
  3132. " Actual: 0x00000000");
  3133. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3134. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3135. " Actual: 0x00000001");
  3136. }
  3137. TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
  3138. ASSERT_HRESULT_FAILED(E_UNEXPECTED);
  3139. # ifndef __BORLANDC__
  3140. // ICE's in C++Builder 2007 and 2009.
  3141. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
  3142. "Expected: (OkHRESULTSuccess()) fails.\n"
  3143. " Actual: 0x00000000");
  3144. # endif
  3145. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3146. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3147. " Actual: 0x00000001");
  3148. }
  3149. // Tests that streaming to the HRESULT macros works.
  3150. TEST(HRESULTAssertionTest, Streaming) {
  3151. EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3152. ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3153. EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3154. ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3155. EXPECT_NONFATAL_FAILURE(
  3156. EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
  3157. "expected failure");
  3158. # ifndef __BORLANDC__
  3159. // ICE's in C++Builder 2007 and 2009.
  3160. EXPECT_FATAL_FAILURE(
  3161. ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
  3162. "expected failure");
  3163. # endif
  3164. EXPECT_NONFATAL_FAILURE(
  3165. EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
  3166. "expected failure");
  3167. EXPECT_FATAL_FAILURE(
  3168. ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
  3169. "expected failure");
  3170. }
  3171. #endif // GTEST_OS_WINDOWS
  3172. #ifdef __BORLANDC__
  3173. // Silences warnings: "Condition is always true", "Unreachable code"
  3174. # pragma option push -w-ccc -w-rch
  3175. #endif
  3176. // Tests that the assertion macros behave like single statements.
  3177. TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
  3178. if (AlwaysFalse())
  3179. ASSERT_TRUE(false) << "This should never be executed; "
  3180. "It's a compilation test only.";
  3181. if (AlwaysTrue())
  3182. EXPECT_FALSE(false);
  3183. else
  3184. ; // NOLINT
  3185. if (AlwaysFalse())
  3186. ASSERT_LT(1, 3);
  3187. if (AlwaysFalse())
  3188. ; // NOLINT
  3189. else
  3190. EXPECT_GT(3, 2) << "";
  3191. }
  3192. #if GTEST_HAS_EXCEPTIONS
  3193. // Tests that the compiler will not complain about unreachable code in the
  3194. // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
  3195. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
  3196. int n = 0;
  3197. EXPECT_THROW(throw 1, int);
  3198. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
  3199. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
  3200. EXPECT_NO_THROW(n++);
  3201. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
  3202. EXPECT_ANY_THROW(throw 1);
  3203. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
  3204. }
  3205. TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
  3206. if (AlwaysFalse())
  3207. EXPECT_THROW(ThrowNothing(), bool);
  3208. if (AlwaysTrue())
  3209. EXPECT_THROW(ThrowAnInteger(), int);
  3210. else
  3211. ; // NOLINT
  3212. if (AlwaysFalse())
  3213. EXPECT_NO_THROW(ThrowAnInteger());
  3214. if (AlwaysTrue())
  3215. EXPECT_NO_THROW(ThrowNothing());
  3216. else
  3217. ; // NOLINT
  3218. if (AlwaysFalse())
  3219. EXPECT_ANY_THROW(ThrowNothing());
  3220. if (AlwaysTrue())
  3221. EXPECT_ANY_THROW(ThrowAnInteger());
  3222. else
  3223. ; // NOLINT
  3224. }
  3225. #endif // GTEST_HAS_EXCEPTIONS
  3226. TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
  3227. if (AlwaysFalse())
  3228. EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
  3229. << "It's a compilation test only.";
  3230. else
  3231. ; // NOLINT
  3232. if (AlwaysFalse())
  3233. ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
  3234. else
  3235. ; // NOLINT
  3236. if (AlwaysTrue())
  3237. EXPECT_NO_FATAL_FAILURE(SUCCEED());
  3238. else
  3239. ; // NOLINT
  3240. if (AlwaysFalse())
  3241. ; // NOLINT
  3242. else
  3243. ASSERT_NO_FATAL_FAILURE(SUCCEED());
  3244. }
  3245. // Tests that the assertion macros work well with switch statements.
  3246. TEST(AssertionSyntaxTest, WorksWithSwitch) {
  3247. switch (0) {
  3248. case 1:
  3249. break;
  3250. default:
  3251. ASSERT_TRUE(true);
  3252. }
  3253. switch (0)
  3254. case 0:
  3255. EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
  3256. // Binary assertions are implemented using a different code path
  3257. // than the Boolean assertions. Hence we test them separately.
  3258. switch (0) {
  3259. case 1:
  3260. default:
  3261. ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
  3262. }
  3263. switch (0)
  3264. case 0:
  3265. EXPECT_NE(1, 2);
  3266. }
  3267. #if GTEST_HAS_EXCEPTIONS
  3268. void ThrowAString() {
  3269. throw "std::string";
  3270. }
  3271. // Test that the exception assertion macros compile and work with const
  3272. // type qualifier.
  3273. TEST(AssertionSyntaxTest, WorksWithConst) {
  3274. ASSERT_THROW(ThrowAString(), const char*);
  3275. EXPECT_THROW(ThrowAString(), const char*);
  3276. }
  3277. #endif // GTEST_HAS_EXCEPTIONS
  3278. } // namespace
  3279. namespace testing {
  3280. // Tests that Google Test tracks SUCCEED*.
  3281. TEST(SuccessfulAssertionTest, SUCCEED) {
  3282. SUCCEED();
  3283. SUCCEED() << "OK";
  3284. EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
  3285. }
  3286. // Tests that Google Test doesn't track successful EXPECT_*.
  3287. TEST(SuccessfulAssertionTest, EXPECT) {
  3288. EXPECT_TRUE(true);
  3289. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3290. }
  3291. // Tests that Google Test doesn't track successful EXPECT_STR*.
  3292. TEST(SuccessfulAssertionTest, EXPECT_STR) {
  3293. EXPECT_STREQ("", "");
  3294. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3295. }
  3296. // Tests that Google Test doesn't track successful ASSERT_*.
  3297. TEST(SuccessfulAssertionTest, ASSERT) {
  3298. ASSERT_TRUE(true);
  3299. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3300. }
  3301. // Tests that Google Test doesn't track successful ASSERT_STR*.
  3302. TEST(SuccessfulAssertionTest, ASSERT_STR) {
  3303. ASSERT_STREQ("", "");
  3304. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3305. }
  3306. } // namespace testing
  3307. namespace {
  3308. // Tests the message streaming variation of assertions.
  3309. TEST(AssertionWithMessageTest, EXPECT) {
  3310. EXPECT_EQ(1, 1) << "This should succeed.";
  3311. EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
  3312. "Expected failure #1");
  3313. EXPECT_LE(1, 2) << "This should succeed.";
  3314. EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
  3315. "Expected failure #2.");
  3316. EXPECT_GE(1, 0) << "This should succeed.";
  3317. EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
  3318. "Expected failure #3.");
  3319. EXPECT_STREQ("1", "1") << "This should succeed.";
  3320. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
  3321. "Expected failure #4.");
  3322. EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
  3323. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
  3324. "Expected failure #5.");
  3325. EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
  3326. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
  3327. "Expected failure #6.");
  3328. EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
  3329. }
  3330. TEST(AssertionWithMessageTest, ASSERT) {
  3331. ASSERT_EQ(1, 1) << "This should succeed.";
  3332. ASSERT_NE(1, 2) << "This should succeed.";
  3333. ASSERT_LE(1, 2) << "This should succeed.";
  3334. ASSERT_LT(1, 2) << "This should succeed.";
  3335. ASSERT_GE(1, 0) << "This should succeed.";
  3336. EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
  3337. "Expected failure.");
  3338. }
  3339. TEST(AssertionWithMessageTest, ASSERT_STR) {
  3340. ASSERT_STREQ("1", "1") << "This should succeed.";
  3341. ASSERT_STRNE("1", "2") << "This should succeed.";
  3342. ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
  3343. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
  3344. "Expected failure.");
  3345. }
  3346. TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
  3347. ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
  3348. ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
  3349. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
  3350. "Expect failure.");
  3351. // To work around a bug in gcc 2.95.0, there is intentionally no
  3352. // space after the first comma in the previous statement.
  3353. }
  3354. // Tests using ASSERT_FALSE with a streamed message.
  3355. TEST(AssertionWithMessageTest, ASSERT_FALSE) {
  3356. ASSERT_FALSE(false) << "This shouldn't fail.";
  3357. EXPECT_FATAL_FAILURE({ // NOLINT
  3358. ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
  3359. << " evaluates to " << true;
  3360. }, "Expected failure");
  3361. }
  3362. // Tests using FAIL with a streamed message.
  3363. TEST(AssertionWithMessageTest, FAIL) {
  3364. EXPECT_FATAL_FAILURE(FAIL() << 0,
  3365. "0");
  3366. }
  3367. // Tests using SUCCEED with a streamed message.
  3368. TEST(AssertionWithMessageTest, SUCCEED) {
  3369. SUCCEED() << "Success == " << 1;
  3370. }
  3371. // Tests using ASSERT_TRUE with a streamed message.
  3372. TEST(AssertionWithMessageTest, ASSERT_TRUE) {
  3373. ASSERT_TRUE(true) << "This should succeed.";
  3374. ASSERT_TRUE(true) << true;
  3375. EXPECT_FATAL_FAILURE({ // NOLINT
  3376. ASSERT_TRUE(false) << static_cast<const char *>(NULL)
  3377. << static_cast<char *>(NULL);
  3378. }, "(null)(null)");
  3379. }
  3380. #if GTEST_OS_WINDOWS
  3381. // Tests using wide strings in assertion messages.
  3382. TEST(AssertionWithMessageTest, WideStringMessage) {
  3383. EXPECT_NONFATAL_FAILURE({ // NOLINT
  3384. EXPECT_TRUE(false) << L"This failure is expected.\x8119";
  3385. }, "This failure is expected.");
  3386. EXPECT_FATAL_FAILURE({ // NOLINT
  3387. ASSERT_EQ(1, 2) << "This failure is "
  3388. << L"expected too.\x8120";
  3389. }, "This failure is expected too.");
  3390. }
  3391. #endif // GTEST_OS_WINDOWS
  3392. // Tests EXPECT_TRUE.
  3393. TEST(ExpectTest, EXPECT_TRUE) {
  3394. EXPECT_TRUE(true) << "Intentional success";
  3395. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
  3396. "Intentional failure #1.");
  3397. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
  3398. "Intentional failure #2.");
  3399. EXPECT_TRUE(2 > 1); // NOLINT
  3400. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
  3401. "Value of: 2 < 1\n"
  3402. " Actual: false\n"
  3403. "Expected: true");
  3404. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
  3405. "2 > 3");
  3406. }
  3407. // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
  3408. TEST(ExpectTest, ExpectTrueWithAssertionResult) {
  3409. EXPECT_TRUE(ResultIsEven(2));
  3410. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
  3411. "Value of: ResultIsEven(3)\n"
  3412. " Actual: false (3 is odd)\n"
  3413. "Expected: true");
  3414. EXPECT_TRUE(ResultIsEvenNoExplanation(2));
  3415. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
  3416. "Value of: ResultIsEvenNoExplanation(3)\n"
  3417. " Actual: false (3 is odd)\n"
  3418. "Expected: true");
  3419. }
  3420. // Tests EXPECT_FALSE with a streamed message.
  3421. TEST(ExpectTest, EXPECT_FALSE) {
  3422. EXPECT_FALSE(2 < 1); // NOLINT
  3423. EXPECT_FALSE(false) << "Intentional success";
  3424. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
  3425. "Intentional failure #1.");
  3426. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
  3427. "Intentional failure #2.");
  3428. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
  3429. "Value of: 2 > 1\n"
  3430. " Actual: true\n"
  3431. "Expected: false");
  3432. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
  3433. "2 < 3");
  3434. }
  3435. // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
  3436. TEST(ExpectTest, ExpectFalseWithAssertionResult) {
  3437. EXPECT_FALSE(ResultIsEven(3));
  3438. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
  3439. "Value of: ResultIsEven(2)\n"
  3440. " Actual: true (2 is even)\n"
  3441. "Expected: false");
  3442. EXPECT_FALSE(ResultIsEvenNoExplanation(3));
  3443. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
  3444. "Value of: ResultIsEvenNoExplanation(2)\n"
  3445. " Actual: true\n"
  3446. "Expected: false");
  3447. }
  3448. #ifdef __BORLANDC__
  3449. // Restores warnings after previous "#pragma option push" supressed them
  3450. # pragma option pop
  3451. #endif
  3452. // Tests EXPECT_EQ.
  3453. TEST(ExpectTest, EXPECT_EQ) {
  3454. EXPECT_EQ(5, 2 + 3);
  3455. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
  3456. "Value of: 2*3\n"
  3457. " Actual: 6\n"
  3458. "Expected: 5");
  3459. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
  3460. "2 - 3");
  3461. }
  3462. // Tests using EXPECT_EQ on double values. The purpose is to make
  3463. // sure that the specialization we did for integer and anonymous enums
  3464. // isn't used for double arguments.
  3465. TEST(ExpectTest, EXPECT_EQ_Double) {
  3466. // A success.
  3467. EXPECT_EQ(5.6, 5.6);
  3468. // A failure.
  3469. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
  3470. "5.1");
  3471. }
  3472. #if GTEST_CAN_COMPARE_NULL
  3473. // Tests EXPECT_EQ(NULL, pointer).
  3474. TEST(ExpectTest, EXPECT_EQ_NULL) {
  3475. // A success.
  3476. const char* p = NULL;
  3477. // Some older GCC versions may issue a spurious warning in this or the next
  3478. // assertion statement. This warning should not be suppressed with
  3479. // static_cast since the test verifies the ability to use bare NULL as the
  3480. // expected parameter to the macro.
  3481. EXPECT_EQ(NULL, p);
  3482. // A failure.
  3483. int n = 0;
  3484. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
  3485. "Value of: &n\n");
  3486. }
  3487. #endif // GTEST_CAN_COMPARE_NULL
  3488. // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
  3489. // treated as a null pointer by the compiler, we need to make sure
  3490. // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
  3491. // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
  3492. TEST(ExpectTest, EXPECT_EQ_0) {
  3493. int n = 0;
  3494. // A success.
  3495. EXPECT_EQ(0, n);
  3496. // A failure.
  3497. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
  3498. "Expected: 0");
  3499. }
  3500. // Tests EXPECT_NE.
  3501. TEST(ExpectTest, EXPECT_NE) {
  3502. EXPECT_NE(6, 7);
  3503. EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
  3504. "Expected: ('a') != ('a'), "
  3505. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  3506. EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
  3507. "2");
  3508. char* const p0 = NULL;
  3509. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
  3510. "p0");
  3511. // Only way to get the Nokia compiler to compile the cast
  3512. // is to have a separate void* variable first. Putting
  3513. // the two casts on the same line doesn't work, neither does
  3514. // a direct C-style to char*.
  3515. void* pv1 = (void*)0x1234; // NOLINT
  3516. char* const p1 = reinterpret_cast<char*>(pv1);
  3517. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
  3518. "p1");
  3519. }
  3520. // Tests EXPECT_LE.
  3521. TEST(ExpectTest, EXPECT_LE) {
  3522. EXPECT_LE(2, 3);
  3523. EXPECT_LE(2, 2);
  3524. EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
  3525. "Expected: (2) <= (0), actual: 2 vs 0");
  3526. EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
  3527. "(1.1) <= (0.9)");
  3528. }
  3529. // Tests EXPECT_LT.
  3530. TEST(ExpectTest, EXPECT_LT) {
  3531. EXPECT_LT(2, 3);
  3532. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
  3533. "Expected: (2) < (2), actual: 2 vs 2");
  3534. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
  3535. "(2) < (1)");
  3536. }
  3537. // Tests EXPECT_GE.
  3538. TEST(ExpectTest, EXPECT_GE) {
  3539. EXPECT_GE(2, 1);
  3540. EXPECT_GE(2, 2);
  3541. EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
  3542. "Expected: (2) >= (3), actual: 2 vs 3");
  3543. EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
  3544. "(0.9) >= (1.1)");
  3545. }
  3546. // Tests EXPECT_GT.
  3547. TEST(ExpectTest, EXPECT_GT) {
  3548. EXPECT_GT(2, 1);
  3549. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
  3550. "Expected: (2) > (2), actual: 2 vs 2");
  3551. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
  3552. "(2) > (3)");
  3553. }
  3554. #if GTEST_HAS_EXCEPTIONS
  3555. // Tests EXPECT_THROW.
  3556. TEST(ExpectTest, EXPECT_THROW) {
  3557. EXPECT_THROW(ThrowAnInteger(), int);
  3558. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
  3559. "Expected: ThrowAnInteger() throws an exception of "
  3560. "type bool.\n Actual: it throws a different type.");
  3561. EXPECT_NONFATAL_FAILURE(
  3562. EXPECT_THROW(ThrowNothing(), bool),
  3563. "Expected: ThrowNothing() throws an exception of type bool.\n"
  3564. " Actual: it throws nothing.");
  3565. }
  3566. // Tests EXPECT_NO_THROW.
  3567. TEST(ExpectTest, EXPECT_NO_THROW) {
  3568. EXPECT_NO_THROW(ThrowNothing());
  3569. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
  3570. "Expected: ThrowAnInteger() doesn't throw an "
  3571. "exception.\n Actual: it throws.");
  3572. }
  3573. // Tests EXPECT_ANY_THROW.
  3574. TEST(ExpectTest, EXPECT_ANY_THROW) {
  3575. EXPECT_ANY_THROW(ThrowAnInteger());
  3576. EXPECT_NONFATAL_FAILURE(
  3577. EXPECT_ANY_THROW(ThrowNothing()),
  3578. "Expected: ThrowNothing() throws an exception.\n"
  3579. " Actual: it doesn't.");
  3580. }
  3581. #endif // GTEST_HAS_EXCEPTIONS
  3582. // Make sure we deal with the precedence of <<.
  3583. TEST(ExpectTest, ExpectPrecedence) {
  3584. EXPECT_EQ(1 < 2, true);
  3585. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
  3586. "Value of: true && false");
  3587. }
  3588. // Tests the StreamableToString() function.
  3589. // Tests using StreamableToString() on a scalar.
  3590. TEST(StreamableToStringTest, Scalar) {
  3591. EXPECT_STREQ("5", StreamableToString(5).c_str());
  3592. }
  3593. // Tests using StreamableToString() on a non-char pointer.
  3594. TEST(StreamableToStringTest, Pointer) {
  3595. int n = 0;
  3596. int* p = &n;
  3597. EXPECT_STRNE("(null)", StreamableToString(p).c_str());
  3598. }
  3599. // Tests using StreamableToString() on a NULL non-char pointer.
  3600. TEST(StreamableToStringTest, NullPointer) {
  3601. int* p = NULL;
  3602. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3603. }
  3604. // Tests using StreamableToString() on a C string.
  3605. TEST(StreamableToStringTest, CString) {
  3606. EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
  3607. }
  3608. // Tests using StreamableToString() on a NULL C string.
  3609. TEST(StreamableToStringTest, NullCString) {
  3610. char* p = NULL;
  3611. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3612. }
  3613. // Tests using streamable values as assertion messages.
  3614. // Tests using std::string as an assertion message.
  3615. TEST(StreamableTest, string) {
  3616. static const std::string str(
  3617. "This failure message is a std::string, and is expected.");
  3618. EXPECT_FATAL_FAILURE(FAIL() << str,
  3619. str.c_str());
  3620. }
  3621. // Tests that we can output strings containing embedded NULs.
  3622. // Limited to Linux because we can only do this with std::string's.
  3623. TEST(StreamableTest, stringWithEmbeddedNUL) {
  3624. static const char char_array_with_nul[] =
  3625. "Here's a NUL\0 and some more string";
  3626. static const std::string string_with_nul(char_array_with_nul,
  3627. sizeof(char_array_with_nul)
  3628. - 1); // drops the trailing NUL
  3629. EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
  3630. "Here's a NUL\\0 and some more string");
  3631. }
  3632. // Tests that we can output a NUL char.
  3633. TEST(StreamableTest, NULChar) {
  3634. EXPECT_FATAL_FAILURE({ // NOLINT
  3635. FAIL() << "A NUL" << '\0' << " and some more string";
  3636. }, "A NUL\\0 and some more string");
  3637. }
  3638. // Tests using int as an assertion message.
  3639. TEST(StreamableTest, int) {
  3640. EXPECT_FATAL_FAILURE(FAIL() << 900913,
  3641. "900913");
  3642. }
  3643. // Tests using NULL char pointer as an assertion message.
  3644. //
  3645. // In MSVC, streaming a NULL char * causes access violation. Google Test
  3646. // implemented a workaround (substituting "(null)" for NULL). This
  3647. // tests whether the workaround works.
  3648. TEST(StreamableTest, NullCharPtr) {
  3649. EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
  3650. "(null)");
  3651. }
  3652. // Tests that basic IO manipulators (endl, ends, and flush) can be
  3653. // streamed to testing::Message.
  3654. TEST(StreamableTest, BasicIoManip) {
  3655. EXPECT_FATAL_FAILURE({ // NOLINT
  3656. FAIL() << "Line 1." << std::endl
  3657. << "A NUL char " << std::ends << std::flush << " in line 2.";
  3658. }, "Line 1.\nA NUL char \\0 in line 2.");
  3659. }
  3660. // Tests the macros that haven't been covered so far.
  3661. void AddFailureHelper(bool* aborted) {
  3662. *aborted = true;
  3663. ADD_FAILURE() << "Intentional failure.";
  3664. *aborted = false;
  3665. }
  3666. // Tests ADD_FAILURE.
  3667. TEST(MacroTest, ADD_FAILURE) {
  3668. bool aborted = true;
  3669. EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
  3670. "Intentional failure.");
  3671. EXPECT_FALSE(aborted);
  3672. }
  3673. // Tests ADD_FAILURE_AT.
  3674. TEST(MacroTest, ADD_FAILURE_AT) {
  3675. // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
  3676. // the failure message contains the user-streamed part.
  3677. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
  3678. // Verifies that the user-streamed part is optional.
  3679. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
  3680. // Unfortunately, we cannot verify that the failure message contains
  3681. // the right file path and line number the same way, as
  3682. // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
  3683. // line number. Instead, we do that in gtest_output_test_.cc.
  3684. }
  3685. // Tests FAIL.
  3686. TEST(MacroTest, FAIL) {
  3687. EXPECT_FATAL_FAILURE(FAIL(),
  3688. "Failed");
  3689. EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
  3690. "Intentional failure.");
  3691. }
  3692. // Tests SUCCEED
  3693. TEST(MacroTest, SUCCEED) {
  3694. SUCCEED();
  3695. SUCCEED() << "Explicit success.";
  3696. }
  3697. // Tests for EXPECT_EQ() and ASSERT_EQ().
  3698. //
  3699. // These tests fail *intentionally*, s.t. the failure messages can be
  3700. // generated and tested.
  3701. //
  3702. // We have different tests for different argument types.
  3703. // Tests using bool values in {EXPECT|ASSERT}_EQ.
  3704. TEST(EqAssertionTest, Bool) {
  3705. EXPECT_EQ(true, true);
  3706. EXPECT_FATAL_FAILURE({
  3707. bool false_value = false;
  3708. ASSERT_EQ(false_value, true);
  3709. }, "Value of: true");
  3710. }
  3711. // Tests using int values in {EXPECT|ASSERT}_EQ.
  3712. TEST(EqAssertionTest, Int) {
  3713. ASSERT_EQ(32, 32);
  3714. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
  3715. "33");
  3716. }
  3717. // Tests using time_t values in {EXPECT|ASSERT}_EQ.
  3718. TEST(EqAssertionTest, Time_T) {
  3719. EXPECT_EQ(static_cast<time_t>(0),
  3720. static_cast<time_t>(0));
  3721. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
  3722. static_cast<time_t>(1234)),
  3723. "1234");
  3724. }
  3725. // Tests using char values in {EXPECT|ASSERT}_EQ.
  3726. TEST(EqAssertionTest, Char) {
  3727. ASSERT_EQ('z', 'z');
  3728. const char ch = 'b';
  3729. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
  3730. "ch");
  3731. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
  3732. "ch");
  3733. }
  3734. // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
  3735. TEST(EqAssertionTest, WideChar) {
  3736. EXPECT_EQ(L'b', L'b');
  3737. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
  3738. "Value of: L'x'\n"
  3739. " Actual: L'x' (120, 0x78)\n"
  3740. "Expected: L'\0'\n"
  3741. "Which is: L'\0' (0, 0x0)");
  3742. static wchar_t wchar;
  3743. wchar = L'b';
  3744. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
  3745. "wchar");
  3746. wchar = 0x8119;
  3747. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
  3748. "Value of: wchar");
  3749. }
  3750. // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
  3751. TEST(EqAssertionTest, StdString) {
  3752. // Compares a const char* to an std::string that has identical
  3753. // content.
  3754. ASSERT_EQ("Test", ::std::string("Test"));
  3755. // Compares two identical std::strings.
  3756. static const ::std::string str1("A * in the middle");
  3757. static const ::std::string str2(str1);
  3758. EXPECT_EQ(str1, str2);
  3759. // Compares a const char* to an std::string that has different
  3760. // content
  3761. EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
  3762. "::std::string(\"test\")");
  3763. // Compares an std::string to a char* that has different content.
  3764. char* const p1 = const_cast<char*>("foo");
  3765. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
  3766. "p1");
  3767. // Compares two std::strings that have different contents, one of
  3768. // which having a NUL character in the middle. This should fail.
  3769. static ::std::string str3(str1);
  3770. str3.at(2) = '\0';
  3771. EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
  3772. "Value of: str3\n"
  3773. " Actual: \"A \\0 in the middle\"");
  3774. }
  3775. #if GTEST_HAS_STD_WSTRING
  3776. // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
  3777. TEST(EqAssertionTest, StdWideString) {
  3778. // Compares two identical std::wstrings.
  3779. const ::std::wstring wstr1(L"A * in the middle");
  3780. const ::std::wstring wstr2(wstr1);
  3781. ASSERT_EQ(wstr1, wstr2);
  3782. // Compares an std::wstring to a const wchar_t* that has identical
  3783. // content.
  3784. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
  3785. EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
  3786. // Compares an std::wstring to a const wchar_t* that has different
  3787. // content.
  3788. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
  3789. EXPECT_NONFATAL_FAILURE({ // NOLINT
  3790. EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
  3791. }, "kTestX8120");
  3792. // Compares two std::wstrings that have different contents, one of
  3793. // which having a NUL character in the middle.
  3794. ::std::wstring wstr3(wstr1);
  3795. wstr3.at(2) = L'\0';
  3796. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
  3797. "wstr3");
  3798. // Compares a wchar_t* to an std::wstring that has different
  3799. // content.
  3800. EXPECT_FATAL_FAILURE({ // NOLINT
  3801. ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
  3802. }, "");
  3803. }
  3804. #endif // GTEST_HAS_STD_WSTRING
  3805. #if GTEST_HAS_GLOBAL_STRING
  3806. // Tests using ::string values in {EXPECT|ASSERT}_EQ.
  3807. TEST(EqAssertionTest, GlobalString) {
  3808. // Compares a const char* to a ::string that has identical content.
  3809. EXPECT_EQ("Test", ::string("Test"));
  3810. // Compares two identical ::strings.
  3811. const ::string str1("A * in the middle");
  3812. const ::string str2(str1);
  3813. ASSERT_EQ(str1, str2);
  3814. // Compares a ::string to a const char* that has different content.
  3815. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
  3816. "test");
  3817. // Compares two ::strings that have different contents, one of which
  3818. // having a NUL character in the middle.
  3819. ::string str3(str1);
  3820. str3.at(2) = '\0';
  3821. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
  3822. "str3");
  3823. // Compares a ::string to a char* that has different content.
  3824. EXPECT_FATAL_FAILURE({ // NOLINT
  3825. ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
  3826. }, "");
  3827. }
  3828. #endif // GTEST_HAS_GLOBAL_STRING
  3829. #if GTEST_HAS_GLOBAL_WSTRING
  3830. // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
  3831. TEST(EqAssertionTest, GlobalWideString) {
  3832. // Compares two identical ::wstrings.
  3833. static const ::wstring wstr1(L"A * in the middle");
  3834. static const ::wstring wstr2(wstr1);
  3835. EXPECT_EQ(wstr1, wstr2);
  3836. // Compares a const wchar_t* to a ::wstring that has identical content.
  3837. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
  3838. ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
  3839. // Compares a const wchar_t* to a ::wstring that has different
  3840. // content.
  3841. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
  3842. EXPECT_NONFATAL_FAILURE({ // NOLINT
  3843. EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
  3844. }, "Test\\x8119");
  3845. // Compares a wchar_t* to a ::wstring that has different content.
  3846. wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
  3847. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
  3848. "bar");
  3849. // Compares two ::wstrings that have different contents, one of which
  3850. // having a NUL character in the middle.
  3851. static ::wstring wstr3;
  3852. wstr3 = wstr1;
  3853. wstr3.at(2) = L'\0';
  3854. EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
  3855. "wstr3");
  3856. }
  3857. #endif // GTEST_HAS_GLOBAL_WSTRING
  3858. // Tests using char pointers in {EXPECT|ASSERT}_EQ.
  3859. TEST(EqAssertionTest, CharPointer) {
  3860. char* const p0 = NULL;
  3861. // Only way to get the Nokia compiler to compile the cast
  3862. // is to have a separate void* variable first. Putting
  3863. // the two casts on the same line doesn't work, neither does
  3864. // a direct C-style to char*.
  3865. void* pv1 = (void*)0x1234; // NOLINT
  3866. void* pv2 = (void*)0xABC0; // NOLINT
  3867. char* const p1 = reinterpret_cast<char*>(pv1);
  3868. char* const p2 = reinterpret_cast<char*>(pv2);
  3869. ASSERT_EQ(p1, p1);
  3870. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
  3871. "Value of: p2");
  3872. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
  3873. "p2");
  3874. EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
  3875. reinterpret_cast<char*>(0xABC0)),
  3876. "ABC0");
  3877. }
  3878. // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
  3879. TEST(EqAssertionTest, WideCharPointer) {
  3880. wchar_t* const p0 = NULL;
  3881. // Only way to get the Nokia compiler to compile the cast
  3882. // is to have a separate void* variable first. Putting
  3883. // the two casts on the same line doesn't work, neither does
  3884. // a direct C-style to char*.
  3885. void* pv1 = (void*)0x1234; // NOLINT
  3886. void* pv2 = (void*)0xABC0; // NOLINT
  3887. wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
  3888. wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
  3889. EXPECT_EQ(p0, p0);
  3890. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
  3891. "Value of: p2");
  3892. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
  3893. "p2");
  3894. void* pv3 = (void*)0x1234; // NOLINT
  3895. void* pv4 = (void*)0xABC0; // NOLINT
  3896. const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
  3897. const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
  3898. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
  3899. "p4");
  3900. }
  3901. // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
  3902. TEST(EqAssertionTest, OtherPointer) {
  3903. ASSERT_EQ(static_cast<const int*>(NULL),
  3904. static_cast<const int*>(NULL));
  3905. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
  3906. reinterpret_cast<const int*>(0x1234)),
  3907. "0x1234");
  3908. }
  3909. // A class that supports binary comparison operators but not streaming.
  3910. class UnprintableChar {
  3911. public:
  3912. explicit UnprintableChar(char ch) : char_(ch) {}
  3913. bool operator==(const UnprintableChar& rhs) const {
  3914. return char_ == rhs.char_;
  3915. }
  3916. bool operator!=(const UnprintableChar& rhs) const {
  3917. return char_ != rhs.char_;
  3918. }
  3919. bool operator<(const UnprintableChar& rhs) const {
  3920. return char_ < rhs.char_;
  3921. }
  3922. bool operator<=(const UnprintableChar& rhs) const {
  3923. return char_ <= rhs.char_;
  3924. }
  3925. bool operator>(const UnprintableChar& rhs) const {
  3926. return char_ > rhs.char_;
  3927. }
  3928. bool operator>=(const UnprintableChar& rhs) const {
  3929. return char_ >= rhs.char_;
  3930. }
  3931. private:
  3932. char char_;
  3933. };
  3934. // Tests that ASSERT_EQ() and friends don't require the arguments to
  3935. // be printable.
  3936. TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
  3937. const UnprintableChar x('x'), y('y');
  3938. ASSERT_EQ(x, x);
  3939. EXPECT_NE(x, y);
  3940. ASSERT_LT(x, y);
  3941. EXPECT_LE(x, y);
  3942. ASSERT_GT(y, x);
  3943. EXPECT_GE(x, x);
  3944. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
  3945. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
  3946. EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
  3947. EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
  3948. EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
  3949. // Code tested by EXPECT_FATAL_FAILURE cannot reference local
  3950. // variables, so we have to write UnprintableChar('x') instead of x.
  3951. #ifndef __BORLANDC__
  3952. // ICE's in C++Builder.
  3953. EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
  3954. "1-byte object <78>");
  3955. EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
  3956. "1-byte object <78>");
  3957. #endif
  3958. EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
  3959. "1-byte object <79>");
  3960. EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
  3961. "1-byte object <78>");
  3962. EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
  3963. "1-byte object <79>");
  3964. }
  3965. // Tests the FRIEND_TEST macro.
  3966. // This class has a private member we want to test. We will test it
  3967. // both in a TEST and in a TEST_F.
  3968. class Foo {
  3969. public:
  3970. Foo() {}
  3971. private:
  3972. int Bar() const { return 1; }
  3973. // Declares the friend tests that can access the private member
  3974. // Bar().
  3975. FRIEND_TEST(FRIEND_TEST_Test, TEST);
  3976. FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
  3977. };
  3978. // Tests that the FRIEND_TEST declaration allows a TEST to access a
  3979. // class's private members. This should compile.
  3980. TEST(FRIEND_TEST_Test, TEST) {
  3981. ASSERT_EQ(1, Foo().Bar());
  3982. }
  3983. // The fixture needed to test using FRIEND_TEST with TEST_F.
  3984. class FRIEND_TEST_Test2 : public Test {
  3985. protected:
  3986. Foo foo;
  3987. };
  3988. // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
  3989. // class's private members. This should compile.
  3990. TEST_F(FRIEND_TEST_Test2, TEST_F) {
  3991. ASSERT_EQ(1, foo.Bar());
  3992. }
  3993. // Tests the life cycle of Test objects.
  3994. // The test fixture for testing the life cycle of Test objects.
  3995. //
  3996. // This class counts the number of live test objects that uses this
  3997. // fixture.
  3998. class TestLifeCycleTest : public Test {
  3999. protected:
  4000. // Constructor. Increments the number of test objects that uses
  4001. // this fixture.
  4002. TestLifeCycleTest() { count_++; }
  4003. // Destructor. Decrements the number of test objects that uses this
  4004. // fixture.
  4005. ~TestLifeCycleTest() { count_--; }
  4006. // Returns the number of live test objects that uses this fixture.
  4007. int count() const { return count_; }
  4008. private:
  4009. static int count_;
  4010. };
  4011. int TestLifeCycleTest::count_ = 0;
  4012. // Tests the life cycle of test objects.
  4013. TEST_F(TestLifeCycleTest, Test1) {
  4014. // There should be only one test object in this test case that's
  4015. // currently alive.
  4016. ASSERT_EQ(1, count());
  4017. }
  4018. // Tests the life cycle of test objects.
  4019. TEST_F(TestLifeCycleTest, Test2) {
  4020. // After Test1 is done and Test2 is started, there should still be
  4021. // only one live test object, as the object for Test1 should've been
  4022. // deleted.
  4023. ASSERT_EQ(1, count());
  4024. }
  4025. } // namespace
  4026. // Tests that the copy constructor works when it is NOT optimized away by
  4027. // the compiler.
  4028. TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
  4029. // Checks that the copy constructor doesn't try to dereference NULL pointers
  4030. // in the source object.
  4031. AssertionResult r1 = AssertionSuccess();
  4032. AssertionResult r2 = r1;
  4033. // The following line is added to prevent the compiler from optimizing
  4034. // away the constructor call.
  4035. r1 << "abc";
  4036. AssertionResult r3 = r1;
  4037. EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
  4038. EXPECT_STREQ("abc", r1.message());
  4039. }
  4040. // Tests that AssertionSuccess and AssertionFailure construct
  4041. // AssertionResult objects as expected.
  4042. TEST(AssertionResultTest, ConstructionWorks) {
  4043. AssertionResult r1 = AssertionSuccess();
  4044. EXPECT_TRUE(r1);
  4045. EXPECT_STREQ("", r1.message());
  4046. AssertionResult r2 = AssertionSuccess() << "abc";
  4047. EXPECT_TRUE(r2);
  4048. EXPECT_STREQ("abc", r2.message());
  4049. AssertionResult r3 = AssertionFailure();
  4050. EXPECT_FALSE(r3);
  4051. EXPECT_STREQ("", r3.message());
  4052. AssertionResult r4 = AssertionFailure() << "def";
  4053. EXPECT_FALSE(r4);
  4054. EXPECT_STREQ("def", r4.message());
  4055. AssertionResult r5 = AssertionFailure(Message() << "ghi");
  4056. EXPECT_FALSE(r5);
  4057. EXPECT_STREQ("ghi", r5.message());
  4058. }
  4059. // Tests that the negation flips the predicate result but keeps the message.
  4060. TEST(AssertionResultTest, NegationWorks) {
  4061. AssertionResult r1 = AssertionSuccess() << "abc";
  4062. EXPECT_FALSE(!r1);
  4063. EXPECT_STREQ("abc", (!r1).message());
  4064. AssertionResult r2 = AssertionFailure() << "def";
  4065. EXPECT_TRUE(!r2);
  4066. EXPECT_STREQ("def", (!r2).message());
  4067. }
  4068. TEST(AssertionResultTest, StreamingWorks) {
  4069. AssertionResult r = AssertionSuccess();
  4070. r << "abc" << 'd' << 0 << true;
  4071. EXPECT_STREQ("abcd0true", r.message());
  4072. }
  4073. TEST(AssertionResultTest, CanStreamOstreamManipulators) {
  4074. AssertionResult r = AssertionSuccess();
  4075. r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
  4076. EXPECT_STREQ("Data\n\\0Will be visible", r.message());
  4077. }
  4078. // Tests streaming a user type whose definition and operator << are
  4079. // both in the global namespace.
  4080. class Base {
  4081. public:
  4082. explicit Base(int an_x) : x_(an_x) {}
  4083. int x() const { return x_; }
  4084. private:
  4085. int x_;
  4086. };
  4087. std::ostream& operator<<(std::ostream& os,
  4088. const Base& val) {
  4089. return os << val.x();
  4090. }
  4091. std::ostream& operator<<(std::ostream& os,
  4092. const Base* pointer) {
  4093. return os << "(" << pointer->x() << ")";
  4094. }
  4095. TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
  4096. Message msg;
  4097. Base a(1);
  4098. msg << a << &a; // Uses ::operator<<.
  4099. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4100. }
  4101. // Tests streaming a user type whose definition and operator<< are
  4102. // both in an unnamed namespace.
  4103. namespace {
  4104. class MyTypeInUnnamedNameSpace : public Base {
  4105. public:
  4106. explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
  4107. };
  4108. std::ostream& operator<<(std::ostream& os,
  4109. const MyTypeInUnnamedNameSpace& val) {
  4110. return os << val.x();
  4111. }
  4112. std::ostream& operator<<(std::ostream& os,
  4113. const MyTypeInUnnamedNameSpace* pointer) {
  4114. return os << "(" << pointer->x() << ")";
  4115. }
  4116. } // namespace
  4117. TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
  4118. Message msg;
  4119. MyTypeInUnnamedNameSpace a(1);
  4120. msg << a << &a; // Uses <unnamed_namespace>::operator<<.
  4121. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4122. }
  4123. // Tests streaming a user type whose definition and operator<< are
  4124. // both in a user namespace.
  4125. namespace namespace1 {
  4126. class MyTypeInNameSpace1 : public Base {
  4127. public:
  4128. explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
  4129. };
  4130. std::ostream& operator<<(std::ostream& os,
  4131. const MyTypeInNameSpace1& val) {
  4132. return os << val.x();
  4133. }
  4134. std::ostream& operator<<(std::ostream& os,
  4135. const MyTypeInNameSpace1* pointer) {
  4136. return os << "(" << pointer->x() << ")";
  4137. }
  4138. } // namespace namespace1
  4139. TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
  4140. Message msg;
  4141. namespace1::MyTypeInNameSpace1 a(1);
  4142. msg << a << &a; // Uses namespace1::operator<<.
  4143. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4144. }
  4145. // Tests streaming a user type whose definition is in a user namespace
  4146. // but whose operator<< is in the global namespace.
  4147. namespace namespace2 {
  4148. class MyTypeInNameSpace2 : public ::Base {
  4149. public:
  4150. explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
  4151. };
  4152. } // namespace namespace2
  4153. std::ostream& operator<<(std::ostream& os,
  4154. const namespace2::MyTypeInNameSpace2& val) {
  4155. return os << val.x();
  4156. }
  4157. std::ostream& operator<<(std::ostream& os,
  4158. const namespace2::MyTypeInNameSpace2* pointer) {
  4159. return os << "(" << pointer->x() << ")";
  4160. }
  4161. TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
  4162. Message msg;
  4163. namespace2::MyTypeInNameSpace2 a(1);
  4164. msg << a << &a; // Uses ::operator<<.
  4165. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4166. }
  4167. // Tests streaming NULL pointers to testing::Message.
  4168. TEST(MessageTest, NullPointers) {
  4169. Message msg;
  4170. char* const p1 = NULL;
  4171. unsigned char* const p2 = NULL;
  4172. int* p3 = NULL;
  4173. double* p4 = NULL;
  4174. bool* p5 = NULL;
  4175. Message* p6 = NULL;
  4176. msg << p1 << p2 << p3 << p4 << p5 << p6;
  4177. ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
  4178. msg.GetString().c_str());
  4179. }
  4180. // Tests streaming wide strings to testing::Message.
  4181. TEST(MessageTest, WideStrings) {
  4182. // Streams a NULL of type const wchar_t*.
  4183. const wchar_t* const_wstr = NULL;
  4184. EXPECT_STREQ("(null)",
  4185. (Message() << const_wstr).GetString().c_str());
  4186. // Streams a NULL of type wchar_t*.
  4187. wchar_t* wstr = NULL;
  4188. EXPECT_STREQ("(null)",
  4189. (Message() << wstr).GetString().c_str());
  4190. // Streams a non-NULL of type const wchar_t*.
  4191. const_wstr = L"abc\x8119";
  4192. EXPECT_STREQ("abc\xe8\x84\x99",
  4193. (Message() << const_wstr).GetString().c_str());
  4194. // Streams a non-NULL of type wchar_t*.
  4195. wstr = const_cast<wchar_t*>(const_wstr);
  4196. EXPECT_STREQ("abc\xe8\x84\x99",
  4197. (Message() << wstr).GetString().c_str());
  4198. }
  4199. // This line tests that we can define tests in the testing namespace.
  4200. namespace testing {
  4201. // Tests the TestInfo class.
  4202. class TestInfoTest : public Test {
  4203. protected:
  4204. static const TestInfo* GetTestInfo(const char* test_name) {
  4205. const TestCase* const test_case = GetUnitTestImpl()->
  4206. GetTestCase("TestInfoTest", "", NULL, NULL);
  4207. for (int i = 0; i < test_case->total_test_count(); ++i) {
  4208. const TestInfo* const test_info = test_case->GetTestInfo(i);
  4209. if (strcmp(test_name, test_info->name()) == 0)
  4210. return test_info;
  4211. }
  4212. return NULL;
  4213. }
  4214. static const TestResult* GetTestResult(
  4215. const TestInfo* test_info) {
  4216. return test_info->result();
  4217. }
  4218. };
  4219. // Tests TestInfo::test_case_name() and TestInfo::name().
  4220. TEST_F(TestInfoTest, Names) {
  4221. const TestInfo* const test_info = GetTestInfo("Names");
  4222. ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
  4223. ASSERT_STREQ("Names", test_info->name());
  4224. }
  4225. // Tests TestInfo::result().
  4226. TEST_F(TestInfoTest, result) {
  4227. const TestInfo* const test_info = GetTestInfo("result");
  4228. // Initially, there is no TestPartResult for this test.
  4229. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4230. // After the previous assertion, there is still none.
  4231. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4232. }
  4233. // Tests setting up and tearing down a test case.
  4234. class SetUpTestCaseTest : public Test {
  4235. protected:
  4236. // This will be called once before the first test in this test case
  4237. // is run.
  4238. static void SetUpTestCase() {
  4239. printf("Setting up the test case . . .\n");
  4240. // Initializes some shared resource. In this simple example, we
  4241. // just create a C string. More complex stuff can be done if
  4242. // desired.
  4243. shared_resource_ = "123";
  4244. // Increments the number of test cases that have been set up.
  4245. counter_++;
  4246. // SetUpTestCase() should be called only once.
  4247. EXPECT_EQ(1, counter_);
  4248. }
  4249. // This will be called once after the last test in this test case is
  4250. // run.
  4251. static void TearDownTestCase() {
  4252. printf("Tearing down the test case . . .\n");
  4253. // Decrements the number of test cases that have been set up.
  4254. counter_--;
  4255. // TearDownTestCase() should be called only once.
  4256. EXPECT_EQ(0, counter_);
  4257. // Cleans up the shared resource.
  4258. shared_resource_ = NULL;
  4259. }
  4260. // This will be called before each test in this test case.
  4261. virtual void SetUp() {
  4262. // SetUpTestCase() should be called only once, so counter_ should
  4263. // always be 1.
  4264. EXPECT_EQ(1, counter_);
  4265. }
  4266. // Number of test cases that have been set up.
  4267. static int counter_;
  4268. // Some resource to be shared by all tests in this test case.
  4269. static const char* shared_resource_;
  4270. };
  4271. int SetUpTestCaseTest::counter_ = 0;
  4272. const char* SetUpTestCaseTest::shared_resource_ = NULL;
  4273. // A test that uses the shared resource.
  4274. TEST_F(SetUpTestCaseTest, Test1) {
  4275. EXPECT_STRNE(NULL, shared_resource_);
  4276. }
  4277. // Another test that uses the shared resource.
  4278. TEST_F(SetUpTestCaseTest, Test2) {
  4279. EXPECT_STREQ("123", shared_resource_);
  4280. }
  4281. // The InitGoogleTestTest test case tests testing::InitGoogleTest().
  4282. // The Flags struct stores a copy of all Google Test flags.
  4283. struct Flags {
  4284. // Constructs a Flags struct where each flag has its default value.
  4285. Flags() : also_run_disabled_tests(false),
  4286. break_on_failure(false),
  4287. catch_exceptions(false),
  4288. death_test_use_fork(false),
  4289. filter(""),
  4290. list_tests(false),
  4291. output(""),
  4292. print_time(true),
  4293. random_seed(0),
  4294. repeat(1),
  4295. shuffle(false),
  4296. stack_trace_depth(kMaxStackTraceDepth),
  4297. stream_result_to(""),
  4298. throw_on_failure(false) {}
  4299. // Factory methods.
  4300. // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
  4301. // the given value.
  4302. static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
  4303. Flags flags;
  4304. flags.also_run_disabled_tests = also_run_disabled_tests;
  4305. return flags;
  4306. }
  4307. // Creates a Flags struct where the gtest_break_on_failure flag has
  4308. // the given value.
  4309. static Flags BreakOnFailure(bool break_on_failure) {
  4310. Flags flags;
  4311. flags.break_on_failure = break_on_failure;
  4312. return flags;
  4313. }
  4314. // Creates a Flags struct where the gtest_catch_exceptions flag has
  4315. // the given value.
  4316. static Flags CatchExceptions(bool catch_exceptions) {
  4317. Flags flags;
  4318. flags.catch_exceptions = catch_exceptions;
  4319. return flags;
  4320. }
  4321. // Creates a Flags struct where the gtest_death_test_use_fork flag has
  4322. // the given value.
  4323. static Flags DeathTestUseFork(bool death_test_use_fork) {
  4324. Flags flags;
  4325. flags.death_test_use_fork = death_test_use_fork;
  4326. return flags;
  4327. }
  4328. // Creates a Flags struct where the gtest_filter flag has the given
  4329. // value.
  4330. static Flags Filter(const char* filter) {
  4331. Flags flags;
  4332. flags.filter = filter;
  4333. return flags;
  4334. }
  4335. // Creates a Flags struct where the gtest_list_tests flag has the
  4336. // given value.
  4337. static Flags ListTests(bool list_tests) {
  4338. Flags flags;
  4339. flags.list_tests = list_tests;
  4340. return flags;
  4341. }
  4342. // Creates a Flags struct where the gtest_output flag has the given
  4343. // value.
  4344. static Flags Output(const char* output) {
  4345. Flags flags;
  4346. flags.output = output;
  4347. return flags;
  4348. }
  4349. // Creates a Flags struct where the gtest_print_time flag has the given
  4350. // value.
  4351. static Flags PrintTime(bool print_time) {
  4352. Flags flags;
  4353. flags.print_time = print_time;
  4354. return flags;
  4355. }
  4356. // Creates a Flags struct where the gtest_random_seed flag has
  4357. // the given value.
  4358. static Flags RandomSeed(Int32 random_seed) {
  4359. Flags flags;
  4360. flags.random_seed = random_seed;
  4361. return flags;
  4362. }
  4363. // Creates a Flags struct where the gtest_repeat flag has the given
  4364. // value.
  4365. static Flags Repeat(Int32 repeat) {
  4366. Flags flags;
  4367. flags.repeat = repeat;
  4368. return flags;
  4369. }
  4370. // Creates a Flags struct where the gtest_shuffle flag has
  4371. // the given value.
  4372. static Flags Shuffle(bool shuffle) {
  4373. Flags flags;
  4374. flags.shuffle = shuffle;
  4375. return flags;
  4376. }
  4377. // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
  4378. // the given value.
  4379. static Flags StackTraceDepth(Int32 stack_trace_depth) {
  4380. Flags flags;
  4381. flags.stack_trace_depth = stack_trace_depth;
  4382. return flags;
  4383. }
  4384. // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
  4385. // the given value.
  4386. static Flags StreamResultTo(const char* stream_result_to) {
  4387. Flags flags;
  4388. flags.stream_result_to = stream_result_to;
  4389. return flags;
  4390. }
  4391. // Creates a Flags struct where the gtest_throw_on_failure flag has
  4392. // the given value.
  4393. static Flags ThrowOnFailure(bool throw_on_failure) {
  4394. Flags flags;
  4395. flags.throw_on_failure = throw_on_failure;
  4396. return flags;
  4397. }
  4398. // These fields store the flag values.
  4399. bool also_run_disabled_tests;
  4400. bool break_on_failure;
  4401. bool catch_exceptions;
  4402. bool death_test_use_fork;
  4403. const char* filter;
  4404. bool list_tests;
  4405. const char* output;
  4406. bool print_time;
  4407. Int32 random_seed;
  4408. Int32 repeat;
  4409. bool shuffle;
  4410. Int32 stack_trace_depth;
  4411. const char* stream_result_to;
  4412. bool throw_on_failure;
  4413. };
  4414. // Fixture for testing InitGoogleTest().
  4415. class InitGoogleTestTest : public Test {
  4416. protected:
  4417. // Clears the flags before each test.
  4418. virtual void SetUp() {
  4419. GTEST_FLAG(also_run_disabled_tests) = false;
  4420. GTEST_FLAG(break_on_failure) = false;
  4421. GTEST_FLAG(catch_exceptions) = false;
  4422. GTEST_FLAG(death_test_use_fork) = false;
  4423. GTEST_FLAG(filter) = "";
  4424. GTEST_FLAG(list_tests) = false;
  4425. GTEST_FLAG(output) = "";
  4426. GTEST_FLAG(print_time) = true;
  4427. GTEST_FLAG(random_seed) = 0;
  4428. GTEST_FLAG(repeat) = 1;
  4429. GTEST_FLAG(shuffle) = false;
  4430. GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
  4431. GTEST_FLAG(stream_result_to) = "";
  4432. GTEST_FLAG(throw_on_failure) = false;
  4433. }
  4434. // Asserts that two narrow or wide string arrays are equal.
  4435. template <typename CharType>
  4436. static void AssertStringArrayEq(size_t size1, CharType** array1,
  4437. size_t size2, CharType** array2) {
  4438. ASSERT_EQ(size1, size2) << " Array sizes different.";
  4439. for (size_t i = 0; i != size1; i++) {
  4440. ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
  4441. }
  4442. }
  4443. // Verifies that the flag values match the expected values.
  4444. static void CheckFlags(const Flags& expected) {
  4445. EXPECT_EQ(expected.also_run_disabled_tests,
  4446. GTEST_FLAG(also_run_disabled_tests));
  4447. EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
  4448. EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
  4449. EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
  4450. EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
  4451. EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
  4452. EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
  4453. EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
  4454. EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
  4455. EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
  4456. EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
  4457. EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
  4458. EXPECT_STREQ(expected.stream_result_to,
  4459. GTEST_FLAG(stream_result_to).c_str());
  4460. EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
  4461. }
  4462. // Parses a command line (specified by argc1 and argv1), then
  4463. // verifies that the flag values are expected and that the
  4464. // recognized flags are removed from the command line.
  4465. template <typename CharType>
  4466. static void TestParsingFlags(int argc1, const CharType** argv1,
  4467. int argc2, const CharType** argv2,
  4468. const Flags& expected, bool should_print_help) {
  4469. const bool saved_help_flag = ::testing::internal::g_help_flag;
  4470. ::testing::internal::g_help_flag = false;
  4471. #if GTEST_HAS_STREAM_REDIRECTION
  4472. CaptureStdout();
  4473. #endif
  4474. // Parses the command line.
  4475. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
  4476. #if GTEST_HAS_STREAM_REDIRECTION
  4477. const std::string captured_stdout = GetCapturedStdout();
  4478. #endif
  4479. // Verifies the flag values.
  4480. CheckFlags(expected);
  4481. // Verifies that the recognized flags are removed from the command
  4482. // line.
  4483. AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
  4484. // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
  4485. // help message for the flags it recognizes.
  4486. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
  4487. #if GTEST_HAS_STREAM_REDIRECTION
  4488. const char* const expected_help_fragment =
  4489. "This program contains tests written using";
  4490. if (should_print_help) {
  4491. EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
  4492. } else {
  4493. EXPECT_PRED_FORMAT2(IsNotSubstring,
  4494. expected_help_fragment, captured_stdout);
  4495. }
  4496. #endif // GTEST_HAS_STREAM_REDIRECTION
  4497. ::testing::internal::g_help_flag = saved_help_flag;
  4498. }
  4499. // This macro wraps TestParsingFlags s.t. the user doesn't need
  4500. // to specify the array sizes.
  4501. #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
  4502. TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
  4503. sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
  4504. expected, should_print_help)
  4505. };
  4506. // Tests parsing an empty command line.
  4507. TEST_F(InitGoogleTestTest, Empty) {
  4508. const char* argv[] = {
  4509. NULL
  4510. };
  4511. const char* argv2[] = {
  4512. NULL
  4513. };
  4514. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4515. }
  4516. // Tests parsing a command line that has no flag.
  4517. TEST_F(InitGoogleTestTest, NoFlag) {
  4518. const char* argv[] = {
  4519. "foo.exe",
  4520. NULL
  4521. };
  4522. const char* argv2[] = {
  4523. "foo.exe",
  4524. NULL
  4525. };
  4526. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4527. }
  4528. // Tests parsing a bad --gtest_filter flag.
  4529. TEST_F(InitGoogleTestTest, FilterBad) {
  4530. const char* argv[] = {
  4531. "foo.exe",
  4532. "--gtest_filter",
  4533. NULL
  4534. };
  4535. const char* argv2[] = {
  4536. "foo.exe",
  4537. "--gtest_filter",
  4538. NULL
  4539. };
  4540. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
  4541. }
  4542. // Tests parsing an empty --gtest_filter flag.
  4543. TEST_F(InitGoogleTestTest, FilterEmpty) {
  4544. const char* argv[] = {
  4545. "foo.exe",
  4546. "--gtest_filter=",
  4547. NULL
  4548. };
  4549. const char* argv2[] = {
  4550. "foo.exe",
  4551. NULL
  4552. };
  4553. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
  4554. }
  4555. // Tests parsing a non-empty --gtest_filter flag.
  4556. TEST_F(InitGoogleTestTest, FilterNonEmpty) {
  4557. const char* argv[] = {
  4558. "foo.exe",
  4559. "--gtest_filter=abc",
  4560. NULL
  4561. };
  4562. const char* argv2[] = {
  4563. "foo.exe",
  4564. NULL
  4565. };
  4566. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
  4567. }
  4568. // Tests parsing --gtest_break_on_failure.
  4569. TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
  4570. const char* argv[] = {
  4571. "foo.exe",
  4572. "--gtest_break_on_failure",
  4573. NULL
  4574. };
  4575. const char* argv2[] = {
  4576. "foo.exe",
  4577. NULL
  4578. };
  4579. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4580. }
  4581. // Tests parsing --gtest_break_on_failure=0.
  4582. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
  4583. const char* argv[] = {
  4584. "foo.exe",
  4585. "--gtest_break_on_failure=0",
  4586. NULL
  4587. };
  4588. const char* argv2[] = {
  4589. "foo.exe",
  4590. NULL
  4591. };
  4592. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4593. }
  4594. // Tests parsing --gtest_break_on_failure=f.
  4595. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
  4596. const char* argv[] = {
  4597. "foo.exe",
  4598. "--gtest_break_on_failure=f",
  4599. NULL
  4600. };
  4601. const char* argv2[] = {
  4602. "foo.exe",
  4603. NULL
  4604. };
  4605. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4606. }
  4607. // Tests parsing --gtest_break_on_failure=F.
  4608. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
  4609. const char* argv[] = {
  4610. "foo.exe",
  4611. "--gtest_break_on_failure=F",
  4612. NULL
  4613. };
  4614. const char* argv2[] = {
  4615. "foo.exe",
  4616. NULL
  4617. };
  4618. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4619. }
  4620. // Tests parsing a --gtest_break_on_failure flag that has a "true"
  4621. // definition.
  4622. TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
  4623. const char* argv[] = {
  4624. "foo.exe",
  4625. "--gtest_break_on_failure=1",
  4626. NULL
  4627. };
  4628. const char* argv2[] = {
  4629. "foo.exe",
  4630. NULL
  4631. };
  4632. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4633. }
  4634. // Tests parsing --gtest_catch_exceptions.
  4635. TEST_F(InitGoogleTestTest, CatchExceptions) {
  4636. const char* argv[] = {
  4637. "foo.exe",
  4638. "--gtest_catch_exceptions",
  4639. NULL
  4640. };
  4641. const char* argv2[] = {
  4642. "foo.exe",
  4643. NULL
  4644. };
  4645. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
  4646. }
  4647. // Tests parsing --gtest_death_test_use_fork.
  4648. TEST_F(InitGoogleTestTest, DeathTestUseFork) {
  4649. const char* argv[] = {
  4650. "foo.exe",
  4651. "--gtest_death_test_use_fork",
  4652. NULL
  4653. };
  4654. const char* argv2[] = {
  4655. "foo.exe",
  4656. NULL
  4657. };
  4658. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
  4659. }
  4660. // Tests having the same flag twice with different values. The
  4661. // expected behavior is that the one coming last takes precedence.
  4662. TEST_F(InitGoogleTestTest, DuplicatedFlags) {
  4663. const char* argv[] = {
  4664. "foo.exe",
  4665. "--gtest_filter=a",
  4666. "--gtest_filter=b",
  4667. NULL
  4668. };
  4669. const char* argv2[] = {
  4670. "foo.exe",
  4671. NULL
  4672. };
  4673. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
  4674. }
  4675. // Tests having an unrecognized flag on the command line.
  4676. TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
  4677. const char* argv[] = {
  4678. "foo.exe",
  4679. "--gtest_break_on_failure",
  4680. "bar", // Unrecognized by Google Test.
  4681. "--gtest_filter=b",
  4682. NULL
  4683. };
  4684. const char* argv2[] = {
  4685. "foo.exe",
  4686. "bar",
  4687. NULL
  4688. };
  4689. Flags flags;
  4690. flags.break_on_failure = true;
  4691. flags.filter = "b";
  4692. GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
  4693. }
  4694. // Tests having a --gtest_list_tests flag
  4695. TEST_F(InitGoogleTestTest, ListTestsFlag) {
  4696. const char* argv[] = {
  4697. "foo.exe",
  4698. "--gtest_list_tests",
  4699. NULL
  4700. };
  4701. const char* argv2[] = {
  4702. "foo.exe",
  4703. NULL
  4704. };
  4705. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4706. }
  4707. // Tests having a --gtest_list_tests flag with a "true" value
  4708. TEST_F(InitGoogleTestTest, ListTestsTrue) {
  4709. const char* argv[] = {
  4710. "foo.exe",
  4711. "--gtest_list_tests=1",
  4712. NULL
  4713. };
  4714. const char* argv2[] = {
  4715. "foo.exe",
  4716. NULL
  4717. };
  4718. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4719. }
  4720. // Tests having a --gtest_list_tests flag with a "false" value
  4721. TEST_F(InitGoogleTestTest, ListTestsFalse) {
  4722. const char* argv[] = {
  4723. "foo.exe",
  4724. "--gtest_list_tests=0",
  4725. NULL
  4726. };
  4727. const char* argv2[] = {
  4728. "foo.exe",
  4729. NULL
  4730. };
  4731. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4732. }
  4733. // Tests parsing --gtest_list_tests=f.
  4734. TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
  4735. const char* argv[] = {
  4736. "foo.exe",
  4737. "--gtest_list_tests=f",
  4738. NULL
  4739. };
  4740. const char* argv2[] = {
  4741. "foo.exe",
  4742. NULL
  4743. };
  4744. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4745. }
  4746. // Tests parsing --gtest_list_tests=F.
  4747. TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
  4748. const char* argv[] = {
  4749. "foo.exe",
  4750. "--gtest_list_tests=F",
  4751. NULL
  4752. };
  4753. const char* argv2[] = {
  4754. "foo.exe",
  4755. NULL
  4756. };
  4757. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4758. }
  4759. // Tests parsing --gtest_output (invalid).
  4760. TEST_F(InitGoogleTestTest, OutputEmpty) {
  4761. const char* argv[] = {
  4762. "foo.exe",
  4763. "--gtest_output",
  4764. NULL
  4765. };
  4766. const char* argv2[] = {
  4767. "foo.exe",
  4768. "--gtest_output",
  4769. NULL
  4770. };
  4771. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
  4772. }
  4773. // Tests parsing --gtest_output=xml
  4774. TEST_F(InitGoogleTestTest, OutputXml) {
  4775. const char* argv[] = {
  4776. "foo.exe",
  4777. "--gtest_output=xml",
  4778. NULL
  4779. };
  4780. const char* argv2[] = {
  4781. "foo.exe",
  4782. NULL
  4783. };
  4784. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
  4785. }
  4786. // Tests parsing --gtest_output=xml:file
  4787. TEST_F(InitGoogleTestTest, OutputXmlFile) {
  4788. const char* argv[] = {
  4789. "foo.exe",
  4790. "--gtest_output=xml:file",
  4791. NULL
  4792. };
  4793. const char* argv2[] = {
  4794. "foo.exe",
  4795. NULL
  4796. };
  4797. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
  4798. }
  4799. // Tests parsing --gtest_output=xml:directory/path/
  4800. TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
  4801. const char* argv[] = {
  4802. "foo.exe",
  4803. "--gtest_output=xml:directory/path/",
  4804. NULL
  4805. };
  4806. const char* argv2[] = {
  4807. "foo.exe",
  4808. NULL
  4809. };
  4810. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4811. Flags::Output("xml:directory/path/"), false);
  4812. }
  4813. // Tests having a --gtest_print_time flag
  4814. TEST_F(InitGoogleTestTest, PrintTimeFlag) {
  4815. const char* argv[] = {
  4816. "foo.exe",
  4817. "--gtest_print_time",
  4818. NULL
  4819. };
  4820. const char* argv2[] = {
  4821. "foo.exe",
  4822. NULL
  4823. };
  4824. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  4825. }
  4826. // Tests having a --gtest_print_time flag with a "true" value
  4827. TEST_F(InitGoogleTestTest, PrintTimeTrue) {
  4828. const char* argv[] = {
  4829. "foo.exe",
  4830. "--gtest_print_time=1",
  4831. NULL
  4832. };
  4833. const char* argv2[] = {
  4834. "foo.exe",
  4835. NULL
  4836. };
  4837. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  4838. }
  4839. // Tests having a --gtest_print_time flag with a "false" value
  4840. TEST_F(InitGoogleTestTest, PrintTimeFalse) {
  4841. const char* argv[] = {
  4842. "foo.exe",
  4843. "--gtest_print_time=0",
  4844. NULL
  4845. };
  4846. const char* argv2[] = {
  4847. "foo.exe",
  4848. NULL
  4849. };
  4850. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4851. }
  4852. // Tests parsing --gtest_print_time=f.
  4853. TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
  4854. const char* argv[] = {
  4855. "foo.exe",
  4856. "--gtest_print_time=f",
  4857. NULL
  4858. };
  4859. const char* argv2[] = {
  4860. "foo.exe",
  4861. NULL
  4862. };
  4863. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4864. }
  4865. // Tests parsing --gtest_print_time=F.
  4866. TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
  4867. const char* argv[] = {
  4868. "foo.exe",
  4869. "--gtest_print_time=F",
  4870. NULL
  4871. };
  4872. const char* argv2[] = {
  4873. "foo.exe",
  4874. NULL
  4875. };
  4876. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4877. }
  4878. // Tests parsing --gtest_random_seed=number
  4879. TEST_F(InitGoogleTestTest, RandomSeed) {
  4880. const char* argv[] = {
  4881. "foo.exe",
  4882. "--gtest_random_seed=1000",
  4883. NULL
  4884. };
  4885. const char* argv2[] = {
  4886. "foo.exe",
  4887. NULL
  4888. };
  4889. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
  4890. }
  4891. // Tests parsing --gtest_repeat=number
  4892. TEST_F(InitGoogleTestTest, Repeat) {
  4893. const char* argv[] = {
  4894. "foo.exe",
  4895. "--gtest_repeat=1000",
  4896. NULL
  4897. };
  4898. const char* argv2[] = {
  4899. "foo.exe",
  4900. NULL
  4901. };
  4902. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
  4903. }
  4904. // Tests having a --gtest_also_run_disabled_tests flag
  4905. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
  4906. const char* argv[] = {
  4907. "foo.exe",
  4908. "--gtest_also_run_disabled_tests",
  4909. NULL
  4910. };
  4911. const char* argv2[] = {
  4912. "foo.exe",
  4913. NULL
  4914. };
  4915. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4916. Flags::AlsoRunDisabledTests(true), false);
  4917. }
  4918. // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
  4919. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
  4920. const char* argv[] = {
  4921. "foo.exe",
  4922. "--gtest_also_run_disabled_tests=1",
  4923. NULL
  4924. };
  4925. const char* argv2[] = {
  4926. "foo.exe",
  4927. NULL
  4928. };
  4929. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4930. Flags::AlsoRunDisabledTests(true), false);
  4931. }
  4932. // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
  4933. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
  4934. const char* argv[] = {
  4935. "foo.exe",
  4936. "--gtest_also_run_disabled_tests=0",
  4937. NULL
  4938. };
  4939. const char* argv2[] = {
  4940. "foo.exe",
  4941. NULL
  4942. };
  4943. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4944. Flags::AlsoRunDisabledTests(false), false);
  4945. }
  4946. // Tests parsing --gtest_shuffle.
  4947. TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
  4948. const char* argv[] = {
  4949. "foo.exe",
  4950. "--gtest_shuffle",
  4951. NULL
  4952. };
  4953. const char* argv2[] = {
  4954. "foo.exe",
  4955. NULL
  4956. };
  4957. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  4958. }
  4959. // Tests parsing --gtest_shuffle=0.
  4960. TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
  4961. const char* argv[] = {
  4962. "foo.exe",
  4963. "--gtest_shuffle=0",
  4964. NULL
  4965. };
  4966. const char* argv2[] = {
  4967. "foo.exe",
  4968. NULL
  4969. };
  4970. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
  4971. }
  4972. // Tests parsing a --gtest_shuffle flag that has a "true"
  4973. // definition.
  4974. TEST_F(InitGoogleTestTest, ShuffleTrue) {
  4975. const char* argv[] = {
  4976. "foo.exe",
  4977. "--gtest_shuffle=1",
  4978. NULL
  4979. };
  4980. const char* argv2[] = {
  4981. "foo.exe",
  4982. NULL
  4983. };
  4984. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  4985. }
  4986. // Tests parsing --gtest_stack_trace_depth=number.
  4987. TEST_F(InitGoogleTestTest, StackTraceDepth) {
  4988. const char* argv[] = {
  4989. "foo.exe",
  4990. "--gtest_stack_trace_depth=5",
  4991. NULL
  4992. };
  4993. const char* argv2[] = {
  4994. "foo.exe",
  4995. NULL
  4996. };
  4997. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
  4998. }
  4999. TEST_F(InitGoogleTestTest, StreamResultTo) {
  5000. const char* argv[] = {
  5001. "foo.exe",
  5002. "--gtest_stream_result_to=localhost:1234",
  5003. NULL
  5004. };
  5005. const char* argv2[] = {
  5006. "foo.exe",
  5007. NULL
  5008. };
  5009. GTEST_TEST_PARSING_FLAGS_(
  5010. argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
  5011. }
  5012. // Tests parsing --gtest_throw_on_failure.
  5013. TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
  5014. const char* argv[] = {
  5015. "foo.exe",
  5016. "--gtest_throw_on_failure",
  5017. NULL
  5018. };
  5019. const char* argv2[] = {
  5020. "foo.exe",
  5021. NULL
  5022. };
  5023. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  5024. }
  5025. // Tests parsing --gtest_throw_on_failure=0.
  5026. TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
  5027. const char* argv[] = {
  5028. "foo.exe",
  5029. "--gtest_throw_on_failure=0",
  5030. NULL
  5031. };
  5032. const char* argv2[] = {
  5033. "foo.exe",
  5034. NULL
  5035. };
  5036. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
  5037. }
  5038. // Tests parsing a --gtest_throw_on_failure flag that has a "true"
  5039. // definition.
  5040. TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
  5041. const char* argv[] = {
  5042. "foo.exe",
  5043. "--gtest_throw_on_failure=1",
  5044. NULL
  5045. };
  5046. const char* argv2[] = {
  5047. "foo.exe",
  5048. NULL
  5049. };
  5050. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  5051. }
  5052. #if GTEST_OS_WINDOWS
  5053. // Tests parsing wide strings.
  5054. TEST_F(InitGoogleTestTest, WideStrings) {
  5055. const wchar_t* argv[] = {
  5056. L"foo.exe",
  5057. L"--gtest_filter=Foo*",
  5058. L"--gtest_list_tests=1",
  5059. L"--gtest_break_on_failure",
  5060. L"--non_gtest_flag",
  5061. NULL
  5062. };
  5063. const wchar_t* argv2[] = {
  5064. L"foo.exe",
  5065. L"--non_gtest_flag",
  5066. NULL
  5067. };
  5068. Flags expected_flags;
  5069. expected_flags.break_on_failure = true;
  5070. expected_flags.filter = "Foo*";
  5071. expected_flags.list_tests = true;
  5072. GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
  5073. }
  5074. #endif // GTEST_OS_WINDOWS
  5075. // Tests current_test_info() in UnitTest.
  5076. class CurrentTestInfoTest : public Test {
  5077. protected:
  5078. // Tests that current_test_info() returns NULL before the first test in
  5079. // the test case is run.
  5080. static void SetUpTestCase() {
  5081. // There should be no tests running at this point.
  5082. const TestInfo* test_info =
  5083. UnitTest::GetInstance()->current_test_info();
  5084. EXPECT_TRUE(test_info == NULL)
  5085. << "There should be no tests running at this point.";
  5086. }
  5087. // Tests that current_test_info() returns NULL after the last test in
  5088. // the test case has run.
  5089. static void TearDownTestCase() {
  5090. const TestInfo* test_info =
  5091. UnitTest::GetInstance()->current_test_info();
  5092. EXPECT_TRUE(test_info == NULL)
  5093. << "There should be no tests running at this point.";
  5094. }
  5095. };
  5096. // Tests that current_test_info() returns TestInfo for currently running
  5097. // test by checking the expected test name against the actual one.
  5098. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
  5099. const TestInfo* test_info =
  5100. UnitTest::GetInstance()->current_test_info();
  5101. ASSERT_TRUE(NULL != test_info)
  5102. << "There is a test running so we should have a valid TestInfo.";
  5103. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
  5104. << "Expected the name of the currently running test case.";
  5105. EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
  5106. << "Expected the name of the currently running test.";
  5107. }
  5108. // Tests that current_test_info() returns TestInfo for currently running
  5109. // test by checking the expected test name against the actual one. We
  5110. // use this test to see that the TestInfo object actually changed from
  5111. // the previous invocation.
  5112. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
  5113. const TestInfo* test_info =
  5114. UnitTest::GetInstance()->current_test_info();
  5115. ASSERT_TRUE(NULL != test_info)
  5116. << "There is a test running so we should have a valid TestInfo.";
  5117. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
  5118. << "Expected the name of the currently running test case.";
  5119. EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
  5120. << "Expected the name of the currently running test.";
  5121. }
  5122. } // namespace testing
  5123. // These two lines test that we can define tests in a namespace that
  5124. // has the name "testing" and is nested in another namespace.
  5125. namespace my_namespace {
  5126. namespace testing {
  5127. // Makes sure that TEST knows to use ::testing::Test instead of
  5128. // ::my_namespace::testing::Test.
  5129. class Test {};
  5130. // Makes sure that an assertion knows to use ::testing::Message instead of
  5131. // ::my_namespace::testing::Message.
  5132. class Message {};
  5133. // Makes sure that an assertion knows to use
  5134. // ::testing::AssertionResult instead of
  5135. // ::my_namespace::testing::AssertionResult.
  5136. class AssertionResult {};
  5137. // Tests that an assertion that should succeed works as expected.
  5138. TEST(NestedTestingNamespaceTest, Success) {
  5139. EXPECT_EQ(1, 1) << "This shouldn't fail.";
  5140. }
  5141. // Tests that an assertion that should fail works as expected.
  5142. TEST(NestedTestingNamespaceTest, Failure) {
  5143. EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
  5144. "This failure is expected.");
  5145. }
  5146. } // namespace testing
  5147. } // namespace my_namespace
  5148. // Tests that one can call superclass SetUp and TearDown methods--
  5149. // that is, that they are not private.
  5150. // No tests are based on this fixture; the test "passes" if it compiles
  5151. // successfully.
  5152. class ProtectedFixtureMethodsTest : public Test {
  5153. protected:
  5154. virtual void SetUp() {
  5155. Test::SetUp();
  5156. }
  5157. virtual void TearDown() {
  5158. Test::TearDown();
  5159. }
  5160. };
  5161. // StreamingAssertionsTest tests the streaming versions of a representative
  5162. // sample of assertions.
  5163. TEST(StreamingAssertionsTest, Unconditional) {
  5164. SUCCEED() << "expected success";
  5165. EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
  5166. "expected failure");
  5167. EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
  5168. "expected failure");
  5169. }
  5170. #ifdef __BORLANDC__
  5171. // Silences warnings: "Condition is always true", "Unreachable code"
  5172. # pragma option push -w-ccc -w-rch
  5173. #endif
  5174. TEST(StreamingAssertionsTest, Truth) {
  5175. EXPECT_TRUE(true) << "unexpected failure";
  5176. ASSERT_TRUE(true) << "unexpected failure";
  5177. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
  5178. "expected failure");
  5179. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
  5180. "expected failure");
  5181. }
  5182. TEST(StreamingAssertionsTest, Truth2) {
  5183. EXPECT_FALSE(false) << "unexpected failure";
  5184. ASSERT_FALSE(false) << "unexpected failure";
  5185. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
  5186. "expected failure");
  5187. EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
  5188. "expected failure");
  5189. }
  5190. #ifdef __BORLANDC__
  5191. // Restores warnings after previous "#pragma option push" supressed them
  5192. # pragma option pop
  5193. #endif
  5194. TEST(StreamingAssertionsTest, IntegerEquals) {
  5195. EXPECT_EQ(1, 1) << "unexpected failure";
  5196. ASSERT_EQ(1, 1) << "unexpected failure";
  5197. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
  5198. "expected failure");
  5199. EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
  5200. "expected failure");
  5201. }
  5202. TEST(StreamingAssertionsTest, IntegerLessThan) {
  5203. EXPECT_LT(1, 2) << "unexpected failure";
  5204. ASSERT_LT(1, 2) << "unexpected failure";
  5205. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
  5206. "expected failure");
  5207. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
  5208. "expected failure");
  5209. }
  5210. TEST(StreamingAssertionsTest, StringsEqual) {
  5211. EXPECT_STREQ("foo", "foo") << "unexpected failure";
  5212. ASSERT_STREQ("foo", "foo") << "unexpected failure";
  5213. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
  5214. "expected failure");
  5215. EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
  5216. "expected failure");
  5217. }
  5218. TEST(StreamingAssertionsTest, StringsNotEqual) {
  5219. EXPECT_STRNE("foo", "bar") << "unexpected failure";
  5220. ASSERT_STRNE("foo", "bar") << "unexpected failure";
  5221. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
  5222. "expected failure");
  5223. EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
  5224. "expected failure");
  5225. }
  5226. TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
  5227. EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5228. ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5229. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
  5230. "expected failure");
  5231. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
  5232. "expected failure");
  5233. }
  5234. TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
  5235. EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
  5236. ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
  5237. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
  5238. "expected failure");
  5239. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
  5240. "expected failure");
  5241. }
  5242. TEST(StreamingAssertionsTest, FloatingPointEquals) {
  5243. EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5244. ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5245. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5246. "expected failure");
  5247. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5248. "expected failure");
  5249. }
  5250. #if GTEST_HAS_EXCEPTIONS
  5251. TEST(StreamingAssertionsTest, Throw) {
  5252. EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5253. ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5254. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
  5255. "expected failure", "expected failure");
  5256. EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
  5257. "expected failure", "expected failure");
  5258. }
  5259. TEST(StreamingAssertionsTest, NoThrow) {
  5260. EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5261. ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5262. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
  5263. "expected failure", "expected failure");
  5264. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
  5265. "expected failure", "expected failure");
  5266. }
  5267. TEST(StreamingAssertionsTest, AnyThrow) {
  5268. EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5269. ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5270. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
  5271. "expected failure", "expected failure");
  5272. EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
  5273. "expected failure", "expected failure");
  5274. }
  5275. #endif // GTEST_HAS_EXCEPTIONS
  5276. // Tests that Google Test correctly decides whether to use colors in the output.
  5277. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
  5278. GTEST_FLAG(color) = "yes";
  5279. SetEnv("TERM", "xterm"); // TERM supports colors.
  5280. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5281. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5282. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5283. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5284. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5285. }
  5286. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
  5287. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5288. GTEST_FLAG(color) = "True";
  5289. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5290. GTEST_FLAG(color) = "t";
  5291. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5292. GTEST_FLAG(color) = "1";
  5293. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5294. }
  5295. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
  5296. GTEST_FLAG(color) = "no";
  5297. SetEnv("TERM", "xterm"); // TERM supports colors.
  5298. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5299. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5300. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5301. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5302. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5303. }
  5304. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
  5305. SetEnv("TERM", "xterm"); // TERM supports colors.
  5306. GTEST_FLAG(color) = "F";
  5307. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5308. GTEST_FLAG(color) = "0";
  5309. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5310. GTEST_FLAG(color) = "unknown";
  5311. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5312. }
  5313. TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
  5314. GTEST_FLAG(color) = "auto";
  5315. SetEnv("TERM", "xterm"); // TERM supports colors.
  5316. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5317. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5318. }
  5319. TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
  5320. GTEST_FLAG(color) = "auto";
  5321. #if GTEST_OS_WINDOWS
  5322. // On Windows, we ignore the TERM variable as it's usually not set.
  5323. SetEnv("TERM", "dumb");
  5324. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5325. SetEnv("TERM", "");
  5326. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5327. SetEnv("TERM", "xterm");
  5328. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5329. #else
  5330. // On non-Windows platforms, we rely on TERM to determine if the
  5331. // terminal supports colors.
  5332. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5333. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5334. SetEnv("TERM", "emacs"); // TERM doesn't support colors.
  5335. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5336. SetEnv("TERM", "vt100"); // TERM doesn't support colors.
  5337. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5338. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
  5339. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5340. SetEnv("TERM", "xterm"); // TERM supports colors.
  5341. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5342. SetEnv("TERM", "xterm-color"); // TERM supports colors.
  5343. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5344. SetEnv("TERM", "xterm-256color"); // TERM supports colors.
  5345. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5346. SetEnv("TERM", "screen"); // TERM supports colors.
  5347. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5348. SetEnv("TERM", "linux"); // TERM supports colors.
  5349. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5350. SetEnv("TERM", "cygwin"); // TERM supports colors.
  5351. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5352. #endif // GTEST_OS_WINDOWS
  5353. }
  5354. // Verifies that StaticAssertTypeEq works in a namespace scope.
  5355. static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
  5356. static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
  5357. StaticAssertTypeEq<const int, const int>();
  5358. // Verifies that StaticAssertTypeEq works in a class.
  5359. template <typename T>
  5360. class StaticAssertTypeEqTestHelper {
  5361. public:
  5362. StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
  5363. };
  5364. TEST(StaticAssertTypeEqTest, WorksInClass) {
  5365. StaticAssertTypeEqTestHelper<bool>();
  5366. }
  5367. // Verifies that StaticAssertTypeEq works inside a function.
  5368. typedef int IntAlias;
  5369. TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
  5370. StaticAssertTypeEq<int, IntAlias>();
  5371. StaticAssertTypeEq<int*, IntAlias*>();
  5372. }
  5373. TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
  5374. testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
  5375. // We don't have a stack walker in Google Test yet.
  5376. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
  5377. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
  5378. }
  5379. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5380. EXPECT_FALSE(HasNonfatalFailure());
  5381. }
  5382. static void FailFatally() { FAIL(); }
  5383. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
  5384. FailFatally();
  5385. const bool has_nonfatal_failure = HasNonfatalFailure();
  5386. ClearCurrentTestPartResults();
  5387. EXPECT_FALSE(has_nonfatal_failure);
  5388. }
  5389. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5390. ADD_FAILURE();
  5391. const bool has_nonfatal_failure = HasNonfatalFailure();
  5392. ClearCurrentTestPartResults();
  5393. EXPECT_TRUE(has_nonfatal_failure);
  5394. }
  5395. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5396. FailFatally();
  5397. ADD_FAILURE();
  5398. const bool has_nonfatal_failure = HasNonfatalFailure();
  5399. ClearCurrentTestPartResults();
  5400. EXPECT_TRUE(has_nonfatal_failure);
  5401. }
  5402. // A wrapper for calling HasNonfatalFailure outside of a test body.
  5403. static bool HasNonfatalFailureHelper() {
  5404. return testing::Test::HasNonfatalFailure();
  5405. }
  5406. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
  5407. EXPECT_FALSE(HasNonfatalFailureHelper());
  5408. }
  5409. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
  5410. ADD_FAILURE();
  5411. const bool has_nonfatal_failure = HasNonfatalFailureHelper();
  5412. ClearCurrentTestPartResults();
  5413. EXPECT_TRUE(has_nonfatal_failure);
  5414. }
  5415. TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5416. EXPECT_FALSE(HasFailure());
  5417. }
  5418. TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
  5419. FailFatally();
  5420. const bool has_failure = HasFailure();
  5421. ClearCurrentTestPartResults();
  5422. EXPECT_TRUE(has_failure);
  5423. }
  5424. TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5425. ADD_FAILURE();
  5426. const bool has_failure = HasFailure();
  5427. ClearCurrentTestPartResults();
  5428. EXPECT_TRUE(has_failure);
  5429. }
  5430. TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5431. FailFatally();
  5432. ADD_FAILURE();
  5433. const bool has_failure = HasFailure();
  5434. ClearCurrentTestPartResults();
  5435. EXPECT_TRUE(has_failure);
  5436. }
  5437. // A wrapper for calling HasFailure outside of a test body.
  5438. static bool HasFailureHelper() { return testing::Test::HasFailure(); }
  5439. TEST(HasFailureTest, WorksOutsideOfTestBody) {
  5440. EXPECT_FALSE(HasFailureHelper());
  5441. }
  5442. TEST(HasFailureTest, WorksOutsideOfTestBody2) {
  5443. ADD_FAILURE();
  5444. const bool has_failure = HasFailureHelper();
  5445. ClearCurrentTestPartResults();
  5446. EXPECT_TRUE(has_failure);
  5447. }
  5448. class TestListener : public EmptyTestEventListener {
  5449. public:
  5450. TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
  5451. TestListener(int* on_start_counter, bool* is_destroyed)
  5452. : on_start_counter_(on_start_counter),
  5453. is_destroyed_(is_destroyed) {}
  5454. virtual ~TestListener() {
  5455. if (is_destroyed_)
  5456. *is_destroyed_ = true;
  5457. }
  5458. protected:
  5459. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
  5460. if (on_start_counter_ != NULL)
  5461. (*on_start_counter_)++;
  5462. }
  5463. private:
  5464. int* on_start_counter_;
  5465. bool* is_destroyed_;
  5466. };
  5467. // Tests the constructor.
  5468. TEST(TestEventListenersTest, ConstructionWorks) {
  5469. TestEventListeners listeners;
  5470. EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
  5471. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5472. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5473. }
  5474. // Tests that the TestEventListeners destructor deletes all the listeners it
  5475. // owns.
  5476. TEST(TestEventListenersTest, DestructionWorks) {
  5477. bool default_result_printer_is_destroyed = false;
  5478. bool default_xml_printer_is_destroyed = false;
  5479. bool extra_listener_is_destroyed = false;
  5480. TestListener* default_result_printer = new TestListener(
  5481. NULL, &default_result_printer_is_destroyed);
  5482. TestListener* default_xml_printer = new TestListener(
  5483. NULL, &default_xml_printer_is_destroyed);
  5484. TestListener* extra_listener = new TestListener(
  5485. NULL, &extra_listener_is_destroyed);
  5486. {
  5487. TestEventListeners listeners;
  5488. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
  5489. default_result_printer);
  5490. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
  5491. default_xml_printer);
  5492. listeners.Append(extra_listener);
  5493. }
  5494. EXPECT_TRUE(default_result_printer_is_destroyed);
  5495. EXPECT_TRUE(default_xml_printer_is_destroyed);
  5496. EXPECT_TRUE(extra_listener_is_destroyed);
  5497. }
  5498. // Tests that a listener Append'ed to a TestEventListeners list starts
  5499. // receiving events.
  5500. TEST(TestEventListenersTest, Append) {
  5501. int on_start_counter = 0;
  5502. bool is_destroyed = false;
  5503. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5504. {
  5505. TestEventListeners listeners;
  5506. listeners.Append(listener);
  5507. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5508. *UnitTest::GetInstance());
  5509. EXPECT_EQ(1, on_start_counter);
  5510. }
  5511. EXPECT_TRUE(is_destroyed);
  5512. }
  5513. // Tests that listeners receive events in the order they were appended to
  5514. // the list, except for *End requests, which must be received in the reverse
  5515. // order.
  5516. class SequenceTestingListener : public EmptyTestEventListener {
  5517. public:
  5518. SequenceTestingListener(std::vector<std::string>* vector, const char* id)
  5519. : vector_(vector), id_(id) {}
  5520. protected:
  5521. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
  5522. vector_->push_back(GetEventDescription("OnTestProgramStart"));
  5523. }
  5524. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
  5525. vector_->push_back(GetEventDescription("OnTestProgramEnd"));
  5526. }
  5527. virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
  5528. int /*iteration*/) {
  5529. vector_->push_back(GetEventDescription("OnTestIterationStart"));
  5530. }
  5531. virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  5532. int /*iteration*/) {
  5533. vector_->push_back(GetEventDescription("OnTestIterationEnd"));
  5534. }
  5535. private:
  5536. std::string GetEventDescription(const char* method) {
  5537. Message message;
  5538. message << id_ << "." << method;
  5539. return message.GetString();
  5540. }
  5541. std::vector<std::string>* vector_;
  5542. const char* const id_;
  5543. GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
  5544. };
  5545. TEST(EventListenerTest, AppendKeepsOrder) {
  5546. std::vector<std::string> vec;
  5547. TestEventListeners listeners;
  5548. listeners.Append(new SequenceTestingListener(&vec, "1st"));
  5549. listeners.Append(new SequenceTestingListener(&vec, "2nd"));
  5550. listeners.Append(new SequenceTestingListener(&vec, "3rd"));
  5551. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5552. *UnitTest::GetInstance());
  5553. ASSERT_EQ(3U, vec.size());
  5554. EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
  5555. EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
  5556. EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
  5557. vec.clear();
  5558. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
  5559. *UnitTest::GetInstance());
  5560. ASSERT_EQ(3U, vec.size());
  5561. EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
  5562. EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
  5563. EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
  5564. vec.clear();
  5565. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
  5566. *UnitTest::GetInstance(), 0);
  5567. ASSERT_EQ(3U, vec.size());
  5568. EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
  5569. EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
  5570. EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
  5571. vec.clear();
  5572. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
  5573. *UnitTest::GetInstance(), 0);
  5574. ASSERT_EQ(3U, vec.size());
  5575. EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
  5576. EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
  5577. EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
  5578. }
  5579. // Tests that a listener removed from a TestEventListeners list stops receiving
  5580. // events and is not deleted when the list is destroyed.
  5581. TEST(TestEventListenersTest, Release) {
  5582. int on_start_counter = 0;
  5583. bool is_destroyed = false;
  5584. // Although Append passes the ownership of this object to the list,
  5585. // the following calls release it, and we need to delete it before the
  5586. // test ends.
  5587. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5588. {
  5589. TestEventListeners listeners;
  5590. listeners.Append(listener);
  5591. EXPECT_EQ(listener, listeners.Release(listener));
  5592. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5593. *UnitTest::GetInstance());
  5594. EXPECT_TRUE(listeners.Release(listener) == NULL);
  5595. }
  5596. EXPECT_EQ(0, on_start_counter);
  5597. EXPECT_FALSE(is_destroyed);
  5598. delete listener;
  5599. }
  5600. // Tests that no events are forwarded when event forwarding is disabled.
  5601. TEST(EventListenerTest, SuppressEventForwarding) {
  5602. int on_start_counter = 0;
  5603. TestListener* listener = new TestListener(&on_start_counter, NULL);
  5604. TestEventListeners listeners;
  5605. listeners.Append(listener);
  5606. ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5607. TestEventListenersAccessor::SuppressEventForwarding(&listeners);
  5608. ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5609. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5610. *UnitTest::GetInstance());
  5611. EXPECT_EQ(0, on_start_counter);
  5612. }
  5613. // Tests that events generated by Google Test are not forwarded in
  5614. // death test subprocesses.
  5615. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
  5616. EXPECT_DEATH_IF_SUPPORTED({
  5617. GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
  5618. *GetUnitTestImpl()->listeners())) << "expected failure";},
  5619. "expected failure");
  5620. }
  5621. // Tests that a listener installed via SetDefaultResultPrinter() starts
  5622. // receiving events and is returned via default_result_printer() and that
  5623. // the previous default_result_printer is removed from the list and deleted.
  5624. TEST(EventListenerTest, default_result_printer) {
  5625. int on_start_counter = 0;
  5626. bool is_destroyed = false;
  5627. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5628. TestEventListeners listeners;
  5629. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5630. EXPECT_EQ(listener, listeners.default_result_printer());
  5631. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5632. *UnitTest::GetInstance());
  5633. EXPECT_EQ(1, on_start_counter);
  5634. // Replacing default_result_printer with something else should remove it
  5635. // from the list and destroy it.
  5636. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
  5637. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5638. EXPECT_TRUE(is_destroyed);
  5639. // After broadcasting an event the counter is still the same, indicating
  5640. // the listener is not in the list anymore.
  5641. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5642. *UnitTest::GetInstance());
  5643. EXPECT_EQ(1, on_start_counter);
  5644. }
  5645. // Tests that the default_result_printer listener stops receiving events
  5646. // when removed via Release and that is not owned by the list anymore.
  5647. TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
  5648. int on_start_counter = 0;
  5649. bool is_destroyed = false;
  5650. // Although Append passes the ownership of this object to the list,
  5651. // the following calls release it, and we need to delete it before the
  5652. // test ends.
  5653. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5654. {
  5655. TestEventListeners listeners;
  5656. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5657. EXPECT_EQ(listener, listeners.Release(listener));
  5658. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5659. EXPECT_FALSE(is_destroyed);
  5660. // Broadcasting events now should not affect default_result_printer.
  5661. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5662. *UnitTest::GetInstance());
  5663. EXPECT_EQ(0, on_start_counter);
  5664. }
  5665. // Destroying the list should not affect the listener now, too.
  5666. EXPECT_FALSE(is_destroyed);
  5667. delete listener;
  5668. }
  5669. // Tests that a listener installed via SetDefaultXmlGenerator() starts
  5670. // receiving events and is returned via default_xml_generator() and that
  5671. // the previous default_xml_generator is removed from the list and deleted.
  5672. TEST(EventListenerTest, default_xml_generator) {
  5673. int on_start_counter = 0;
  5674. bool is_destroyed = false;
  5675. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5676. TestEventListeners listeners;
  5677. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5678. EXPECT_EQ(listener, listeners.default_xml_generator());
  5679. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5680. *UnitTest::GetInstance());
  5681. EXPECT_EQ(1, on_start_counter);
  5682. // Replacing default_xml_generator with something else should remove it
  5683. // from the list and destroy it.
  5684. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
  5685. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5686. EXPECT_TRUE(is_destroyed);
  5687. // After broadcasting an event the counter is still the same, indicating
  5688. // the listener is not in the list anymore.
  5689. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5690. *UnitTest::GetInstance());
  5691. EXPECT_EQ(1, on_start_counter);
  5692. }
  5693. // Tests that the default_xml_generator listener stops receiving events
  5694. // when removed via Release and that is not owned by the list anymore.
  5695. TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
  5696. int on_start_counter = 0;
  5697. bool is_destroyed = false;
  5698. // Although Append passes the ownership of this object to the list,
  5699. // the following calls release it, and we need to delete it before the
  5700. // test ends.
  5701. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5702. {
  5703. TestEventListeners listeners;
  5704. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5705. EXPECT_EQ(listener, listeners.Release(listener));
  5706. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5707. EXPECT_FALSE(is_destroyed);
  5708. // Broadcasting events now should not affect default_xml_generator.
  5709. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5710. *UnitTest::GetInstance());
  5711. EXPECT_EQ(0, on_start_counter);
  5712. }
  5713. // Destroying the list should not affect the listener now, too.
  5714. EXPECT_FALSE(is_destroyed);
  5715. delete listener;
  5716. }
  5717. // Sanity tests to ensure that the alternative, verbose spellings of
  5718. // some of the macros work. We don't test them thoroughly as that
  5719. // would be quite involved. Since their implementations are
  5720. // straightforward, and they are rarely used, we'll just rely on the
  5721. // users to tell us when they are broken.
  5722. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
  5723. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
  5724. // GTEST_FAIL is the same as FAIL.
  5725. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
  5726. "An expected failure");
  5727. // GTEST_ASSERT_XY is the same as ASSERT_XY.
  5728. GTEST_ASSERT_EQ(0, 0);
  5729. EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
  5730. "An expected failure");
  5731. EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
  5732. "An expected failure");
  5733. GTEST_ASSERT_NE(0, 1);
  5734. GTEST_ASSERT_NE(1, 0);
  5735. EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
  5736. "An expected failure");
  5737. GTEST_ASSERT_LE(0, 0);
  5738. GTEST_ASSERT_LE(0, 1);
  5739. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
  5740. "An expected failure");
  5741. GTEST_ASSERT_LT(0, 1);
  5742. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
  5743. "An expected failure");
  5744. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
  5745. "An expected failure");
  5746. GTEST_ASSERT_GE(0, 0);
  5747. GTEST_ASSERT_GE(1, 0);
  5748. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
  5749. "An expected failure");
  5750. GTEST_ASSERT_GT(1, 0);
  5751. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
  5752. "An expected failure");
  5753. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
  5754. "An expected failure");
  5755. }
  5756. // Tests for internal utilities necessary for implementation of the universal
  5757. // printing.
  5758. // TODO([email protected]): Find a better home for them.
  5759. class ConversionHelperBase {};
  5760. class ConversionHelperDerived : public ConversionHelperBase {};
  5761. // Tests that IsAProtocolMessage<T>::value is a compile-time constant.
  5762. TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
  5763. GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
  5764. const_true);
  5765. GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
  5766. }
  5767. // Tests that IsAProtocolMessage<T>::value is true when T is
  5768. // proto2::Message or a sub-class of it.
  5769. TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
  5770. EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
  5771. EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
  5772. }
  5773. // Tests that IsAProtocolMessage<T>::value is false when T is neither
  5774. // ProtocolMessage nor a sub-class of it.
  5775. TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
  5776. EXPECT_FALSE(IsAProtocolMessage<int>::value);
  5777. EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
  5778. }
  5779. // Tests that CompileAssertTypesEqual compiles when the type arguments are
  5780. // equal.
  5781. TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
  5782. CompileAssertTypesEqual<void, void>();
  5783. CompileAssertTypesEqual<int*, int*>();
  5784. }
  5785. // Tests that RemoveReference does not affect non-reference types.
  5786. TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
  5787. CompileAssertTypesEqual<int, RemoveReference<int>::type>();
  5788. CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
  5789. }
  5790. // Tests that RemoveReference removes reference from reference types.
  5791. TEST(RemoveReferenceTest, RemovesReference) {
  5792. CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
  5793. CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
  5794. }
  5795. // Tests GTEST_REMOVE_REFERENCE_.
  5796. template <typename T1, typename T2>
  5797. void TestGTestRemoveReference() {
  5798. CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
  5799. }
  5800. TEST(RemoveReferenceTest, MacroVersion) {
  5801. TestGTestRemoveReference<int, int>();
  5802. TestGTestRemoveReference<const char, const char&>();
  5803. }
  5804. // Tests that RemoveConst does not affect non-const types.
  5805. TEST(RemoveConstTest, DoesNotAffectNonConstType) {
  5806. CompileAssertTypesEqual<int, RemoveConst<int>::type>();
  5807. CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
  5808. }
  5809. // Tests that RemoveConst removes const from const types.
  5810. TEST(RemoveConstTest, RemovesConst) {
  5811. CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
  5812. CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
  5813. CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
  5814. }
  5815. // Tests GTEST_REMOVE_CONST_.
  5816. template <typename T1, typename T2>
  5817. void TestGTestRemoveConst() {
  5818. CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
  5819. }
  5820. TEST(RemoveConstTest, MacroVersion) {
  5821. TestGTestRemoveConst<int, int>();
  5822. TestGTestRemoveConst<double&, double&>();
  5823. TestGTestRemoveConst<char, const char>();
  5824. }
  5825. // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
  5826. template <typename T1, typename T2>
  5827. void TestGTestRemoveReferenceAndConst() {
  5828. CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
  5829. }
  5830. TEST(RemoveReferenceToConstTest, Works) {
  5831. TestGTestRemoveReferenceAndConst<int, int>();
  5832. TestGTestRemoveReferenceAndConst<double, double&>();
  5833. TestGTestRemoveReferenceAndConst<char, const char>();
  5834. TestGTestRemoveReferenceAndConst<char, const char&>();
  5835. TestGTestRemoveReferenceAndConst<const char*, const char*>();
  5836. }
  5837. // Tests that AddReference does not affect reference types.
  5838. TEST(AddReferenceTest, DoesNotAffectReferenceType) {
  5839. CompileAssertTypesEqual<int&, AddReference<int&>::type>();
  5840. CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
  5841. }
  5842. // Tests that AddReference adds reference to non-reference types.
  5843. TEST(AddReferenceTest, AddsReference) {
  5844. CompileAssertTypesEqual<int&, AddReference<int>::type>();
  5845. CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
  5846. }
  5847. // Tests GTEST_ADD_REFERENCE_.
  5848. template <typename T1, typename T2>
  5849. void TestGTestAddReference() {
  5850. CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
  5851. }
  5852. TEST(AddReferenceTest, MacroVersion) {
  5853. TestGTestAddReference<int&, int>();
  5854. TestGTestAddReference<const char&, const char&>();
  5855. }
  5856. // Tests GTEST_REFERENCE_TO_CONST_.
  5857. template <typename T1, typename T2>
  5858. void TestGTestReferenceToConst() {
  5859. CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
  5860. }
  5861. TEST(GTestReferenceToConstTest, Works) {
  5862. TestGTestReferenceToConst<const char&, char>();
  5863. TestGTestReferenceToConst<const int&, const int>();
  5864. TestGTestReferenceToConst<const double&, double>();
  5865. TestGTestReferenceToConst<const std::string&, const std::string&>();
  5866. }
  5867. // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
  5868. TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
  5869. GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
  5870. GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
  5871. const_false);
  5872. }
  5873. // Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
  5874. // be implicitly converted to T2.
  5875. TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
  5876. EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
  5877. EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
  5878. EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
  5879. EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
  5880. EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
  5881. const ConversionHelperBase&>::value));
  5882. EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
  5883. ConversionHelperBase>::value));
  5884. }
  5885. // Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
  5886. // cannot be implicitly converted to T2.
  5887. TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
  5888. EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
  5889. EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
  5890. EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
  5891. EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
  5892. ConversionHelperDerived&>::value));
  5893. }
  5894. // Tests IsContainerTest.
  5895. class NonContainer {};
  5896. TEST(IsContainerTestTest, WorksForNonContainer) {
  5897. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
  5898. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
  5899. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
  5900. }
  5901. TEST(IsContainerTestTest, WorksForContainer) {
  5902. EXPECT_EQ(sizeof(IsContainer),
  5903. sizeof(IsContainerTest<std::vector<bool> >(0)));
  5904. EXPECT_EQ(sizeof(IsContainer),
  5905. sizeof(IsContainerTest<std::map<int, double> >(0)));
  5906. }
  5907. // Tests ArrayEq().
  5908. TEST(ArrayEqTest, WorksForDegeneratedArrays) {
  5909. EXPECT_TRUE(ArrayEq(5, 5L));
  5910. EXPECT_FALSE(ArrayEq('a', 0));
  5911. }
  5912. TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
  5913. // Note that a and b are distinct but compatible types.
  5914. const int a[] = { 0, 1 };
  5915. long b[] = { 0, 1 };
  5916. EXPECT_TRUE(ArrayEq(a, b));
  5917. EXPECT_TRUE(ArrayEq(a, 2, b));
  5918. b[0] = 2;
  5919. EXPECT_FALSE(ArrayEq(a, b));
  5920. EXPECT_FALSE(ArrayEq(a, 1, b));
  5921. }
  5922. TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
  5923. const char a[][3] = { "hi", "lo" };
  5924. const char b[][3] = { "hi", "lo" };
  5925. const char c[][3] = { "hi", "li" };
  5926. EXPECT_TRUE(ArrayEq(a, b));
  5927. EXPECT_TRUE(ArrayEq(a, 2, b));
  5928. EXPECT_FALSE(ArrayEq(a, c));
  5929. EXPECT_FALSE(ArrayEq(a, 2, c));
  5930. }
  5931. // Tests ArrayAwareFind().
  5932. TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
  5933. const char a[] = "hello";
  5934. EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
  5935. EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
  5936. }
  5937. TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
  5938. int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
  5939. const int b[2] = { 2, 3 };
  5940. EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
  5941. const int c[2] = { 6, 7 };
  5942. EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
  5943. }
  5944. // Tests CopyArray().
  5945. TEST(CopyArrayTest, WorksForDegeneratedArrays) {
  5946. int n = 0;
  5947. CopyArray('a', &n);
  5948. EXPECT_EQ('a', n);
  5949. }
  5950. TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
  5951. const char a[3] = "hi";
  5952. int b[3];
  5953. #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
  5954. CopyArray(a, &b);
  5955. EXPECT_TRUE(ArrayEq(a, b));
  5956. #endif
  5957. int c[3];
  5958. CopyArray(a, 3, c);
  5959. EXPECT_TRUE(ArrayEq(a, c));
  5960. }
  5961. TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
  5962. const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
  5963. int b[2][3];
  5964. #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
  5965. CopyArray(a, &b);
  5966. EXPECT_TRUE(ArrayEq(a, b));
  5967. #endif
  5968. int c[2][3];
  5969. CopyArray(a, 2, c);
  5970. EXPECT_TRUE(ArrayEq(a, c));
  5971. }
  5972. // Tests NativeArray.
  5973. TEST(NativeArrayTest, ConstructorFromArrayWorks) {
  5974. const int a[3] = { 0, 1, 2 };
  5975. NativeArray<int> na(a, 3, kReference);
  5976. EXPECT_EQ(3U, na.size());
  5977. EXPECT_EQ(a, na.begin());
  5978. }
  5979. TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
  5980. typedef int Array[2];
  5981. Array* a = new Array[1];
  5982. (*a)[0] = 0;
  5983. (*a)[1] = 1;
  5984. NativeArray<int> na(*a, 2, kCopy);
  5985. EXPECT_NE(*a, na.begin());
  5986. delete[] a;
  5987. EXPECT_EQ(0, na.begin()[0]);
  5988. EXPECT_EQ(1, na.begin()[1]);
  5989. // We rely on the heap checker to verify that na deletes the copy of
  5990. // array.
  5991. }
  5992. TEST(NativeArrayTest, TypeMembersAreCorrect) {
  5993. StaticAssertTypeEq<char, NativeArray<char>::value_type>();
  5994. StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
  5995. StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
  5996. StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
  5997. }
  5998. TEST(NativeArrayTest, MethodsWork) {
  5999. const int a[3] = { 0, 1, 2 };
  6000. NativeArray<int> na(a, 3, kCopy);
  6001. ASSERT_EQ(3U, na.size());
  6002. EXPECT_EQ(3, na.end() - na.begin());
  6003. NativeArray<int>::const_iterator it = na.begin();
  6004. EXPECT_EQ(0, *it);
  6005. ++it;
  6006. EXPECT_EQ(1, *it);
  6007. it++;
  6008. EXPECT_EQ(2, *it);
  6009. ++it;
  6010. EXPECT_EQ(na.end(), it);
  6011. EXPECT_TRUE(na == na);
  6012. NativeArray<int> na2(a, 3, kReference);
  6013. EXPECT_TRUE(na == na2);
  6014. const int b1[3] = { 0, 1, 1 };
  6015. const int b2[4] = { 0, 1, 2, 3 };
  6016. EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
  6017. EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
  6018. }
  6019. TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
  6020. const char a[2][3] = { "hi", "lo" };
  6021. NativeArray<char[3]> na(a, 2, kReference);
  6022. ASSERT_EQ(2U, na.size());
  6023. EXPECT_EQ(a, na.begin());
  6024. }
  6025. // Tests SkipPrefix().
  6026. TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
  6027. const char* const str = "hello";
  6028. const char* p = str;
  6029. EXPECT_TRUE(SkipPrefix("", &p));
  6030. EXPECT_EQ(str, p);
  6031. p = str;
  6032. EXPECT_TRUE(SkipPrefix("hell", &p));
  6033. EXPECT_EQ(str + 4, p);
  6034. }
  6035. TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
  6036. const char* const str = "world";
  6037. const char* p = str;
  6038. EXPECT_FALSE(SkipPrefix("W", &p));
  6039. EXPECT_EQ(str, p);
  6040. p = str;
  6041. EXPECT_FALSE(SkipPrefix("world!", &p));
  6042. EXPECT_EQ(str, p);
  6043. }