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.

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